Ravenveil commited on
Commit
8b8cf47
·
verified ·
1 Parent(s): 7534830

backup retry 06_ovow_code 2026-11-09 06:06:15 (part 2)

Browse files
This view is limited to 50 files because it contains too many changes.   See raw diff
Files changed (50) hide show
  1. OVOW/third_party/sam3/sam3.egg-info/PKG-INFO +525 -0
  2. OVOW/third_party/sam3/sam3.egg-info/SOURCES.txt +150 -0
  3. OVOW/third_party/sam3/sam3.egg-info/dependency_links.txt +1 -0
  4. OVOW/third_party/sam3/sam3.egg-info/requires.txt +49 -0
  5. OVOW/third_party/sam3/sam3.egg-info/top_level.txt +1 -0
  6. OVOW/third_party/sam3/sam3/train/data/torch_dataset.py +54 -0
  7. OVOW/third_party/sam3/sam3/train/loss/__init__.py +3 -0
  8. OVOW/third_party/sam3/sam3/train/loss/loss_fns.py +1324 -0
  9. OVOW/third_party/sam3/sam3/train/loss/mask_sampling.py +115 -0
  10. OVOW/third_party/sam3/sam3/train/loss/sam3_loss.py +203 -0
  11. OVOW/third_party/sam3/sam3/train/loss/sigmoid_focal_loss.py +323 -0
  12. OVOW/third_party/sam3/sam3/train/masks_ops.py +274 -0
  13. OVOW/third_party/sam3/sam3/train/matcher.py +807 -0
  14. OVOW/third_party/sam3/sam3/train/nms_helper.py +308 -0
  15. OVOW/third_party/sam3/sam3/train/optim/__init__.py +3 -0
  16. OVOW/third_party/sam3/sam3/train/optim/optimizer.py +499 -0
  17. OVOW/third_party/sam3/sam3/train/optim/schedulers.py +43 -0
  18. OVOW/third_party/sam3/sam3/train/train.py +338 -0
  19. OVOW/third_party/sam3/sam3/train/trainer.py +1189 -0
  20. OVOW/third_party/sam3/sam3/train/transforms/__init__.py +3 -0
  21. OVOW/third_party/sam3/sam3/train/transforms/basic.py +456 -0
  22. OVOW/third_party/sam3/sam3/train/transforms/basic_for_api.py +1395 -0
  23. OVOW/third_party/sam3/sam3/train/transforms/filter_query_transforms.py +607 -0
  24. OVOW/third_party/sam3/sam3/train/transforms/point_sampling.py +346 -0
  25. OVOW/third_party/sam3/sam3/train/transforms/segmentation.py +156 -0
  26. OVOW/third_party/sam3/sam3/train/utils/__init__.py +3 -0
  27. OVOW/third_party/sam3/sam3/train/utils/checkpoint_utils.py +360 -0
  28. OVOW/third_party/sam3/sam3/train/utils/distributed.py +587 -0
  29. OVOW/third_party/sam3/sam3/train/utils/logger.py +241 -0
  30. OVOW/third_party/sam3/sam3/train/utils/train_utils.py +286 -0
  31. OVOW/third_party/sam3/sam3/visualization_utils.py +943 -0
  32. OVOW/third_party/sam3/scripts/eval/gold/README.md +299 -0
  33. OVOW/third_party/sam3/scripts/eval/gold/eval_sam3.py +106 -0
  34. OVOW/third_party/sam3/scripts/eval/silver/CONFIG_FRAMES.yaml +24 -0
  35. OVOW/third_party/sam3/scripts/eval/silver/README.md +405 -0
  36. OVOW/third_party/sam3/scripts/eval/silver/download_fathomnet.py +64 -0
  37. OVOW/third_party/sam3/scripts/eval/silver/download_inaturalist.py +83 -0
  38. OVOW/third_party/sam3/scripts/eval/silver/download_preprocess_nga.py +142 -0
  39. OVOW/third_party/sam3/scripts/eval/silver/download_videos.py +261 -0
  40. OVOW/third_party/sam3/scripts/eval/silver/extract_frames.py +101 -0
  41. OVOW/third_party/sam3/scripts/eval/silver/fathomnet_image_uuids.json +0 -0
  42. OVOW/third_party/sam3/scripts/eval/silver/inaturalist_image_subset.json +0 -0
  43. OVOW/third_party/sam3/scripts/eval/silver/preprocess_silver_geode_bdd100k_food_rec.py +72 -0
  44. OVOW/third_party/sam3/scripts/eval/silver/utils.py +150 -0
  45. OVOW/third_party/sam3/scripts/eval/standalone_cgf1.py +50 -0
  46. OVOW/third_party/sam3/scripts/eval/veval/README.md +248 -0
  47. OVOW/third_party/sam3/scripts/eval/veval/__init__.py +3 -0
  48. OVOW/third_party/sam3/scripts/eval/veval/saco_yt1b_annot_update.py +138 -0
  49. OVOW/third_party/sam3/scripts/eval/veval/saco_yt1b_downloader.py +137 -0
  50. OVOW/third_party/sam3/scripts/eval/veval/saco_yt1b_frame_prep_util.py +267 -0
OVOW/third_party/sam3/sam3.egg-info/PKG-INFO ADDED
@@ -0,0 +1,525 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ Metadata-Version: 2.4
2
+ Name: sam3
3
+ Version: 0.1.0
4
+ Summary: SAM3 (Segment Anything Model 3) implementation
5
+ Author: Meta AI Research
6
+ License: SAM License
7
+ Last Updated: November 19, 2025
8
+
9
+ “Agreement” means the terms and conditions for use, reproduction, distribution and modification of the SAM Materials set forth herein.
10
+
11
+
12
+ “SAM Materials” means, collectively, Documentation and the models, software and algorithms, including machine-learning model code, trained model weights, inference-enabling code, training-enabling code, fine-tuning enabling code, and other elements of the foregoing distributed by Meta and made available under this Agreement.
13
+
14
+ “Documentation” means the specifications, manuals and documentation accompanying
15
+ SAM Materials distributed by Meta.
16
+
17
+
18
+ “Licensee” or “you” means you, or your employer or any other person or entity (if you are entering into this Agreement on such person or entity’s behalf), of the age required under applicable laws, rules or regulations to provide legal consent and that has legal authority to bind your employer or such other person or entity if you are entering in this Agreement on their behalf.
19
+
20
+
21
+ “Meta” or “we” means Meta Platforms Ireland Limited (if you are located in or, if you are an entity, your principal place of business is in the EEA or Switzerland) or Meta Platforms, Inc. (if you are located outside of the EEA or Switzerland).
22
+
23
+
24
+ “Sanctions” means any economic or trade sanctions or restrictions administered or enforced by the United States (including the Office of Foreign Assets Control of the U.S. Department of the Treasury (“OFAC”), the U.S. Department of State and the U.S. Department of Commerce), the United Nations, the European Union, or the United Kingdom.
25
+
26
+
27
+ “Trade Controls” means any of the following: Sanctions and applicable export and import controls.
28
+
29
+ By using or distributing any portion or element of the SAM Materials, you agree to be bound by this Agreement.
30
+
31
+
32
+ 1. License Rights and Redistribution.
33
+
34
+
35
+ a. Grant of Rights. You are granted a non-exclusive, worldwide, non-transferable and royalty-free limited license under Meta’s intellectual property or other rights owned by Meta embodied in the SAM Materials to use, reproduce, distribute, copy, create derivative works of, and make modifications to the SAM Materials.
36
+
37
+ b. Redistribution and Use.
38
+ i. Distribution of SAM Materials, and any derivative works thereof, are subject to the terms of this Agreement. If you distribute or make the SAM Materials, or any derivative works thereof, available to a third party, you may only do so under the terms of this Agreement and you shall provide a copy of this Agreement with any such SAM Materials.
39
+
40
+
41
+ ii. If you submit for publication the results of research you perform on, using, or otherwise in connection with SAM Materials, you must acknowledge the use of SAM Materials in your publication.
42
+
43
+
44
+ iii. Your use of the SAM Materials must comply with applicable laws and regulations, including Trade Control Laws and applicable privacy and data protection laws.
45
+ iv. Your use of the SAM Materials will not involve or encourage others to reverse engineer, decompile or discover the underlying components of the SAM Materials.
46
+ v. You are not the target of Trade Controls and your use of SAM Materials must comply with Trade Controls. You agree not to use, or permit others to use, SAM Materials for any activities subject to the International Traffic in Arms Regulations (ITAR) or end uses prohibited by Trade Controls, including those related to military or warfare purposes, nuclear industries or applications, espionage, or the development or use of guns or illegal weapons.
47
+ 2. User Support. Your use of the SAM Materials is done at your own discretion; Meta does not process any information nor provide any service in relation to such use. Meta is under no obligation to provide any support services for the SAM Materials. Any support provided is “as is”, “with all faults”, and without warranty of any kind.
48
+
49
+
50
+ 3. Disclaimer of Warranty. UNLESS REQUIRED BY APPLICABLE LAW, THE SAM MATERIALS AND ANY OUTPUT AND RESULTS THEREFROM ARE PROVIDED ON AN “AS IS” BASIS, WITHOUT WARRANTIES OF ANY KIND, AND META DISCLAIMS ALL WARRANTIES OF ANY KIND, BOTH EXPRESS AND IMPLIED, INCLUDING, WITHOUT LIMITATION, ANY WARRANTIES OF TITLE, NON-INFRINGEMENT, MERCHANTABILITY, OR FITNESS FOR A PARTICULAR PURPOSE. YOU ARE SOLELY RESPONSIBLE FOR DETERMINING THE APPROPRIATENESS OF USING OR REDISTRIBUTING THE SAM MATERIALS AND ASSUME ANY RISKS ASSOCIATED WITH YOUR USE OF THE SAM MATERIALS AND ANY OUTPUT AND RESULTS.
51
+
52
+ 4. Limitation of Liability. IN NO EVENT WILL META OR ITS AFFILIATES BE LIABLE UNDER ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, TORT, NEGLIGENCE, PRODUCTS LIABILITY, OR OTHERWISE, ARISING OUT OF THIS AGREEMENT, FOR ANY LOST PROFITS OR ANY DIRECT OR INDIRECT, SPECIAL, CONSEQUENTIAL, INCIDENTAL, EXEMPLARY OR PUNITIVE DAMAGES, EVEN IF META OR ITS AFFILIATES HAVE BEEN ADVISED OF THE POSSIBILITY OF ANY OF THE FOREGOING.
53
+
54
+ 5. Intellectual Property.
55
+
56
+
57
+ a. Subject to Meta’s ownership of SAM Materials and derivatives made by or for Meta, with respect to any derivative works and modifications of the SAM Materials that are made by you, as between you and Meta, you are and will be the owner of such derivative works and modifications.
58
+
59
+ b. If you institute litigation or other proceedings against Meta or any entity (including a cross-claim or counterclaim in a lawsuit) alleging that the SAM Materials, outputs or results, or any portion of any of the foregoing, constitutes infringement of intellectual property or other rights owned or licensable by you, then any licenses granted to you under this Agreement shall terminate as of the date such litigation or claim is filed or instituted. You will indemnify and hold harmless Meta from and against any claim by any third party arising out of or related to your use or distribution of the SAM Materials.
60
+
61
+ 6. Term and Termination. The term of this Agreement will commence upon your acceptance of this Agreement or access to the SAM Materials and will continue in full force and effect until terminated in accordance with the terms and conditions herein. Meta may terminate this Agreement if you are in breach of any term or condition of this Agreement. Upon termination of this Agreement, you shall delete and cease use of the SAM Materials. Sections 3, 4 and 7 shall survive the termination of this Agreement.
62
+
63
+ 7. Governing Law and Jurisdiction. This Agreement will be governed and construed under the laws of the State of California without regard to choice of law principles, and the UN Convention on Contracts for the International Sale of Goods does not apply to this Agreement. The courts of California shall have exclusive jurisdiction of any dispute arising out of this Agreement.
64
+
65
+
66
+ 8. Modifications and Amendments. Meta may modify this Agreement from time to time; provided that they are similar in spirit to the current version of the Agreement, but may differ in detail to address new problems or concerns. All such changes will be effective immediately. Your continued use of the SAM Materials after any modification to this Agreement constitutes your agreement to such modification. Except as provided in this Agreement, no modification or addition to any provision of this Agreement will be binding unless it is in writing and signed by an authorized representative of both you and Meta.
67
+
68
+ Project-URL: Homepage, https://github.com/facebookresearch/sam3
69
+ Project-URL: Bug Tracker, https://github.com/facebookresearch/sam3/issues
70
+ Classifier: Development Status :: 4 - Beta
71
+ Classifier: Intended Audience :: Science/Research
72
+ Classifier: License :: OSI Approved :: MIT License
73
+ Classifier: Programming Language :: Python :: 3
74
+ Classifier: Programming Language :: Python :: 3.8
75
+ Classifier: Programming Language :: Python :: 3.9
76
+ Classifier: Programming Language :: Python :: 3.10
77
+ Classifier: Programming Language :: Python :: 3.11
78
+ Classifier: Programming Language :: Python :: 3.12
79
+ Classifier: Topic :: Scientific/Engineering :: Artificial Intelligence
80
+ Requires-Python: >=3.8
81
+ Description-Content-Type: text/markdown
82
+ License-File: LICENSE
83
+ Requires-Dist: timm>=1.0.17
84
+ Requires-Dist: numpy<2,>=1.26
85
+ Requires-Dist: tqdm
86
+ Requires-Dist: ftfy==6.1.1
87
+ Requires-Dist: regex
88
+ Requires-Dist: iopath>=0.1.10
89
+ Requires-Dist: typing_extensions
90
+ Requires-Dist: huggingface_hub
91
+ Provides-Extra: dev
92
+ Requires-Dist: pytest; extra == "dev"
93
+ Requires-Dist: pytest-cov; extra == "dev"
94
+ Requires-Dist: black==24.2.0; extra == "dev"
95
+ Requires-Dist: ufmt==2.8.0; extra == "dev"
96
+ Requires-Dist: ruff-api==0.1.0; extra == "dev"
97
+ Requires-Dist: usort==1.0.2; extra == "dev"
98
+ Requires-Dist: gitpython==3.1.31; extra == "dev"
99
+ Requires-Dist: yt-dlp; extra == "dev"
100
+ Requires-Dist: pandas; extra == "dev"
101
+ Requires-Dist: opencv-python; extra == "dev"
102
+ Requires-Dist: pycocotools; extra == "dev"
103
+ Requires-Dist: numba; extra == "dev"
104
+ Requires-Dist: python-rapidjson; extra == "dev"
105
+ Provides-Extra: notebooks
106
+ Requires-Dist: matplotlib; extra == "notebooks"
107
+ Requires-Dist: jupyter; extra == "notebooks"
108
+ Requires-Dist: notebook; extra == "notebooks"
109
+ Requires-Dist: ipywidgets; extra == "notebooks"
110
+ Requires-Dist: ipycanvas; extra == "notebooks"
111
+ Requires-Dist: ipympl; extra == "notebooks"
112
+ Requires-Dist: pycocotools; extra == "notebooks"
113
+ Requires-Dist: decord; extra == "notebooks"
114
+ Requires-Dist: opencv-python; extra == "notebooks"
115
+ Requires-Dist: einops; extra == "notebooks"
116
+ Requires-Dist: scikit-image; extra == "notebooks"
117
+ Requires-Dist: scikit-learn; extra == "notebooks"
118
+ Provides-Extra: train
119
+ Requires-Dist: hydra-core; extra == "train"
120
+ Requires-Dist: submitit; extra == "train"
121
+ Requires-Dist: tensorboard; extra == "train"
122
+ Requires-Dist: zstandard; extra == "train"
123
+ Requires-Dist: scipy; extra == "train"
124
+ Requires-Dist: torchmetrics; extra == "train"
125
+ Requires-Dist: fvcore; extra == "train"
126
+ Requires-Dist: fairscale; extra == "train"
127
+ Requires-Dist: scikit-image; extra == "train"
128
+ Requires-Dist: scikit-learn; extra == "train"
129
+ Dynamic: license-file
130
+
131
+ # SAM 3: Segment Anything with Concepts
132
+
133
+ Meta Superintelligence Labs
134
+
135
+ [Nicolas Carion](https://www.nicolascarion.com/)\*,
136
+ [Laura Gustafson](https://scholar.google.com/citations?user=c8IpF9gAAAAJ&hl=en)\*,
137
+ [Yuan-Ting Hu](https://scholar.google.com/citations?user=E8DVVYQAAAAJ&hl=en)\*,
138
+ [Shoubhik Debnath](https://scholar.google.com/citations?user=fb6FOfsAAAAJ&hl=en)\*,
139
+ [Ronghang Hu](https://ronghanghu.com/)\*,
140
+ [Didac Suris](https://www.didacsuris.com/)\*,
141
+ [Chaitanya Ryali](https://scholar.google.com/citations?user=4LWx24UAAAAJ&hl=en)\*,
142
+ [Kalyan Vasudev Alwala](https://scholar.google.co.in/citations?user=m34oaWEAAAAJ&hl=en)\*,
143
+ [Haitham Khedr](https://hkhedr.com/)\*, Andrew Huang,
144
+ [Jie Lei](https://jayleicn.github.io/),
145
+ [Tengyu Ma](https://scholar.google.com/citations?user=VeTSl0wAAAAJ&hl=en),
146
+ [Baishan Guo](https://scholar.google.com/citations?user=BC5wDu8AAAAJ&hl=en),
147
+ Arpit Kalla, [Markus Marks](https://damaggu.github.io/),
148
+ [Joseph Greer](https://scholar.google.com/citations?user=guL96CkAAAAJ&hl=en),
149
+ Meng Wang, [Peize Sun](https://peizesun.github.io/),
150
+ [Roman Rädle](https://scholar.google.com/citations?user=Tpt57v0AAAAJ&hl=en),
151
+ [Triantafyllos Afouras](https://www.robots.ox.ac.uk/~afourast/),
152
+ [Effrosyni Mavroudi](https://scholar.google.com/citations?user=vYRzGGEAAAAJ&hl=en),
153
+ [Katherine Xu](https://k8xu.github.io/)°,
154
+ [Tsung-Han Wu](https://patrickthwu.com/)°,
155
+ [Yu Zhou](https://yu-bryan-zhou.github.io/)°,
156
+ [Liliane Momeni](https://scholar.google.com/citations?user=Lb-KgVYAAAAJ&hl=en)°,
157
+ [Rishi Hazra](https://rishihazra.github.io/)°,
158
+ [Shuangrui Ding](https://mark12ding.github.io/)°,
159
+ [Sagar Vaze](https://sgvaze.github.io/)°,
160
+ [Francois Porcher](https://scholar.google.com/citations?user=LgHZ8hUAAAAJ&hl=en)°,
161
+ [Feng Li](https://fengli-ust.github.io/)°,
162
+ [Siyuan Li](https://siyuanliii.github.io/)°,
163
+ [Aishwarya Kamath](https://ashkamath.github.io/)°,
164
+ [Ho Kei Cheng](https://hkchengrex.com/)°,
165
+ [Piotr Dollar](https://pdollar.github.io/)†,
166
+ [Nikhila Ravi](https://nikhilaravi.com/)†,
167
+ [Kate Saenko](https://ai.bu.edu/ksaenko.html)†,
168
+ [Pengchuan Zhang](https://pzzhang.github.io/pzzhang/)†,
169
+ [Christoph Feichtenhofer](https://feichtenhofer.github.io/)†
170
+
171
+ \* core contributor, ° intern, † project lead, order is random within groups
172
+
173
+ [[`Paper`](https://ai.meta.com/research/publications/sam-3-segment-anything-with-concepts/)]
174
+ [[`Project`](https://ai.meta.com/sam3)]
175
+ [[`Demo`](https://segment-anything.com/)]
176
+ [[`Blog`](https://ai.meta.com/blog/segment-anything-model-3/)]
177
+ [[`BibTeX`](#citing-sam-3)]
178
+
179
+ ![SAM 3 architecture](assets/model_diagram.png?raw=true) SAM 3 is a unified foundation model for promptable segmentation in images and videos. It can detect, segment, and track objects using text or visual prompts such as points, boxes, and masks. Compared to its predecessor [SAM 2](https://github.com/facebookresearch/sam2), SAM 3 introduces the ability to exhaustively segment all instances of an open-vocabulary concept specified by a short text phrase or exemplars. Unlike prior work, SAM 3 can handle a vastly larger set of open-vocabulary prompts. It achieves 75-80% of human performance on our new [SA-CO benchmark](https://github.com/facebookresearch/sam3?tab=readme-ov-file#sa-co-dataset) which contains 270K unique concepts, over 50 times more than existing benchmarks.
180
+
181
+ This breakthrough is driven by an innovative data engine that has automatically annotated over 4 million unique concepts, creating the largest high-quality open-vocabulary segmentation dataset to date. In addition, SAM 3 introduces a new model architecture featuring a presence token that improves discrimination between closely related text prompts (e.g., “a player in white” vs. “a player in red”), as well as a decoupled detector–tracker design that minimizes task interference and scales efficiently with data.
182
+
183
+ <p align="center">
184
+ <img src="assets/dog.gif" width=380 />
185
+ <img src="assets/player.gif" width=380 />
186
+ </p>
187
+
188
+ ## Installation
189
+
190
+ ### Prerequisites
191
+
192
+ - Python 3.12 or higher
193
+ - PyTorch 2.7 or higher
194
+ - CUDA-compatible GPU with CUDA 12.6 or higher
195
+
196
+ 1. **Create a new Conda environment:**
197
+
198
+ ```bash
199
+ conda create -n sam3 python=3.12
200
+ conda deactivate
201
+ conda activate sam3
202
+ ```
203
+
204
+ 2. **Install PyTorch with CUDA support:**
205
+
206
+ ```bash
207
+ pip install torch==2.7.0 torchvision torchaudio --index-url https://download.pytorch.org/whl/cu126
208
+ ```
209
+
210
+ 3. **Clone the repository and install the package:**
211
+
212
+ ```bash
213
+ git clone https://github.com/facebookresearch/sam3.git
214
+ cd sam3
215
+ pip install -e .
216
+ ```
217
+
218
+ 4. **Install additional dependencies for example notebooks or development:**
219
+
220
+ ```bash
221
+ # For running example notebooks
222
+ pip install -e ".[notebooks]"
223
+
224
+ # For development
225
+ pip install -e ".[train,dev]"
226
+ ```
227
+
228
+ ## Getting Started
229
+
230
+ ⚠️ Before using SAM 3, please request access to the checkpoints on the SAM 3
231
+ Hugging Face [repo](https://huggingface.co/facebook/sam3). Once accepted, you
232
+ need to be authenticated to download the checkpoints. You can do this by running
233
+ the following [steps](https://huggingface.co/docs/huggingface_hub/en/quick-start#authentication)
234
+ (e.g. `hf auth login` after generating an access token.)
235
+
236
+ ### Basic Usage
237
+
238
+ ```python
239
+ import torch
240
+ #################################### For Image ####################################
241
+ from PIL import Image
242
+ from sam3.model_builder import build_sam3_image_model
243
+ from sam3.model.sam3_image_processor import Sam3Processor
244
+ # Load the model
245
+ model = build_sam3_image_model()
246
+ processor = Sam3Processor(model)
247
+ # Load an image
248
+ image = Image.open("<YOUR_IMAGE_PATH.jpg>")
249
+ inference_state = processor.set_image(image)
250
+ # Prompt the model with text
251
+ output = processor.set_text_prompt(state=inference_state, prompt="<YOUR_TEXT_PROMPT>")
252
+
253
+ # Get the masks, bounding boxes, and scores
254
+ masks, boxes, scores = output["masks"], output["boxes"], output["scores"]
255
+
256
+ #################################### For Video ####################################
257
+
258
+ from sam3.model_builder import build_sam3_video_predictor
259
+
260
+ video_predictor = build_sam3_video_predictor()
261
+ video_path = "<YOUR_VIDEO_PATH>" # a JPEG folder or an MP4 video file
262
+ # Start a session
263
+ response = video_predictor.handle_request(
264
+ request=dict(
265
+ type="start_session",
266
+ resource_path=video_path,
267
+ )
268
+ )
269
+ response = video_predictor.handle_request(
270
+ request=dict(
271
+ type="add_prompt",
272
+ session_id=response["session_id"],
273
+ frame_index=0, # Arbitrary frame index
274
+ text="<YOUR_TEXT_PROMPT>",
275
+ )
276
+ )
277
+ output = response["outputs"]
278
+ ```
279
+
280
+ ## Examples
281
+
282
+ The `examples` directory contains notebooks demonstrating how to use SAM3 with
283
+ various types of prompts:
284
+
285
+ - [`sam3_image_predictor_example.ipynb`](examples/sam3_image_predictor_example.ipynb)
286
+ : Demonstrates how to prompt SAM 3 with text and visual box prompts on images.
287
+ - [`sam3_video_predictor_example.ipynb`](examples/sam3_video_predictor_example.ipynb)
288
+ : Demonstrates how to prompt SAM 3 with text prompts on videos, and doing
289
+ further interactive refinements with points.
290
+ - [`sam3_image_batched_inference.ipynb`](examples/sam3_image_batched_inference.ipynb)
291
+ : Demonstrates how to run batched inference with SAM 3 on images.
292
+ - [`sam3_agent.ipynb`](examples/sam3_agent.ipynb): Demonsterates the use of SAM
293
+ 3 Agent to segment complex text prompt on images.
294
+ - [`saco_gold_silver_vis_example.ipynb`](examples/saco_gold_silver_vis_example.ipynb)
295
+ : Shows a few examples from SA-Co image evaluation set.
296
+ - [`saco_veval_vis_example.ipynb`](examples/saco_veval_vis_example.ipynb) :
297
+ Shows a few examples from SA-Co video evaluation set.
298
+
299
+ There are additional notebooks in the examples directory that demonstrate how to
300
+ use SAM 3 for interactive instance segmentation in images and videos (SAM 1/2
301
+ tasks), or as a tool for an MLLM, and how to run evaluations on the SA-Co
302
+ dataset.
303
+
304
+ To run the Jupyter notebook examples:
305
+
306
+ ```bash
307
+ # Make sure you have the notebooks dependencies installed
308
+ pip install -e ".[notebooks]"
309
+
310
+ # Start Jupyter notebook
311
+ jupyter notebook examples/sam3_image_predictor_example.ipynb
312
+ ```
313
+
314
+ ## Model
315
+
316
+ SAM 3 consists of a detector and a tracker that share a vision encoder. It has 848M parameters. The
317
+ detector is a DETR-based model conditioned on text, geometry, and image
318
+ exemplars. The tracker inherits the SAM 2 transformer encoder-decoder
319
+ architecture, supporting video segmentation and interactive refinement.
320
+
321
+ ## Image Results
322
+
323
+ <div align="center">
324
+ <table style="min-width: 80%; border: 2px solid #ddd; border-collapse: collapse">
325
+ <thead>
326
+ <tr>
327
+ <th rowspan="3" style="border-right: 2px solid #ddd; padding: 12px 20px">Model</th>
328
+ <th colspan="3" style="text-align: center; border-right: 2px solid #ddd; padding: 12px 20px">Instance Segmentation</th>
329
+ <th colspan="5" style="text-align: center; padding: 12px 20px">Box Detection</th>
330
+ </tr>
331
+ <tr>
332
+ <th colspan="2" style="text-align: center; border-right: 1px solid #eee; padding: 12px 20px">LVIS</th>
333
+ <th style="text-align: center; border-right: 2px solid #ddd; padding: 12px 20px">SA-Co/Gold</th>
334
+ <th colspan="2" style="text-align: center; border-right: 1px solid #eee; padding: 12px 20px">LVIS</th>
335
+ <th colspan="2" style="text-align: center; border-right: 1px solid #eee; padding: 12px 20px">COCO</th>
336
+ <th style="text-align: center; padding: 12px 20px">SA-Co/Gold</th>
337
+ </tr>
338
+ <tr>
339
+ <th style="text-align: center; padding: 12px 20px">cgF1</th>
340
+ <th style="text-align: center; border-right: 1px solid #eee; padding: 12px 20px">AP</th>
341
+ <th style="text-align: center; border-right: 2px solid #ddd; padding: 12px 20px">cgF1</th>
342
+ <th style="text-align: center; padding: 12px 20px">cgF1</th>
343
+ <th style="text-align: center; border-right: 1px solid #eee; padding: 12px 20px">AP</th>
344
+ <th style="text-align: center; padding: 12px 20px">AP</th>
345
+ <th style="text-align: center; border-right: 1px solid #eee; padding: 12px 20px">AP<sub>o</sub>
346
+ </th>
347
+ <th style="text-align: center; padding: 12px 20px">cgF1</th>
348
+ </tr>
349
+ </thead>
350
+ <tbody>
351
+ <tr>
352
+ <td style="border-right: 2px solid #ddd; padding: 10px 20px">Human</td>
353
+ <td style="text-align: center; padding: 10px 20px">-</td>
354
+ <td style="text-align: center; border-right: 1px solid #eee; padding: 10px 20px">-</td>
355
+ <td style="text-align: center; border-right: 2px solid #ddd; padding: 10px 20px">72.8</td>
356
+ <td style="text-align: center; padding: 10px 20px">-</td>
357
+ <td style="text-align: center; border-right: 1px solid #eee; padding: 10px 20px">-</td>
358
+ <td style="text-align: center; padding: 10px 20px">-</td>
359
+ <td style="text-align: center; border-right: 1px solid #eee; padding: 10px 20px">-</td>
360
+ <td style="text-align: center; padding: 10px 20px">74.0</td>
361
+ </tr>
362
+ <tr>
363
+ <td style="border-right: 2px solid #ddd; padding: 10px 20px">OWLv2*</td>
364
+ <td style="text-align: center; padding: 10px 20px; color: #999">29.3</td>
365
+ <td style="text-align: center; border-right: 1px solid #eee; padding: 10px 20px; color: #999">43.4</td>
366
+ <td style="text-align: center; border-right: 2px solid #ddd; padding: 10px 20px">24.6</td>
367
+ <td style="text-align: center; padding: 10px 20px; color: #999">30.2</td>
368
+ <td style="text-align: center; border-right: 1px solid #eee; padding: 10px 20px; color: #999">45.5</td>
369
+ <td style="text-align: center; padding: 10px 20px">46.1</td>
370
+ <td style="text-align: center; border-right: 1px solid #eee; padding: 10px 20px">23.9</td>
371
+ <td style="text-align: center; padding: 10px 20px">24.5</td>
372
+ </tr>
373
+ <tr>
374
+ <td style="border-right: 2px solid #ddd; padding: 10px 20px">DINO-X</td>
375
+ <td style="text-align: center; padding: 10px 20px">-</td>
376
+ <td style="text-align: center; border-right: 1px solid #eee; padding: 10px 20px">38.5</td>
377
+ <td style="text-align: center; border-right: 2px solid #ddd; padding: 10px 20px">21.3</td>
378
+ <td style="text-align: center; padding: 10px 20px">-</td>
379
+ <td style="text-align: center; border-right: 1px solid #eee; padding: 10px 20px">52.4</td>
380
+ <td style="text-align: center; padding: 10px 20px">56.0</td>
381
+ <td style="text-align: center; border-right: 1px solid #eee; padding: 10px 20px">-</td>
382
+ <td style="text-align: center; padding: 10px 20px">22.5</td>
383
+ </tr>
384
+ <tr>
385
+ <td style="border-right: 2px solid #ddd; padding: 10px 20px">Gemini 2.5</td>
386
+ <td style="text-align: center; padding: 10px 20px">13.4</td>
387
+ <td style="text-align: center; border-right: 1px solid #eee; padding: 10px 20px">-</td>
388
+ <td style="text-align: center; border-right: 2px solid #ddd; padding: 10px 20px">13.0</td>
389
+ <td style="text-align: center; padding: 10px 20px">16.1</td>
390
+ <td style="text-align: center; border-right: 1px solid #eee; padding: 10px 20px">-</td>
391
+ <td style="text-align: center; padding: 10px 20px">-</td>
392
+ <td style="text-align: center; border-right: 1px solid #eee; padding: 10px 20px">-</td>
393
+ <td style="text-align: center; padding: 10px 20px">14.4</td>
394
+ </tr>
395
+ <tr style="border-top: 2px solid #b19c9cff">
396
+ <td style="border-right: 2px solid #ddd; padding: 10px 20px">SAM 3</td>
397
+ <td style="text-align: center; padding: 10px 20px">37.2</td>
398
+ <td style="text-align: center; border-right: 1px solid #eee; padding: 10px 20px">48.5</td>
399
+ <td style="text-align: center; border-right: 2px solid #ddd; padding: 10px 20px">54.1</td>
400
+ <td style="text-align: center; padding: 10px 20px">40.6</td>
401
+ <td style="text-align: center; border-right: 1px solid #eee; padding: 10px 20px">53.6</td>
402
+ <td style="text-align: center; padding: 10px 20px">56.4</td>
403
+ <td style="text-align: center; border-right: 1px solid #eee; padding: 10px 20px">55.7</td>
404
+ <td style="text-align: center; padding: 10px 20px">55.7</td>
405
+ </tr>
406
+ </tbody>
407
+ </table>
408
+
409
+ <p style="text-align: center; margin-top: 10px; font-size: 0.9em; color: #ddd;">* Partially trained on LVIS, AP<sub>o</sub> refers to COCO-O accuracy</p>
410
+
411
+ </div>
412
+
413
+ ## Video Results
414
+
415
+ <div align="center">
416
+ <table style="min-width: 80%; border: 2px solid #ddd; border-collapse: collapse">
417
+ <thead>
418
+ <tr>
419
+ <th rowspan="2" style="border-right: 2px solid #ddd; padding: 12px 20px">Model</th>
420
+ <th colspan="2" style="text-align: center; border-right: 1px solid #eee; padding: 12px 20px">SA-V test</th>
421
+ <th colspan="2" style="text-align: center; border-right: 1px solid #eee; padding: 12px 20px">YT-Temporal-1B test</th>
422
+ <th colspan="2" style="text-align: center; border-right: 1px solid #eee; padding: 12px 20px">SmartGlasses test</th>
423
+ <th style="text-align: center; border-right: 1px solid #eee; padding: 12px 20px">LVVIS test</th>
424
+ <th style="text-align: center; padding: 12px 20px">BURST test</th>
425
+ </tr>
426
+ <tr>
427
+ <th style="text-align: center; padding: 12px 20px">cgF1</th>
428
+ <th style="text-align: center; border-right: 1px solid #eee; padding: 12px 20px">pHOTA</th>
429
+ <th style="text-align: center; padding: 12px 20px">cgF1</th>
430
+ <th style="text-align: center; border-right: 1px solid #eee; padding: 12px 20px">pHOTA</th>
431
+ <th style="text-align: center; padding: 12px 20px">cgF1</th>
432
+ <th style="text-align: center; border-right: 1px solid #eee; padding: 12px 20px">pHOTA</th>
433
+ <th style="text-align: center; border-right: 1px solid #eee; padding: 12px 20px">mAP</th>
434
+ <th style="text-align: center; padding: 12px 20px">HOTA</th>
435
+ </tr>
436
+ </thead>
437
+ <tbody>
438
+ <tr>
439
+ <td style="border-right: 2px solid #ddd; padding: 10px 20px">Human</td>
440
+ <td style="text-align: center; padding: 10px 20px">53.1</td>
441
+ <td style="text-align: center; border-right: 1px solid #eee; padding: 10px 20px">70.5</td>
442
+ <td style="text-align: center; padding: 10px 20px">71.2</td>
443
+ <td style="text-align: center; border-right: 1px solid #eee; padding: 10px 20px">78.4</td>
444
+ <td style="text-align: center; padding: 10px 20px">58.5</td>
445
+ <td style="text-align: center; border-right: 1px solid #eee; padding: 10px 20px">72.3</td>
446
+ <td style="text-align: center; border-right: 1px solid #eee; padding: 10px 20px">-</td>
447
+ <td style="text-align: center; padding: 10px 20px">-</td>
448
+ </tr>
449
+ <tr style="border-top: 2px solid #b19c9cff">
450
+ <td style="border-right: 2px solid #ddd; padding: 10px 20px">SAM 3</td>
451
+ <td style="text-align: center; padding: 10px 20px">30.3</td>
452
+ <td style="text-align: center; border-right: 1px solid #eee; padding: 10px 20px">58.0</td>
453
+ <td style="text-align: center; padding: 10px 20px">50.8</td>
454
+ <td style="text-align: center; border-right: 1px solid #eee; padding: 10px 20px">69.9</td>
455
+ <td style="text-align: center; padding: 10px 20px">36.4</td>
456
+ <td style="text-align: center; border-right: 1px solid #eee; padding: 10px 20px">63.6</td>
457
+ <td style="text-align: center; border-right: 1px solid #eee; padding: 10px 20px">36.3</td>
458
+ <td style="text-align: center; padding: 10px 20px">44.5</td>
459
+ </tr>
460
+ </tbody>
461
+ </table>
462
+ </div>
463
+
464
+ ## SA-Co Dataset
465
+
466
+ We release 2 image benchmarks, [SA-Co/Gold](scripts/eval/gold/README.md) and
467
+ [SA-Co/Silver](scripts/eval/silver/README.md), and a video benchmark
468
+ [SA-Co/VEval](scripts/eval/veval/README.md). The datasets contain images (or videos) with annotated noun phrases. Each image/video and noun phrase pair is annotated with instance masks and unique IDs of each object matching the phrase. Phrases that have no matching objects (negative prompts) have no masks, shown in red font in the figure. See the linked READMEs for more details on how to download and run evaluations on the datasets.
469
+
470
+ * HuggingFace host: [SA-Co/Gold](https://huggingface.co/datasets/facebook/SACo-Gold), [SA-Co/Silver](https://huggingface.co/datasets/facebook/SACo-Silver) and [SA-Co/VEval](https://huggingface.co/datasets/facebook/SACo-VEval)
471
+ * Roboflow host: [SA-Co/Gold](https://universe.roboflow.com/sa-co-gold), [SA-Co/Silver](https://universe.roboflow.com/sa-co-silver) and [SA-Co/VEval](https://universe.roboflow.com/sa-co-veval)
472
+
473
+ ![SA-Co dataset](assets/sa_co_dataset.jpg?raw=true)
474
+
475
+ ## Development
476
+
477
+ To set up the development environment:
478
+
479
+ ```bash
480
+ pip install -e ".[dev,train]"
481
+ ```
482
+
483
+ To format the code:
484
+
485
+ ```bash
486
+ ufmt format .
487
+ ```
488
+
489
+ ## Contributing
490
+
491
+ See [contributing](CONTRIBUTING.md) and the
492
+ [code of conduct](CODE_OF_CONDUCT.md).
493
+
494
+ ## License
495
+
496
+ This project is licensed under the SAM License - see the [LICENSE](LICENSE) file
497
+ for details.
498
+
499
+ ## Acknowledgements
500
+
501
+ We would like to thank the following people for their contributions to the SAM 3 project: Alex He, Alexander Kirillov,
502
+ Alyssa Newcomb, Ana Paula Kirschner Mofarrej, Andrea Madotto, Andrew Westbury, Ashley Gabriel, Azita Shokpour,
503
+ Ben Samples, Bernie Huang, Carleigh Wood, Ching-Feng Yeh, Christian Puhrsch, Claudette Ward, Daniel Bolya,
504
+ Daniel Li, Facundo Figueroa, Fazila Vhora, George Orlin, Hanzi Mao, Helen Klein, Hu Xu, Ida Cheng, Jake Kinney,
505
+ Jiale Zhi, Jo Sampaio, Joel Schlosser, Justin Johnson, Kai Brown, Karen Bergan, Karla Martucci, Kenny Lehmann,
506
+ Maddie Mintz, Mallika Malhotra, Matt Ward, Michelle Chan, Michelle Restrepo, Miranda Hartley, Muhammad Maaz,
507
+ Nisha Deo, Peter Park, Phillip Thomas, Raghu Nayani, Rene Martinez Doehner, Robbie Adkins, Ross Girshik, Sasha
508
+ Mitts, Shashank Jain, Spencer Whitehead, Ty Toledano, Valentin Gabeur, Vincent Cho, Vivian Lee, William Ngan,
509
+ Xuehai He, Yael Yungster, Ziqi Pang, Ziyi Dou, Zoe Quake.
510
+
511
+ ## Citing SAM 3
512
+
513
+ If you use SAM 3 or the SA-Co dataset in your research, please use the following BibTeX entry.
514
+
515
+ ```bibtex
516
+ @misc{carion2025sam3segmentconcepts,
517
+ title={SAM 3: Segment Anything with Concepts},
518
+ author={Nicolas Carion and Laura Gustafson and Yuan-Ting Hu and Shoubhik Debnath and Ronghang Hu and Didac Suris and Chaitanya Ryali and Kalyan Vasudev Alwala and Haitham Khedr and Andrew Huang and Jie Lei and Tengyu Ma and Baishan Guo and Arpit Kalla and Markus Marks and Joseph Greer and Meng Wang and Peize Sun and Roman Rädle and Triantafyllos Afouras and Effrosyni Mavroudi and Katherine Xu and Tsung-Han Wu and Yu Zhou and Liliane Momeni and Rishi Hazra and Shuangrui Ding and Sagar Vaze and Francois Porcher and Feng Li and Siyuan Li and Aishwarya Kamath and Ho Kei Cheng and Piotr Dollár and Nikhila Ravi and Kate Saenko and Pengchuan Zhang and Christoph Feichtenhofer},
519
+ year={2025},
520
+ eprint={2511.16719},
521
+ archivePrefix={arXiv},
522
+ primaryClass={cs.CV},
523
+ url={https://arxiv.org/abs/2511.16719},
524
+ }
525
+ ```
OVOW/third_party/sam3/sam3.egg-info/SOURCES.txt ADDED
@@ -0,0 +1,150 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ LICENSE
2
+ MANIFEST.in
3
+ README.md
4
+ pyproject.toml
5
+ sam3/__init__.py
6
+ sam3/logger.py
7
+ sam3/model_builder.py
8
+ sam3/visualization_utils.py
9
+ sam3.egg-info/PKG-INFO
10
+ sam3.egg-info/SOURCES.txt
11
+ sam3.egg-info/dependency_links.txt
12
+ sam3.egg-info/requires.txt
13
+ sam3.egg-info/top_level.txt
14
+ sam3/agent/__init__.py
15
+ sam3/agent/agent_core.py
16
+ sam3/agent/client_llm.py
17
+ sam3/agent/client_sam3.py
18
+ sam3/agent/inference.py
19
+ sam3/agent/viz.py
20
+ sam3/agent/helpers/__init__.py
21
+ sam3/agent/helpers/boxes.py
22
+ sam3/agent/helpers/color_map.py
23
+ sam3/agent/helpers/keypoints.py
24
+ sam3/agent/helpers/mask_overlap_removal.py
25
+ sam3/agent/helpers/masks.py
26
+ sam3/agent/helpers/memory.py
27
+ sam3/agent/helpers/rle.py
28
+ sam3/agent/helpers/roi_align.py
29
+ sam3/agent/helpers/rotated_boxes.py
30
+ sam3/agent/helpers/som_utils.py
31
+ sam3/agent/helpers/visualizer.py
32
+ sam3/agent/helpers/zoom_in.py
33
+ sam3/assets/bpe_simple_vocab_16e6.txt.gz
34
+ sam3/eval/__init__.py
35
+ sam3/eval/cgf1_eval.py
36
+ sam3/eval/coco_eval.py
37
+ sam3/eval/coco_eval_offline.py
38
+ sam3/eval/coco_reindex.py
39
+ sam3/eval/coco_writer.py
40
+ sam3/eval/conversion_util.py
41
+ sam3/eval/demo_eval.py
42
+ sam3/eval/postprocessors.py
43
+ sam3/eval/saco_veval_eval.py
44
+ sam3/eval/saco_veval_evaluators.py
45
+ sam3/eval/ytvis_coco_wrapper.py
46
+ sam3/eval/ytvis_eval.py
47
+ sam3/eval/hota_eval_toolkit/__init__.py
48
+ sam3/eval/hota_eval_toolkit/run_ytvis_eval.py
49
+ sam3/eval/hota_eval_toolkit/trackeval/__init__.py
50
+ sam3/eval/hota_eval_toolkit/trackeval/_timing.py
51
+ sam3/eval/hota_eval_toolkit/trackeval/eval.py
52
+ sam3/eval/hota_eval_toolkit/trackeval/utils.py
53
+ sam3/eval/hota_eval_toolkit/trackeval/datasets/__init__.py
54
+ sam3/eval/hota_eval_toolkit/trackeval/datasets/_base_dataset.py
55
+ sam3/eval/hota_eval_toolkit/trackeval/datasets/tao_ow.py
56
+ sam3/eval/hota_eval_toolkit/trackeval/datasets/youtube_vis.py
57
+ sam3/eval/hota_eval_toolkit/trackeval/metrics/__init__.py
58
+ sam3/eval/hota_eval_toolkit/trackeval/metrics/_base_metric.py
59
+ sam3/eval/hota_eval_toolkit/trackeval/metrics/count.py
60
+ sam3/eval/hota_eval_toolkit/trackeval/metrics/hota.py
61
+ sam3/eval/teta_eval_toolkit/__init__.py
62
+ sam3/eval/teta_eval_toolkit/_timing.py
63
+ sam3/eval/teta_eval_toolkit/config.py
64
+ sam3/eval/teta_eval_toolkit/eval.py
65
+ sam3/eval/teta_eval_toolkit/utils.py
66
+ sam3/eval/teta_eval_toolkit/datasets/__init__.py
67
+ sam3/eval/teta_eval_toolkit/datasets/_base_dataset.py
68
+ sam3/eval/teta_eval_toolkit/datasets/coco.py
69
+ sam3/eval/teta_eval_toolkit/datasets/tao.py
70
+ sam3/eval/teta_eval_toolkit/metrics/__init__.py
71
+ sam3/eval/teta_eval_toolkit/metrics/_base_metric.py
72
+ sam3/eval/teta_eval_toolkit/metrics/teta.py
73
+ sam3/model/__init__.py
74
+ sam3/model/act_ckpt_utils.py
75
+ sam3/model/box_ops.py
76
+ sam3/model/data_misc.py
77
+ sam3/model/decoder.py
78
+ sam3/model/edt.py
79
+ sam3/model/encoder.py
80
+ sam3/model/geometry_encoders.py
81
+ sam3/model/io_utils.py
82
+ sam3/model/maskformer_segmentation.py
83
+ sam3/model/memory.py
84
+ sam3/model/model_misc.py
85
+ sam3/model/necks.py
86
+ sam3/model/position_encoding.py
87
+ sam3/model/sam1_task_predictor.py
88
+ sam3/model/sam3_image.py
89
+ sam3/model/sam3_image_processor.py
90
+ sam3/model/sam3_tracker_base.py
91
+ sam3/model/sam3_tracker_utils.py
92
+ sam3/model/sam3_tracking_predictor.py
93
+ sam3/model/sam3_video_base.py
94
+ sam3/model/sam3_video_inference.py
95
+ sam3/model/sam3_video_predictor.py
96
+ sam3/model/text_encoder_ve.py
97
+ sam3/model/tokenizer_ve.py
98
+ sam3/model/vitdet.py
99
+ sam3/model/vl_combiner.py
100
+ sam3/model/utils/__init__.py
101
+ sam3/model/utils/misc.py
102
+ sam3/model/utils/sam1_utils.py
103
+ sam3/model/utils/sam2_utils.py
104
+ sam3/perflib/__init__.py
105
+ sam3/perflib/associate_det_trk.py
106
+ sam3/perflib/compile.py
107
+ sam3/perflib/connected_components.py
108
+ sam3/perflib/fa3.py
109
+ sam3/perflib/masks_ops.py
110
+ sam3/perflib/nms.py
111
+ sam3/perflib/tests/tests.py
112
+ sam3/perflib/triton/connected_components.py
113
+ sam3/perflib/triton/nms.py
114
+ sam3/sam/__init__.py
115
+ sam3/sam/common.py
116
+ sam3/sam/mask_decoder.py
117
+ sam3/sam/prompt_encoder.py
118
+ sam3/sam/rope.py
119
+ sam3/sam/transformer.py
120
+ sam3/train/__init__.py
121
+ sam3/train/masks_ops.py
122
+ sam3/train/matcher.py
123
+ sam3/train/nms_helper.py
124
+ sam3/train/train.py
125
+ sam3/train/trainer.py
126
+ sam3/train/data/__init__.py
127
+ sam3/train/data/coco_json_loaders.py
128
+ sam3/train/data/collator.py
129
+ sam3/train/data/sam3_image_dataset.py
130
+ sam3/train/data/sam3_video_dataset.py
131
+ sam3/train/data/torch_dataset.py
132
+ sam3/train/loss/__init__.py
133
+ sam3/train/loss/loss_fns.py
134
+ sam3/train/loss/mask_sampling.py
135
+ sam3/train/loss/sam3_loss.py
136
+ sam3/train/loss/sigmoid_focal_loss.py
137
+ sam3/train/optim/__init__.py
138
+ sam3/train/optim/optimizer.py
139
+ sam3/train/optim/schedulers.py
140
+ sam3/train/transforms/__init__.py
141
+ sam3/train/transforms/basic.py
142
+ sam3/train/transforms/basic_for_api.py
143
+ sam3/train/transforms/filter_query_transforms.py
144
+ sam3/train/transforms/point_sampling.py
145
+ sam3/train/transforms/segmentation.py
146
+ sam3/train/utils/__init__.py
147
+ sam3/train/utils/checkpoint_utils.py
148
+ sam3/train/utils/distributed.py
149
+ sam3/train/utils/logger.py
150
+ sam3/train/utils/train_utils.py
OVOW/third_party/sam3/sam3.egg-info/dependency_links.txt ADDED
@@ -0,0 +1 @@
 
 
1
+
OVOW/third_party/sam3/sam3.egg-info/requires.txt ADDED
@@ -0,0 +1,49 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ timm>=1.0.17
2
+ numpy<2,>=1.26
3
+ tqdm
4
+ ftfy==6.1.1
5
+ regex
6
+ iopath>=0.1.10
7
+ typing_extensions
8
+ huggingface_hub
9
+
10
+ [dev]
11
+ pytest
12
+ pytest-cov
13
+ black==24.2.0
14
+ ufmt==2.8.0
15
+ ruff-api==0.1.0
16
+ usort==1.0.2
17
+ gitpython==3.1.31
18
+ yt-dlp
19
+ pandas
20
+ opencv-python
21
+ pycocotools
22
+ numba
23
+ python-rapidjson
24
+
25
+ [notebooks]
26
+ matplotlib
27
+ jupyter
28
+ notebook
29
+ ipywidgets
30
+ ipycanvas
31
+ ipympl
32
+ pycocotools
33
+ decord
34
+ opencv-python
35
+ einops
36
+ scikit-image
37
+ scikit-learn
38
+
39
+ [train]
40
+ hydra-core
41
+ submitit
42
+ tensorboard
43
+ zstandard
44
+ scipy
45
+ torchmetrics
46
+ fvcore
47
+ fairscale
48
+ scikit-image
49
+ scikit-learn
OVOW/third_party/sam3/sam3.egg-info/top_level.txt ADDED
@@ -0,0 +1 @@
 
 
1
+ sam3
OVOW/third_party/sam3/sam3/train/data/torch_dataset.py ADDED
@@ -0,0 +1,54 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ # Copyright (c) Meta Platforms, Inc. and affiliates. All Rights Reserved
2
+
3
+ # pyre-unsafe
4
+
5
+ from typing import Callable, Iterable, Optional
6
+
7
+ from torch.utils.data import DataLoader, Dataset, DistributedSampler, IterableDataset
8
+
9
+
10
+ class TorchDataset:
11
+ def __init__(
12
+ self,
13
+ dataset: Dataset,
14
+ batch_size: int,
15
+ num_workers: int,
16
+ shuffle: bool,
17
+ pin_memory: bool,
18
+ drop_last: bool,
19
+ collate_fn: Optional[Callable] = None,
20
+ worker_init_fn: Optional[Callable] = None,
21
+ enable_distributed_sampler=True,
22
+ ) -> None:
23
+ self.dataset = dataset
24
+ self.batch_size = batch_size
25
+ self.num_workers = num_workers
26
+ self.shuffle = shuffle
27
+ self.pin_memory = pin_memory
28
+ self.drop_last = drop_last
29
+ self.collate_fn = collate_fn
30
+ self.worker_init_fn = worker_init_fn
31
+ assert not isinstance(self.dataset, IterableDataset), "Not supported yet"
32
+ if enable_distributed_sampler:
33
+ self.sampler = DistributedSampler(self.dataset, shuffle=self.shuffle)
34
+ else:
35
+ self.sampler = None
36
+
37
+ def get_loader(self, epoch) -> Iterable:
38
+ if self.sampler:
39
+ self.sampler.set_epoch(epoch)
40
+ if hasattr(self.dataset, "epoch"):
41
+ self.dataset.epoch = epoch
42
+ if hasattr(self.dataset, "set_epoch"):
43
+ self.dataset.set_epoch(epoch)
44
+
45
+ return DataLoader(
46
+ self.dataset,
47
+ batch_size=self.batch_size,
48
+ num_workers=self.num_workers,
49
+ pin_memory=self.pin_memory,
50
+ drop_last=self.drop_last,
51
+ sampler=self.sampler,
52
+ collate_fn=self.collate_fn,
53
+ worker_init_fn=self.worker_init_fn,
54
+ )
OVOW/third_party/sam3/sam3/train/loss/__init__.py ADDED
@@ -0,0 +1,3 @@
 
 
 
 
1
+ # Copyright (c) Meta Platforms, Inc. and affiliates. All Rights Reserved
2
+
3
+ # pyre-unsafe
OVOW/third_party/sam3/sam3/train/loss/loss_fns.py ADDED
@@ -0,0 +1,1324 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ # Copyright (c) Meta Platforms, Inc. and affiliates. All Rights Reserved
2
+
3
+ # pyre-unsafe
4
+
5
+ import logging
6
+ import warnings
7
+
8
+ import torch
9
+ import torch.distributed
10
+ import torch.nn.functional as F
11
+ import torchmetrics
12
+ from sam3.model import box_ops
13
+ from sam3.model.data_misc import interpolate
14
+ from sam3.train.loss.sigmoid_focal_loss import (
15
+ triton_sigmoid_focal_loss,
16
+ triton_sigmoid_focal_loss_reduce,
17
+ )
18
+ from torch import nn
19
+
20
+ from .mask_sampling import (
21
+ calculate_uncertainty,
22
+ get_uncertain_point_coords_with_randomness,
23
+ point_sample,
24
+ )
25
+
26
+
27
+ CORE_LOSS_KEY = "core_loss"
28
+
29
+
30
+ def instance_masks_to_semantic_masks(
31
+ instance_masks: torch.Tensor, num_instances: torch.Tensor
32
+ ) -> torch.Tensor:
33
+ """This function converts instance masks to semantic masks.
34
+ It accepts a collapsed batch of instances masks (ie all instance masks are concatenated in a single tensor) and
35
+ the number of instances in each image of the batch.
36
+ It returns a mask with the same spatial dimensions as the input instance masks, where for each batch element the
37
+ semantic mask is the union of all the instance masks in the batch element.
38
+
39
+ If for a given batch element there are no instances (ie num_instances[i]==0), the corresponding semantic mask will be a tensor of zeros.
40
+
41
+ Args:
42
+ instance_masks (torch.Tensor): A tensor of shape (N, H, W) where N is the number of instances in the batch.
43
+ num_instances (torch.Tensor): A tensor of shape (B,) where B is the batch size. It contains the number of instances
44
+ in each image of the batch.
45
+
46
+ Returns:
47
+ torch.Tensor: A tensor of shape (B, H, W) where B is the batch size and H, W are the spatial dimensions of the
48
+ input instance masks.
49
+ """
50
+ if num_instances.sum() == 0:
51
+ # all negative batch, create a tensor of zeros (B, 1, 1)
52
+ return num_instances.unsqueeze(-1).unsqueeze(-1)
53
+
54
+ masks_per_query = torch.split(instance_masks, num_instances.tolist())
55
+
56
+ return torch.stack([torch.any(masks, dim=0) for masks in masks_per_query], dim=0)
57
+
58
+
59
+ @torch.no_grad()
60
+ def accuracy(output, target, topk=(1,)):
61
+ """Computes the precision@k for the specified values of k"""
62
+ if target.numel() == 0:
63
+ return [torch.zeros([], device=output.device)]
64
+ maxk = max(topk)
65
+ batch_size = target.size(0)
66
+
67
+ _, pred = output.topk(maxk, 1, True, True)
68
+ pred = pred.t()
69
+ correct = pred.eq(target.view(1, -1).expand_as(pred))
70
+
71
+ res = []
72
+ for k in topk:
73
+ correct_k = correct[:k].view(-1).float().sum(0)
74
+ res.append(correct_k.mul_(100.0 / batch_size))
75
+ return res
76
+
77
+
78
+ def dice_loss(inputs, targets, num_boxes, loss_on_multimask=False, reduce=True):
79
+ """
80
+ Compute the DICE loss, similar to generalized IOU for masks
81
+ Args:
82
+ inputs: A float tensor of arbitrary shape.
83
+ The predictions for each example.
84
+ targets: A float tensor with the same shape as inputs. Stores the binary
85
+ classification label for each element in inputs
86
+ (0 for the negative class and 1 for the positive class).
87
+ """
88
+ try:
89
+ loss = _dice_loss(inputs, targets, num_boxes, loss_on_multimask, reduce)
90
+ except torch.OutOfMemoryError:
91
+ logging.error("GPU OOM, computing dice loss on CPU")
92
+ # try to recover from GPU OOM by moving tensors to CPU and computing loss there
93
+ orig_device = inputs.device
94
+ inputs = inputs.cpu()
95
+ targets = targets.cpu()
96
+ if isinstance(num_boxes, torch.Tensor):
97
+ num_boxes = num_boxes.cpu()
98
+ loss = _dice_loss(inputs, targets, num_boxes, loss_on_multimask, reduce)
99
+ loss = loss.to(orig_device)
100
+
101
+ return loss
102
+
103
+
104
+ def _dice_loss(inputs, targets, num_boxes, loss_on_multimask=False, reduce=True):
105
+ inputs = inputs.sigmoid()
106
+ if loss_on_multimask:
107
+ # inputs and targets are [N, M, H, W] where M corresponds to multiple predicted masks
108
+ assert inputs.dim() == 4 and targets.dim() == 4
109
+ # flatten spatial dimension while keeping multimask channel dimension
110
+ inputs = inputs.flatten(2)
111
+ targets = targets.flatten(2)
112
+ numerator = 2 * (inputs * targets).sum(-1)
113
+ else:
114
+ inputs = inputs.flatten(1)
115
+ numerator = 2 * (inputs * targets).sum(1)
116
+ denominator = inputs.sum(-1) + targets.sum(-1)
117
+ loss = 1 - (numerator + 1) / (denominator + 1)
118
+ if loss_on_multimask:
119
+ return loss / num_boxes
120
+ if not reduce:
121
+ return loss
122
+ return loss.sum() / num_boxes
123
+
124
+
125
+ def sigmoid_focal_loss(
126
+ inputs,
127
+ targets,
128
+ num_boxes,
129
+ alpha: float = 0.25,
130
+ gamma: float = 2,
131
+ loss_on_multimask=False,
132
+ reduce=True,
133
+ triton=True,
134
+ ):
135
+ """
136
+ Loss used in RetinaNet for dense detection: https://arxiv.org/abs/1708.02002.
137
+ Args:
138
+ inputs: A float tensor of arbitrary shape.
139
+ The predictions for each example.
140
+ targets: A float tensor with the same shape as inputs. Stores the binary
141
+ classification label for each element in inputs
142
+ (0 for the negative class and 1 for the positive class).
143
+ alpha: (optional) Weighting factor in range (0,1) to balance
144
+ positive vs negative examples. Default = -1 (no weighting).
145
+ gamma: Exponent of the modulating factor (1 - p_t) to
146
+ balance easy vs hard examples.
147
+ Returns:
148
+ Loss tensor
149
+ """
150
+ if not (0 <= alpha <= 1) and triton:
151
+ raise RuntimeError(f"Alpha should be in [0,1], got {alpha}")
152
+ if triton:
153
+ if reduce and not loss_on_multimask:
154
+ loss = triton_sigmoid_focal_loss_reduce(inputs, targets, alpha, gamma)
155
+ return loss / (num_boxes * inputs.shape[1])
156
+
157
+ loss = triton_sigmoid_focal_loss(inputs, targets, alpha, gamma)
158
+ else:
159
+ prob = inputs.sigmoid()
160
+ ce_loss = F.binary_cross_entropy_with_logits(inputs, targets, reduction="none")
161
+ p_t = prob * targets + (1 - prob) * (1 - targets)
162
+ loss = ce_loss * ((1 - p_t) ** gamma)
163
+
164
+ if alpha >= 0:
165
+ alpha_t = alpha * targets + (1 - alpha) * (1 - targets)
166
+ loss = alpha_t * loss
167
+
168
+ if not reduce:
169
+ return loss
170
+
171
+ if loss_on_multimask:
172
+ # loss is [N, M, H, W] where M corresponds to multiple predicted masks
173
+ assert loss.dim() == 4
174
+ return loss.flatten(2).mean(-1) / num_boxes # average over spatial dims
175
+ return loss.mean(1).sum() / num_boxes
176
+
177
+
178
+ def iou_loss(
179
+ inputs, targets, pred_ious, num_boxes, loss_on_multimask=False, use_l1_loss=False
180
+ ):
181
+ """MSE loss between predicted IoUs and actual IoUs between inputs and targets."""
182
+ assert inputs.dim() == 4 and targets.dim() == 4
183
+ pred_mask = inputs.flatten(2) > 0
184
+ gt_mask = targets.flatten(2) > 0
185
+ area_i = torch.sum(pred_mask & gt_mask, dim=-1).float()
186
+ area_u = torch.sum(pred_mask | gt_mask, dim=-1).float()
187
+ actual_ious = area_i / torch.clamp(area_u, min=1.0)
188
+
189
+ if use_l1_loss:
190
+ loss = F.l1_loss(pred_ious, actual_ious, reduction="none")
191
+ else:
192
+ loss = F.mse_loss(pred_ious, actual_ious, reduction="none")
193
+ if loss_on_multimask:
194
+ return loss / num_boxes
195
+ return loss.sum() / num_boxes
196
+
197
+
198
+ @torch.jit.script
199
+ def _contrastive_align(logits, positive_map):
200
+ positive_logits = -logits.masked_fill(~positive_map, 0)
201
+ negative_logits = logits # .masked_fill(positive_map, -1000000)
202
+
203
+ boxes_with_pos = positive_map.any(2)
204
+ pos_term = positive_logits.sum(2)
205
+ neg_term = negative_logits.logsumexp(2)
206
+
207
+ nb_pos = positive_map.sum(2) + 1e-6
208
+
209
+ box_to_token_loss = (
210
+ (pos_term / nb_pos + neg_term).masked_fill(~boxes_with_pos, 0).sum()
211
+ )
212
+
213
+ tokens_with_pos = positive_map.any(1)
214
+ pos_term = positive_logits.sum(1)
215
+ neg_term = negative_logits.logsumexp(1)
216
+
217
+ nb_pos = positive_map.sum(1) + 1e-6
218
+
219
+ tokens_to_boxes_loss = (
220
+ (pos_term / nb_pos + neg_term).masked_fill(~tokens_with_pos, 0).sum()
221
+ )
222
+ return (box_to_token_loss + tokens_to_boxes_loss) / 2
223
+
224
+
225
+ def _get_src_permutation_idx(indices):
226
+ # permute predictions following indices
227
+ batch_idx = torch.cat(
228
+ [torch.full_like(src, i) for i, (src, _) in enumerate(indices)]
229
+ )
230
+ src_idx = torch.cat([src for (src, _) in indices])
231
+ return batch_idx, src_idx
232
+
233
+
234
+ class LossWithWeights(nn.Module):
235
+ def __init__(self, weight_dict, compute_aux, supports_o2m_loss=True):
236
+ super().__init__()
237
+ # weights for each computed loss key (those losses not in weight_dict
238
+ # will not be aggregated in the final reduced core loss)
239
+ self.weight_dict = weight_dict if weight_dict is not None else {}
240
+ # whether this loss will be applied on auxiliary outputs
241
+ self.compute_aux = compute_aux
242
+ self.supports_o2m_loss = supports_o2m_loss
243
+ self.target_keys = []
244
+
245
+ def forward(self, *args, is_aux=False, **kwargs):
246
+ if is_aux and not self.compute_aux:
247
+ return {CORE_LOSS_KEY: 0.0}
248
+ losses = self.get_loss(*args, **kwargs)
249
+ losses[CORE_LOSS_KEY] = self.reduce_loss(losses)
250
+ return losses
251
+
252
+ def get_loss(self, **kwargs):
253
+ raise NotImplementedError()
254
+
255
+ def reduce_loss(self, losses):
256
+ reduced_loss = 0.0
257
+ for loss_key, weight in self.weight_dict.items():
258
+ if loss_key not in losses:
259
+ raise ValueError(f"{type(self)} doesn't compute {loss_key}")
260
+ if weight != 0:
261
+ reduced_loss += losses[loss_key] * weight
262
+
263
+ return reduced_loss
264
+
265
+
266
+ class IABCEMdetr(LossWithWeights):
267
+ def __init__(
268
+ self,
269
+ pos_weight,
270
+ weight_dict=None,
271
+ compute_aux=True,
272
+ gamma=0,
273
+ weak_loss=True,
274
+ alpha=0.25,
275
+ pad_n_queries=None,
276
+ pad_scale_pos=1.0,
277
+ use_separate_loss_for_det_and_trk=False,
278
+ num_det_queries=None,
279
+ det_exhaustive_loss_scale_pos=1.0,
280
+ det_exhaustive_loss_scale_neg=1.0,
281
+ det_non_exhaustive_loss_scale_pos=1.0,
282
+ det_non_exhaustive_loss_scale_neg=1.0,
283
+ trk_loss_scale_pos=1.0,
284
+ trk_loss_scale_neg=1.0,
285
+ no_loss_for_fp_propagation=False,
286
+ apply_loss_to_det_queries_in_video_grounding=True,
287
+ use_presence=False,
288
+ use_presence_semgseg=False, # If True, use presence scores from the semgseg head.
289
+ presence_alpha=0.5,
290
+ presence_gamma=0.0,
291
+ pos_focal: bool = False, # for box scores, use focal loss for positives as well
292
+ ):
293
+ super().__init__(weight_dict, compute_aux)
294
+ self.pos_weight = pos_weight
295
+ self.gamma = gamma
296
+ self.weak_loss = weak_loss
297
+ self.alpha = alpha
298
+ self.target_keys.append("boxes_xyxy")
299
+ self.no_loss_for_fp_propagation = no_loss_for_fp_propagation
300
+ if self.weak_loss:
301
+ self.target_keys.append("is_exhaustive")
302
+ # NOTE: This is hacky solution to have the same CE loss scale across datasets where the model might predict different number of object queries for different tasks.
303
+ # If not None, we assume there are a total pad_n_queries object queries.
304
+ # For example, if the model predicts only 1 object query and pad_n_queries=100, we pad the predictions with 99 zero preds.
305
+ # Currently this only affects the BCE loss and not the F1 score.
306
+ self.pad_n_queries = pad_n_queries
307
+ self.pad_scale_pos = pad_scale_pos
308
+ if self.pad_scale_pos != 1.0:
309
+ assert self.pad_n_queries is not None
310
+ # whether to use presence scores
311
+ self.use_presence = use_presence
312
+ self.use_presence_semgseg = use_presence_semgseg
313
+ if self.use_presence_semgseg:
314
+ assert self.use_presence
315
+ self.presence_alpha = presence_alpha
316
+ self.presence_gamma = presence_gamma
317
+ self.pos_focal = pos_focal
318
+
319
+ # Decoupled loss for detection and tracking queries
320
+ self.apply_loss_to_det_queries_in_video_grounding = (
321
+ apply_loss_to_det_queries_in_video_grounding
322
+ )
323
+ self.use_separate_loss_for_det_and_trk = use_separate_loss_for_det_and_trk
324
+ if num_det_queries is not None:
325
+ logging.warning("note: it's not needed to set num_det_queries anymore")
326
+ if self.use_separate_loss_for_det_and_trk:
327
+ assert not self.weak_loss, (
328
+ "Do not use weak_loss in this case -- set separate loss for detection and tracking queries instead"
329
+ )
330
+ self.det_exhaustive_loss_scale_pos = det_exhaustive_loss_scale_pos
331
+ self.det_exhaustive_loss_scale_neg = det_exhaustive_loss_scale_neg
332
+ self.det_non_exhaustive_loss_scale_pos = det_non_exhaustive_loss_scale_pos
333
+ self.det_non_exhaustive_loss_scale_neg = det_non_exhaustive_loss_scale_neg
334
+ self.trk_loss_scale_pos = trk_loss_scale_pos
335
+ self.trk_loss_scale_neg = trk_loss_scale_neg
336
+ else:
337
+ assert (
338
+ det_exhaustive_loss_scale_pos == 1.0
339
+ and det_exhaustive_loss_scale_neg == 1.0
340
+ and det_non_exhaustive_loss_scale_pos == 1.0
341
+ and det_non_exhaustive_loss_scale_neg == 1.0
342
+ and trk_loss_scale_pos == 1.0
343
+ and trk_loss_scale_neg == 1.0
344
+ ), (
345
+ "If not using separate loss for detection and tracking queries, separate detection and tracking loss scales should all be 1.0"
346
+ )
347
+
348
+ def get_loss(self, outputs, targets, indices, num_boxes):
349
+ assert len(outputs["pred_logits"].shape) > 2, "Incorrect predicted logits shape"
350
+ assert outputs["pred_logits"].shape[-1] == 1, "Incorrect predicted logits shape"
351
+ src_logits = outputs["pred_logits"].squeeze(-1)
352
+ prob = src_logits.sigmoid()
353
+
354
+ with torch.no_grad():
355
+ target_classes = torch.full(
356
+ src_logits.shape[:2],
357
+ 0,
358
+ dtype=torch.float,
359
+ device=src_logits.device,
360
+ )
361
+ target_classes[(indices[0], indices[1])] = 1
362
+ src_boxes_xyxy = outputs["pred_boxes_xyxy"][(indices[0], indices[1])]
363
+ target_boxes_giou = (
364
+ targets["boxes_xyxy"][indices[2]]
365
+ if indices[2] is not None
366
+ else targets["boxes_xyxy"]
367
+ )
368
+
369
+ iou = box_ops.fast_diag_box_iou(src_boxes_xyxy, target_boxes_giou)
370
+ t = prob[(indices[0], indices[1])] ** self.alpha * iou ** (1 - self.alpha)
371
+ t = torch.clamp(t, 0.01).detach()
372
+ positive_target_classes = target_classes.clone()
373
+ positive_target_classes[(indices[0], indices[1])] = t
374
+
375
+ # Soft loss on positives
376
+ if self.pos_focal:
377
+ loss_bce = sigmoid_focal_loss(
378
+ src_logits.contiguous(),
379
+ positive_target_classes,
380
+ num_boxes=1,
381
+ alpha=0.5,
382
+ gamma=self.gamma,
383
+ reduce=False,
384
+ )
385
+ else:
386
+ loss_bce = F.binary_cross_entropy_with_logits(
387
+ src_logits, positive_target_classes, reduction="none"
388
+ )
389
+ loss_bce = loss_bce * target_classes * self.pos_weight
390
+
391
+ if (
392
+ self.pad_n_queries is not None
393
+ and isinstance(self.pad_n_queries, int)
394
+ and loss_bce.size(1) < self.pad_n_queries
395
+ ):
396
+ loss_bce = loss_bce * self.pad_scale_pos
397
+ # Negatives
398
+ loss_bce = loss_bce + F.binary_cross_entropy_with_logits(
399
+ src_logits, target_classes, reduction="none"
400
+ ) * (1 - target_classes) * (prob**self.gamma)
401
+
402
+ # Optionally, not applying IABCEMdetr loss to detection queries in video.
403
+ is_video_grounding = outputs.get("is_video_grounding_batch", False)
404
+ if is_video_grounding and not self.apply_loss_to_det_queries_in_video_grounding:
405
+ Q_det = outputs["Q_det"]
406
+ loss_bce[:, :Q_det] *= 0.0
407
+ presence_loss = torch.tensor(0.0, device=src_logits.device)
408
+ presence_dec_acc = torch.tensor(0.0, device=src_logits.device)
409
+ if self.use_presence:
410
+ # no classifiction loss for individual tokens if no target gt
411
+ # cannot directly use targets["num_boxes"] to check if some
412
+ # GT box exists as there may be dummy boxes for "invisible objects"
413
+ # in video grounding data
414
+
415
+ gt_padded_object_ids = targets["object_ids_padded"] # (B, H)
416
+ gt_padded_boxes = targets["boxes_padded"] # (B, H, 4) shape, CxCyWH
417
+ gt_padded_is_visible = (
418
+ (gt_padded_object_ids >= 0)
419
+ & (gt_padded_boxes[..., 2] > 0) # width > 0
420
+ & (gt_padded_boxes[..., 3] > 0) # height > 0
421
+ )
422
+ keep_loss = (gt_padded_is_visible.sum(dim=-1)[..., None] != 0).float()
423
+
424
+ loss_bce = loss_bce * keep_loss
425
+
426
+ if self.use_presence_semgseg:
427
+ # no loss here, has it's own separate loss computation
428
+ assert "presence_logit_dec" not in outputs
429
+ elif "presence_logit_dec" in outputs:
430
+ presence_logits = outputs["presence_logit_dec"].view_as(keep_loss)
431
+ bs = presence_logits.shape[0]
432
+ presence_loss = sigmoid_focal_loss(
433
+ presence_logits,
434
+ keep_loss,
435
+ # not num_boxes, but we'll use it to normalize by bs
436
+ num_boxes=bs,
437
+ alpha=self.presence_alpha,
438
+ gamma=self.presence_gamma,
439
+ )
440
+ pred = (presence_logits.sigmoid() > 0.5).float()
441
+ presence_dec_acc = (pred == keep_loss).float().mean()
442
+ else:
443
+ # for o2m, nothing to do
444
+ pass
445
+
446
+ if self.weak_loss:
447
+ assert not self.use_separate_loss_for_det_and_trk, (
448
+ "Do not use weak_loss in this case -- set separate loss for detection and tracking queries instead"
449
+ )
450
+
451
+ # nullify the negative loss for the non-exhaustive classes
452
+ assert loss_bce.shape[0] == targets["is_exhaustive"].shape[0]
453
+ assert targets["is_exhaustive"].ndim == 1
454
+
455
+ loss_mask = (~targets["is_exhaustive"]).view(-1, 1).expand_as(loss_bce)
456
+ # restrict the mask to the negative supervision
457
+ loss_mask = loss_mask & (target_classes < 0.5)
458
+ loss_mask = ~loss_mask
459
+ # Mask the loss
460
+ loss_bce = loss_bce * loss_mask.float()
461
+ # Average
462
+ loss_bce = loss_bce.sum() / (loss_mask.sum() + 1e-6)
463
+ else:
464
+ # apply separate loss weights to detection and tracking queries
465
+ if self.use_separate_loss_for_det_and_trk:
466
+ Q_det = outputs["Q_det"]
467
+ assert loss_bce.size(1) >= Q_det
468
+ is_positive = target_classes > 0.5
469
+ is_positive_det = is_positive[:, :Q_det]
470
+ is_positive_trk = is_positive[:, Q_det:]
471
+ assert loss_bce.size(0) == targets["is_exhaustive"].size(0)
472
+ is_exhaustive = targets["is_exhaustive"].unsqueeze(1).bool()
473
+ loss_scales = torch.zeros_like(loss_bce)
474
+ # detection query loss weights
475
+ loss_scales[:, :Q_det] = (
476
+ (is_exhaustive & is_positive_det).float()
477
+ * self.det_exhaustive_loss_scale_pos
478
+ + (is_exhaustive & ~is_positive_det).float()
479
+ * self.det_exhaustive_loss_scale_neg
480
+ + (~is_exhaustive & is_positive_det).float()
481
+ * self.det_non_exhaustive_loss_scale_pos
482
+ + (~is_exhaustive & ~is_positive_det).float()
483
+ * self.det_non_exhaustive_loss_scale_neg
484
+ )
485
+ # tracking query weights
486
+ loss_scales[:, Q_det:] = (
487
+ is_positive_trk.float() * self.trk_loss_scale_pos
488
+ + (~is_positive_trk).float() * self.trk_loss_scale_neg
489
+ )
490
+ # apply the loss weights
491
+
492
+ # if the id is -2 means it is a fp propagation , we don't apply the loss to them
493
+ if self.no_loss_for_fp_propagation:
494
+ is_original_queries = outputs["pred_old_obj_ids"] != -2
495
+ loss_scales *= (is_exhaustive | is_original_queries).float()
496
+
497
+ loss_bce = loss_bce * loss_scales
498
+
499
+ if self.pad_n_queries is None or loss_bce.size(1) >= self.pad_n_queries:
500
+ loss_bce = loss_bce.mean()
501
+ else:
502
+ assert isinstance(self.pad_n_queries, int)
503
+ assert loss_bce.size(1) < self.pad_n_queries, (
504
+ f"The number of predictions is more than the expected total after padding. Got {loss_bce.size(1)} predictions."
505
+ )
506
+ loss_bce = loss_bce.sum() / (self.pad_n_queries * loss_bce.size(0))
507
+
508
+ bce_f1 = torchmetrics.functional.f1_score(
509
+ src_logits.sigmoid().flatten(),
510
+ target=target_classes.flatten().long(),
511
+ task="binary",
512
+ )
513
+
514
+ losses = {
515
+ "loss_ce": loss_bce,
516
+ "ce_f1": bce_f1,
517
+ "presence_loss": presence_loss,
518
+ "presence_dec_acc": presence_dec_acc,
519
+ }
520
+ return losses
521
+
522
+
523
+ class Boxes(LossWithWeights):
524
+ def __init__(
525
+ self,
526
+ weight_dict=None,
527
+ compute_aux=True,
528
+ apply_loss_to_det_queries_in_video_grounding=True,
529
+ ):
530
+ super().__init__(weight_dict, compute_aux)
531
+ self.apply_loss_to_det_queries_in_video_grounding = (
532
+ apply_loss_to_det_queries_in_video_grounding
533
+ )
534
+ self.target_keys.extend(["boxes", "boxes_xyxy"])
535
+
536
+ def get_loss(self, outputs, targets, indices, num_boxes):
537
+ """Compute the losses related to the bounding boxes, the L1 regression loss and the GIoU loss
538
+ targets dicts must contain the key "boxes" containing a tensor of dim [nb_target_boxes, 4]
539
+ The target boxes are expected in format (center_x, center_y, h, w), normalized by the image size.
540
+ """
541
+ # Optionally, not applying Boxes loss to detection queries in video.
542
+ is_video_grounding = outputs.get("is_video_grounding_batch", False)
543
+ if is_video_grounding and not self.apply_loss_to_det_queries_in_video_grounding:
544
+ indices = _keep_only_trk_queries_in_match_inds(
545
+ indices, Q_det=outputs["Q_det"]
546
+ )
547
+
548
+ assert "pred_boxes" in outputs
549
+ # idx = self._get_src_permutation_idx(indices)
550
+ src_boxes = outputs["pred_boxes"][(indices[0], indices[1])]
551
+ src_boxes_xyxy = outputs["pred_boxes_xyxy"][(indices[0], indices[1])]
552
+ target_boxes = (
553
+ targets["boxes"] if indices[2] is None else targets["boxes"][indices[2]]
554
+ )
555
+ target_boxes_giou = (
556
+ targets["boxes_xyxy"]
557
+ if indices[2] is None
558
+ else targets["boxes_xyxy"][indices[2]]
559
+ )
560
+
561
+ loss_bbox = F.l1_loss(src_boxes, target_boxes, reduction="none")
562
+
563
+ losses = {}
564
+ losses["loss_bbox"] = loss_bbox.sum() / num_boxes
565
+
566
+ loss_giou = 1 - box_ops.fast_diag_generalized_box_iou(
567
+ src_boxes_xyxy, target_boxes_giou
568
+ )
569
+ losses["loss_giou"] = loss_giou.sum() / num_boxes
570
+ return losses
571
+
572
+
573
+ class Masks(LossWithWeights):
574
+ def __init__(
575
+ self,
576
+ weight_dict=None,
577
+ compute_aux=False,
578
+ focal_alpha=0.25,
579
+ focal_gamma=2,
580
+ num_sample_points=None,
581
+ oversample_ratio=None,
582
+ importance_sample_ratio=None,
583
+ apply_loss_to_det_queries_in_video_grounding=True,
584
+ ):
585
+ super().__init__(weight_dict, compute_aux)
586
+ if compute_aux:
587
+ warnings.warn("Masks loss usually shouldn't be applied to aux outputs")
588
+ self.focal_alpha = focal_alpha
589
+ self.focal_gamma = focal_gamma
590
+ self.num_sample_points = num_sample_points
591
+ self.oversample_ratio = oversample_ratio
592
+ self.importance_sample_ratio = importance_sample_ratio
593
+ self.apply_loss_to_det_queries_in_video_grounding = (
594
+ apply_loss_to_det_queries_in_video_grounding
595
+ )
596
+ self.target_keys.extend(["masks", "is_valid_mask"])
597
+
598
+ def _sampled_loss(self, src_masks, target_masks, num_boxes):
599
+ assert len(src_masks.shape) == 3 and len(target_masks.shape) == 3
600
+ src_masks = src_masks[:, None]
601
+ target_masks = target_masks[:, None]
602
+ with torch.no_grad():
603
+ # Sample point_coords
604
+ point_coords = get_uncertain_point_coords_with_randomness(
605
+ src_masks,
606
+ calculate_uncertainty,
607
+ self.num_sample_points,
608
+ self.oversample_ratio,
609
+ self.importance_sample_ratio,
610
+ )
611
+
612
+ # get GT labels
613
+ sampled_target_masks = point_sample(
614
+ target_masks,
615
+ point_coords,
616
+ align_corners=False,
617
+ ).squeeze(1)
618
+
619
+ sampled_src_masks = point_sample(
620
+ src_masks,
621
+ point_coords,
622
+ align_corners=False,
623
+ ).squeeze(1)
624
+
625
+ losses = {
626
+ "loss_mask": sigmoid_focal_loss(
627
+ sampled_src_masks,
628
+ sampled_target_masks,
629
+ num_boxes,
630
+ alpha=self.focal_alpha,
631
+ gamma=self.focal_gamma,
632
+ ),
633
+ "loss_dice": dice_loss(sampled_src_masks, sampled_target_masks, num_boxes),
634
+ }
635
+ # Not needed for backward
636
+ del src_masks
637
+ del target_masks
638
+
639
+ return losses
640
+
641
+ def get_loss(self, outputs, targets, indices, num_boxes):
642
+ """Compute the losses related to the masks: the focal loss and the dice loss.
643
+ targets dicts must contain the key "masks" containing a tensor of dim [nb_target_boxes, h, w]
644
+ """
645
+ assert "pred_masks" in outputs
646
+ assert "is_valid_mask" in targets
647
+ # Optionally, not applying Masks loss to detection queries in video.
648
+ is_video_grounding = outputs.get("is_video_grounding_batch", False)
649
+ if is_video_grounding and not self.apply_loss_to_det_queries_in_video_grounding:
650
+ indices = _keep_only_trk_queries_in_match_inds(
651
+ indices, Q_det=outputs["Q_det"]
652
+ )
653
+
654
+ src_masks = outputs["pred_masks"]
655
+
656
+ # Dataset doesn't have segmentation masks
657
+ if targets["masks"] is None:
658
+ return {
659
+ "loss_mask": torch.tensor(0.0, device=src_masks.device),
660
+ "loss_dice": torch.tensor(0.0, device=src_masks.device),
661
+ }
662
+
663
+ target_masks = (
664
+ targets["masks"] if indices[2] is None else targets["masks"][indices[2]]
665
+ )
666
+ target_masks = target_masks.to(src_masks)
667
+ keep = (
668
+ targets["is_valid_mask"]
669
+ if indices[2] is None
670
+ else targets["is_valid_mask"][indices[2]]
671
+ )
672
+
673
+ src_masks = src_masks[(indices[0], indices[1])]
674
+
675
+ # Remove invalid masks from loss
676
+ src_masks = src_masks[keep]
677
+ target_masks = target_masks[keep]
678
+
679
+ if self.num_sample_points is not None:
680
+ # Compute loss on sampled points for the Mask
681
+ losses = self._sampled_loss(src_masks, target_masks, num_boxes)
682
+
683
+ else:
684
+ # upsample predictions to the target size
685
+ if target_masks.shape[0] == 0 and src_masks.shape[0] == 0:
686
+ src_masks = src_masks.flatten(1)
687
+ target_masks = target_masks.reshape(src_masks.shape)
688
+ else:
689
+ if len(src_masks.shape) == 3:
690
+ src_masks = src_masks[:, None]
691
+ if src_masks.dtype == torch.bfloat16:
692
+ # Bilinear interpolation does not support bf16
693
+ src_masks = src_masks.to(dtype=torch.float32)
694
+ src_masks = interpolate(
695
+ src_masks,
696
+ size=target_masks.shape[-2:],
697
+ mode="bilinear",
698
+ align_corners=False,
699
+ )
700
+ src_masks = src_masks[:, 0].flatten(1)
701
+ target_masks = target_masks.flatten(1)
702
+
703
+ losses = {
704
+ "loss_mask": sigmoid_focal_loss(
705
+ src_masks,
706
+ target_masks,
707
+ num_boxes,
708
+ alpha=self.focal_alpha,
709
+ gamma=self.focal_gamma,
710
+ ),
711
+ "loss_dice": dice_loss(src_masks, target_masks, num_boxes),
712
+ }
713
+
714
+ return losses
715
+
716
+
717
+ # class MultiStepIteractiveMasks(LossWithWeights):
718
+ # def __init__(
719
+ # self,
720
+ # weight_dict=None,
721
+ # compute_aux=False,
722
+ # focal_alpha=0.25,
723
+ # focal_gamma=2,
724
+ # ):
725
+ # warnings.warn(
726
+ # "MultiStepIteractiveMasks is deprecated. Please use MultiStepMultiMasksAndIous",
727
+ # DeprecationWarning,
728
+ # )
729
+ # super().__init__(weight_dict, compute_aux)
730
+ # self.focal_alpha = focal_alpha
731
+ # self.focal_gamma = focal_gamma
732
+ # self.target_keys.extend(["masks"])
733
+
734
+ # def get_loss(self, outputs, targets, indices, num_boxes):
735
+ # """Compute the losses related to the masks: the focal loss and the dice loss.
736
+ # targets dicts must contain the key "masks" containing a tensor of dim [nb_target_boxes, h, w]
737
+
738
+ # Unlike `Masks`, here the "multistep_pred_masks" can have multiple channels, each
739
+ # corresponding to one iterative prediction step in SAM-style training. We treat each
740
+ # channel as a mask prediction and sum the loss across channels.
741
+ # """
742
+ # src_masks = outputs["multistep_pred_masks"]
743
+ # target_masks = targets["masks"]
744
+ # assert src_masks.size(0) == target_masks.size(0)
745
+ # assert src_masks.dim() == 4
746
+ # assert target_masks.dim() == 3
747
+
748
+ # # tile target_masks according to the number of
749
+ # # channels `src_masks`.
750
+ # num_steps = src_masks.size(1)
751
+ # target_masks = target_masks.unsqueeze(1).to(src_masks.dtype)
752
+ # if num_steps > 1:
753
+ # target_masks = target_masks.repeat(1, num_steps, 1, 1)
754
+
755
+ # # resize `src_masks` to target mask resolution
756
+ # if src_masks.shape != target_masks.shape:
757
+ # src_masks = interpolate(
758
+ # src_masks,
759
+ # size=target_masks.shape[-2:],
760
+ # mode="bilinear",
761
+ # align_corners=False,
762
+ # )
763
+ # assert src_masks.shape == target_masks.shape
764
+
765
+ # # flatten the multiple steps in to the batch dimension
766
+ # src_masks = src_masks.flatten(0, 1).flatten(1)
767
+ # target_masks = target_masks.flatten(0, 1).flatten(1)
768
+ # losses = {
769
+ # "loss_mask": sigmoid_focal_loss(
770
+ # src_masks,
771
+ # target_masks,
772
+ # num_boxes,
773
+ # alpha=self.focal_alpha,
774
+ # gamma=self.focal_gamma,
775
+ # ),
776
+ # "loss_dice": dice_loss(src_masks, target_masks, num_boxes),
777
+ # }
778
+
779
+ # return losses
780
+
781
+
782
+ # class MultiStepMultiMasksAndIous(LossWithWeights):
783
+ # def __init__(
784
+ # self,
785
+ # weight_dict=None,
786
+ # compute_aux=False,
787
+ # focal_alpha=0.25,
788
+ # focal_gamma=2,
789
+ # # if True, back-prop on all predicted ious
790
+ # # not just the one with lowest loss_combo
791
+ # supervise_all_iou=False,
792
+ # # Less slack vs MSE loss in [-1, 1] error range
793
+ # iou_use_l1_loss=False,
794
+ # # Settings for obj score prediction
795
+ # pred_obj_scores=False,
796
+ # focal_gamma_obj_score=0.0,
797
+ # focal_alpha_obj_score=-1,
798
+ # ):
799
+ # super().__init__(weight_dict, compute_aux)
800
+ # self.focal_alpha = focal_alpha
801
+ # self.focal_gamma = focal_gamma
802
+ # self.target_keys.extend(["masks"])
803
+ # assert "loss_mask" in self.weight_dict
804
+ # assert "loss_dice" in self.weight_dict
805
+ # assert "loss_iou" in self.weight_dict
806
+ # if "loss_class" not in self.weight_dict:
807
+ # self.weight_dict["loss_class"] = 0.0
808
+ # self.focal_alpha_obj_score = focal_alpha_obj_score
809
+ # self.focal_gamma_obj_score = focal_gamma_obj_score
810
+ # self.supervise_all_iou = supervise_all_iou
811
+ # self.iou_use_l1_loss = iou_use_l1_loss
812
+ # self.pred_obj_scores = pred_obj_scores
813
+
814
+ # def get_loss(self, outputs, targets, indices, num_boxes):
815
+ # """
816
+ # Compute the losses related to the masks: the focal loss and the dice loss.
817
+ # and also the MSE loss between predicted IoUs and actual IoUs.
818
+
819
+ # Here "multistep_pred_multimasks_high_res" is a list of multimasks (tensors
820
+ # of shape [N, M, H, W], where M could be 1 or larger, corresponding to
821
+ # one or multiple predicted masks from a click.
822
+
823
+ # We back-propagate focal, dice and iou losses only on the prediction channel
824
+ # with the lowest focal+dice loss between predicted mask and ground-truth.
825
+ # """
826
+
827
+ # target_masks = targets["masks"].unsqueeze(1).float()
828
+ # assert target_masks.dim() == 4 # [N, 1, H, W]
829
+ # src_masks_list = outputs["multistep_pred_multimasks_high_res"]
830
+ # ious_list = outputs["multistep_pred_ious"]
831
+ # object_score_logits_list = outputs["multistep_object_score_logits"]
832
+
833
+ # assert len(src_masks_list) == len(ious_list)
834
+ # assert len(object_score_logits_list) == len(ious_list)
835
+
836
+ # # Remove invalid masks from loss
837
+ # keep = targets["is_valid_mask"]
838
+ # target_masks = target_masks[keep]
839
+
840
+ # # accumulate the loss over prediction steps
841
+ # losses = {"loss_mask": 0, "loss_dice": 0, "loss_iou": 0, "loss_class": 0}
842
+ # for src_masks, ious, object_score_logits in zip(
843
+ # src_masks_list, ious_list, object_score_logits_list
844
+ # ):
845
+ # object_score_logits = object_score_logits[keep]
846
+ # ious = ious[keep]
847
+ # src_masks = src_masks[keep]
848
+ # self._update_losses(
849
+ # losses, src_masks, target_masks, ious, num_boxes, object_score_logits
850
+ # )
851
+ # return losses
852
+
853
+ # def _update_losses(
854
+ # self, losses, src_masks, target_masks, ious, num_boxes, object_score_logits
855
+ # ):
856
+ # target_masks = target_masks.expand_as(src_masks)
857
+ # # get focal, dice and iou loss on all output masks in a prediction step
858
+ # loss_multimask = sigmoid_focal_loss(
859
+ # src_masks,
860
+ # target_masks,
861
+ # num_boxes,
862
+ # alpha=self.focal_alpha,
863
+ # gamma=self.focal_gamma,
864
+ # loss_on_multimask=True,
865
+ # triton=False, # only use triton if alpha > 0
866
+ # )
867
+ # loss_multidice = dice_loss(
868
+ # src_masks, target_masks, num_boxes, loss_on_multimask=True
869
+ # )
870
+ # if not self.pred_obj_scores:
871
+ # loss_class = torch.tensor(
872
+ # 0.0, dtype=loss_multimask.dtype, device=loss_multimask.device
873
+ # )
874
+ # target_obj = torch.ones(
875
+ # loss_multimask.shape[0],
876
+ # 1,
877
+ # dtype=loss_multimask.dtype,
878
+ # device=loss_multimask.device,
879
+ # )
880
+ # else:
881
+ # target_obj = torch.any((target_masks[:, 0] > 0).flatten(1), dim=-1)[
882
+ # ..., None
883
+ # ].float()
884
+ # loss_class = sigmoid_focal_loss(
885
+ # object_score_logits,
886
+ # target_obj,
887
+ # num_boxes,
888
+ # alpha=self.focal_alpha_obj_score,
889
+ # gamma=self.focal_gamma_obj_score,
890
+ # triton=False,
891
+ # )
892
+
893
+ # loss_multiiou = iou_loss(
894
+ # src_masks,
895
+ # target_masks,
896
+ # ious,
897
+ # num_boxes,
898
+ # loss_on_multimask=True,
899
+ # use_l1_loss=self.iou_use_l1_loss,
900
+ # )
901
+ # assert loss_multimask.dim() == 2
902
+ # assert loss_multidice.dim() == 2
903
+ # assert loss_multiiou.dim() == 2
904
+ # if loss_multimask.size(1) > 1:
905
+ # # take the mask indices with the smallest focal + dice loss for back propagation
906
+ # loss_combo = (
907
+ # loss_multimask * self.weight_dict["loss_mask"]
908
+ # + loss_multidice * self.weight_dict["loss_dice"]
909
+ # )
910
+ # best_loss_inds = torch.argmin(loss_combo, dim=-1)
911
+ # batch_inds = torch.arange(loss_combo.size(0), device=loss_combo.device)
912
+ # loss_mask = loss_multimask[batch_inds, best_loss_inds].unsqueeze(1)
913
+ # loss_dice = loss_multidice[batch_inds, best_loss_inds].unsqueeze(1)
914
+ # # calculate the iou prediction and slot losses only in the index
915
+ # # with the minimum loss for each mask (to be consistent w/ SAM)
916
+ # if self.supervise_all_iou:
917
+ # loss_iou = loss_multiiou.mean(dim=-1).unsqueeze(1)
918
+ # else:
919
+ # loss_iou = loss_multiiou[batch_inds, best_loss_inds].unsqueeze(1)
920
+ # else:
921
+ # loss_mask = loss_multimask
922
+ # loss_dice = loss_multidice
923
+ # loss_iou = loss_multiiou
924
+
925
+ # # backprop focal, dice and iou loss only if obj present
926
+ # loss_mask = loss_mask * target_obj
927
+ # loss_dice = loss_dice * target_obj
928
+ # loss_iou = loss_iou * target_obj
929
+
930
+ # # sum over batch dimension (note that the losses are already divided by num_boxes)
931
+ # losses["loss_mask"] += loss_mask.sum()
932
+ # losses["loss_dice"] += loss_dice.sum()
933
+ # losses["loss_iou"] += loss_iou.sum()
934
+ # losses["loss_class"] += loss_class
935
+
936
+
937
+ # class TextCriterion(LossWithWeights):
938
+ # def __init__(
939
+ # self,
940
+ # pad_token,
941
+ # max_seq_len=100,
942
+ # weight_dict=None,
943
+ # compute_aux=False,
944
+ # ):
945
+ # super().__init__(weight_dict, compute_aux)
946
+ # self.pad_token = pad_token
947
+ # self.max_seq_len = max_seq_len
948
+ # self.in_lengths = None
949
+
950
+ # def get_loss(self, outputs, **kwargs):
951
+ # nb_tokens = outputs["captioning_tokenized_target"].input_ids.numel()
952
+ # bs, seq_len = outputs["captioning_tokenized_target"].input_ids.shape
953
+ # ce = F.cross_entropy(
954
+ # outputs["captioning_pred_text"].flatten(0, -2),
955
+ # outputs["captioning_tokenized_target"].input_ids.flatten(),
956
+ # ignore_index=self.pad_token,
957
+ # reduction="sum",
958
+ # )
959
+
960
+ # not_pad = (
961
+ # outputs["captioning_tokenized_target"]
962
+ # .input_ids.reshape(-1)
963
+ # .ne(self.pad_token)
964
+ # )
965
+
966
+ # if nb_tokens > 0:
967
+ # nb_non_pad = not_pad.numel()
968
+ # ce = ce / nb_non_pad
969
+
970
+ # preds = outputs["captioning_pred_text"].flatten(0, -2).argmax(-1)[not_pad]
971
+ # targets = outputs["captioning_tokenized_target"].input_ids.flatten()[not_pad]
972
+ # correct = preds == targets
973
+ # correct = correct.sum() / (correct.numel() + 1e-5)
974
+
975
+ # correct_sequence_level = torch.all(
976
+ # (
977
+ # outputs["captioning_pred_text"]
978
+ # .flatten(0, -2)
979
+ # .argmax(-1)
980
+ # .reshape(bs, seq_len)
981
+ # == outputs["captioning_tokenized_target"].input_ids
982
+ # )
983
+ # | (~not_pad).view(bs, seq_len),
984
+ # dim=1,
985
+ # )
986
+ # seq_level_acc = correct_sequence_level.float().mean()
987
+
988
+ # return {"loss_text": ce, "text_acc": correct, "text_seq_acc": seq_level_acc}
989
+
990
+
991
+ def segment_miou(source, target):
992
+ """Compute the mean IoU between two sets of masks"""
993
+ assert source.shape == target.shape, "The two masks must have the same shape"
994
+ assert source.ndim == 3, "The masks must be 3D"
995
+
996
+ valid_targets = (target.sum(dim=(1, 2)) > 0).sum()
997
+ if valid_targets == 0:
998
+ return torch.tensor(1.0, device=source.device)
999
+ intersection = (source.bool() & target.bool()).sum(dim=(1, 2))
1000
+ union = (source.bool() | target.bool()).sum(dim=(1, 2))
1001
+ iou = intersection / (union + 1e-8)
1002
+ return iou.sum() / valid_targets
1003
+
1004
+
1005
+ class SemanticSegCriterion(LossWithWeights):
1006
+ def __init__(
1007
+ self,
1008
+ weight_dict,
1009
+ focal: bool = False,
1010
+ focal_alpha: float = 0.6,
1011
+ focal_gamma: float = 1.6,
1012
+ downsample: bool = True,
1013
+ presence_head: bool = False,
1014
+ # Option to turn off presence loss, if some other component
1015
+ # is already doing it, e.g. decoder - in which case,
1016
+ # we could still set presence_head to True so that
1017
+ # losses are not propogated to masks when there is no GT mask
1018
+ presence_loss: bool = True,
1019
+ ):
1020
+ super().__init__(weight_dict, False)
1021
+ self.focal = focal
1022
+ self.focal_alpha = focal_alpha
1023
+ self.focal_gamma = focal_gamma
1024
+ self.downsample = downsample
1025
+ self.presence_head = presence_head
1026
+ self.presence_loss = presence_loss
1027
+
1028
+ def get_loss(self, out_dict, targets):
1029
+ outputs = out_dict["semantic_seg"]
1030
+ presence_logit = out_dict["presence_logit"]
1031
+ if (
1032
+ "semantic_masks" in targets
1033
+ and targets["semantic_masks"] is not None
1034
+ and targets["semantic_masks"].size(0) > 0
1035
+ ):
1036
+ semantic_targets = targets["semantic_masks"]
1037
+ with torch.no_grad():
1038
+ if self.downsample:
1039
+ # downsample targets to the size of predictions
1040
+ size = outputs.shape[-2:]
1041
+ semantic_targets = (
1042
+ F.interpolate(
1043
+ semantic_targets.float().unsqueeze(1),
1044
+ size=size,
1045
+ mode="bilinear",
1046
+ align_corners=False,
1047
+ )
1048
+ .squeeze(1)
1049
+ .bool()
1050
+ )
1051
+ else:
1052
+ with torch.no_grad():
1053
+ if self.downsample:
1054
+ # downsample targets to the size of predictions
1055
+ size = outputs.shape[-2:]
1056
+ segments = (
1057
+ F.interpolate(
1058
+ targets["masks"].float().unsqueeze(1),
1059
+ size=size,
1060
+ mode="bilinear",
1061
+ align_corners=False,
1062
+ )
1063
+ .squeeze(1)
1064
+ .bool()
1065
+ )
1066
+ else:
1067
+ segments = targets["masks"].bool()
1068
+
1069
+ # the annotations are for instance segmentation, so we merge them to get semantic segmentation
1070
+ semantic_targets = instance_masks_to_semantic_masks(
1071
+ segments, targets["num_boxes"]
1072
+ )
1073
+
1074
+ if not self.downsample:
1075
+ # upsample predictions to the target size
1076
+ size = semantic_targets.shape[-2:]
1077
+ outputs = F.interpolate(
1078
+ outputs.float(),
1079
+ size=size,
1080
+ mode="bilinear",
1081
+ align_corners=False,
1082
+ )
1083
+
1084
+ if self.focal:
1085
+ loss = sigmoid_focal_loss(
1086
+ outputs.squeeze(1).flatten(-2),
1087
+ semantic_targets.float().flatten(-2),
1088
+ num_boxes=len(semantic_targets),
1089
+ alpha=self.focal_alpha,
1090
+ gamma=self.focal_gamma,
1091
+ reduce=not self.presence_head,
1092
+ )
1093
+ if self.presence_head:
1094
+ loss = loss.mean(1)
1095
+ else:
1096
+ loss = F.binary_cross_entropy_with_logits(
1097
+ outputs.squeeze(1),
1098
+ semantic_targets.float(),
1099
+ reduction="none" if self.presence_head else "mean",
1100
+ )
1101
+ if self.presence_head:
1102
+ loss = loss.flatten(1).mean(1)
1103
+
1104
+ loss_dice = dice_loss(
1105
+ outputs.squeeze(1).flatten(1),
1106
+ semantic_targets.flatten(1),
1107
+ len(semantic_targets),
1108
+ reduce=not self.presence_head,
1109
+ )
1110
+
1111
+ miou = segment_miou(outputs.sigmoid().squeeze(1) > 0.5, semantic_targets)
1112
+
1113
+ loss_dict = {}
1114
+
1115
+ if self.presence_head:
1116
+ presence_target = semantic_targets.flatten(1).any(-1)
1117
+ if self.presence_loss:
1118
+ loss_presence = F.binary_cross_entropy_with_logits(
1119
+ presence_logit.flatten(),
1120
+ presence_target.float(),
1121
+ )
1122
+ presence_acc = (
1123
+ ((presence_logit.flatten().sigmoid() > 0.5) == presence_target)
1124
+ .float()
1125
+ .mean()
1126
+ )
1127
+ else:
1128
+ # Dummy values
1129
+ loss_presence = torch.tensor(0.0, device=loss.device)
1130
+ # Whichever component is computing the presence loss,
1131
+ # should also track presence_acc
1132
+ presence_acc = torch.tensor(0.0, device=loss.device)
1133
+
1134
+ loss_dict["loss_semantic_presence"] = loss_presence
1135
+ loss_dict["presence_acc"] = presence_acc
1136
+
1137
+ # reduce the other losses, skipping the negative ones
1138
+ bs = loss.shape[0]
1139
+ assert presence_target.numel() == bs
1140
+
1141
+ mask = presence_target
1142
+ nb_valid = presence_target.sum().item()
1143
+
1144
+ loss = (loss * mask.float()).sum() / (nb_valid + 1e-6)
1145
+ loss_dice = (loss_dice * mask.float()).sum() / (nb_valid + 1e-6)
1146
+
1147
+ loss_dict.update(
1148
+ {
1149
+ "loss_semantic_seg": loss,
1150
+ "loss_semantic_dice": loss_dice,
1151
+ "miou_semantic_seg": miou,
1152
+ }
1153
+ )
1154
+
1155
+ return loss_dict
1156
+
1157
+
1158
+ class Det2TrkAssoc(LossWithWeights):
1159
+ def __init__(
1160
+ self,
1161
+ weight_dict,
1162
+ use_fp_loss=False,
1163
+ fp_loss_on_exhaustive_only=True,
1164
+ treat_fp_as_new_obj=False,
1165
+ ):
1166
+ super().__init__(weight_dict, compute_aux=False)
1167
+ self.use_fp_loss = use_fp_loss
1168
+ self.fp_loss_on_exhaustive_only = fp_loss_on_exhaustive_only
1169
+ self.treat_fp_as_new_obj = treat_fp_as_new_obj
1170
+ if self.use_fp_loss:
1171
+ self.target_keys.append("is_exhaustive")
1172
+
1173
+ def get_loss(self, outputs, targets, indices, num_boxes):
1174
+ det2trk_assoc_logits = outputs["det2trk_assoc_logits"]
1175
+ device = det2trk_assoc_logits.device
1176
+ B, Q_det, Q_trk_plus_2 = det2trk_assoc_logits.shape
1177
+ assert Q_trk_plus_2 >= 2
1178
+ Q_trk = Q_trk_plus_2 - 2
1179
+
1180
+ # We only apply association losses to those detection queries that either match
1181
+ # a GT instance or have score > 0 (i.e. those TP, FN and FP detection queries)
1182
+ matched_object_ids = outputs["matched_object_ids"]
1183
+ assert matched_object_ids.shape == (B, Q_det + Q_trk)
1184
+ matched_obj_ids_det = matched_object_ids[:, :Q_det]
1185
+ matched_obj_ids_trk = matched_object_ids[:, Q_det:]
1186
+ det_is_matched_to_gt = matched_obj_ids_det >= 0
1187
+ trk_is_matched_to_gt = matched_obj_ids_trk >= 0
1188
+
1189
+ # note: -1 label is ignored in the (softmax) cross_entropy loss below
1190
+ det2trk_assoc_labels = -torch.ones(B, Q_det, dtype=torch.long, device=device)
1191
+ # a) If a detection query is matched to a same object ID as a tracking query,
1192
+ # we assign it the index of the tracking query as a label
1193
+ det_is_same_obj_id_as_trk = (
1194
+ det_is_matched_to_gt[:, :, None]
1195
+ & trk_is_matched_to_gt[:, None, :]
1196
+ & (matched_obj_ids_det[:, :, None] == matched_obj_ids_trk[:, None, :])
1197
+ )
1198
+ batch_idx, det_idx, trk_idx = det_is_same_obj_id_as_trk.nonzero(as_tuple=True)
1199
+ det2trk_assoc_labels[batch_idx, det_idx] = trk_idx
1200
+
1201
+ # b) If a detection query is matched to GT but not to any tracking query,
1202
+ # we assign it a "new_object" label
1203
+ det_is_new_obj = det_is_matched_to_gt & ~det_is_same_obj_id_as_trk.any(dim=-1)
1204
+ det2trk_assoc_labels[det_is_new_obj] = Q_trk
1205
+
1206
+ # c) If a detection query is not matched to GT but have score > 0,
1207
+ # we assign it a "false_positive" label
1208
+ if self.use_fp_loss:
1209
+ det_is_above_thresh = outputs["pred_logits"][:, :Q_det].squeeze(2) > 0
1210
+ det_is_fp = ~det_is_matched_to_gt & det_is_above_thresh
1211
+ if self.treat_fp_as_new_obj:
1212
+ det2trk_assoc_labels[det_is_fp] = Q_trk
1213
+ else:
1214
+ if self.fp_loss_on_exhaustive_only:
1215
+ # only count FP detections on batches that are exhaustively annotated
1216
+ det_is_fp &= targets["is_exhaustive"].unsqueeze(1).bool()
1217
+ det2trk_assoc_labels[det_is_fp] = Q_trk + 1
1218
+
1219
+ # softmax cross-entropy loss for detection-to-tracking association
1220
+ loss_det2trk_assoc = F.cross_entropy(
1221
+ input=det2trk_assoc_logits.flatten(0, 1), # (B * Q_det, Q_trk + 2)
1222
+ target=det2trk_assoc_labels.flatten(0, 1), # (B * Q_det)
1223
+ ignore_index=-1,
1224
+ reduction="none",
1225
+ ).view(B, Q_det)
1226
+ # skip det2trk assocation loss on frames w/o any (non-padding) tracking queries
1227
+ frame_has_valid_trk = trk_is_matched_to_gt.any(dim=-1, keepdims=True) # (B, 1)
1228
+ loss_det2trk_assoc = loss_det2trk_assoc * frame_has_valid_trk.float()
1229
+
1230
+ loss_det2trk_assoc = loss_det2trk_assoc.sum() / (B * num_boxes)
1231
+ return {"loss_det2trk_assoc": loss_det2trk_assoc}
1232
+
1233
+
1234
+ class TrackingByDetectionAssoc(LossWithWeights):
1235
+ def __init__(self, weight_dict):
1236
+ super().__init__(weight_dict, compute_aux=False, supports_o2m_loss=False)
1237
+ assert "loss_det2trk_assoc" in self.weight_dict
1238
+ assert "loss_trk2det_assoc" in self.weight_dict
1239
+
1240
+ def get_loss(self, outputs, targets, indices, num_boxes):
1241
+ # Part A: gather object id matching between detection and tracking
1242
+ det2trk_assoc_logits = outputs["det2trk_assoc_logits"] # (B, Q_det+1, Q_trk+1)
1243
+ B, Q_det_plus_1, Q_trk_plus_1 = det2trk_assoc_logits.shape
1244
+ assert Q_det_plus_1 >= 1 and Q_trk_plus_1 >= 1
1245
+ Q_det = Q_det_plus_1 - 1
1246
+ Q_trk = Q_trk_plus_1 - 1
1247
+ device = det2trk_assoc_logits.device
1248
+
1249
+ matched_obj_ids_det = outputs["matched_object_ids"]
1250
+ assert matched_obj_ids_det.shape == (B, Q_det)
1251
+ det_is_matched_to_gt = matched_obj_ids_det >= 0
1252
+ matched_obj_ids_trk = outputs["prev_trk_object_ids"]
1253
+ assert matched_obj_ids_trk.shape == (B, Q_trk)
1254
+ trk_is_matched_to_gt = matched_obj_ids_trk >= 0
1255
+ frame_has_valid_trk = trk_is_matched_to_gt.any(dim=-1, keepdims=True) # (B, 1)
1256
+
1257
+ # check whether a detection object is the same as a tracking object
1258
+ det_is_same_obj_id_as_trk = (
1259
+ det_is_matched_to_gt[:, :, None]
1260
+ & trk_is_matched_to_gt[:, None, :]
1261
+ & (matched_obj_ids_det[:, :, None] == matched_obj_ids_trk[:, None, :])
1262
+ ) # (B, Q_det, Q_trk)
1263
+ # there should be at most one match for each detection and each previous tracked object
1264
+ torch._assert_async(torch.all(det_is_same_obj_id_as_trk.sum(dim=2) <= 1))
1265
+ torch._assert_async(torch.all(det_is_same_obj_id_as_trk.sum(dim=1) <= 1))
1266
+ batch_idx, det_idx, trk_idx = det_is_same_obj_id_as_trk.nonzero(as_tuple=True)
1267
+
1268
+ # Part B: Detection-to-tracking association loss
1269
+ # assign detection-to-tracking labels (note: -1 label is ignored in the loss below)
1270
+ det2trk_assoc_labels = -torch.ones(B, Q_det, dtype=torch.long, device=device)
1271
+ det2trk_assoc_labels[batch_idx, det_idx] = trk_idx
1272
+ # if a detection is matched to GT but not to any tracking, assign it a "new-object" label
1273
+ det_is_new_obj = det_is_matched_to_gt & ~det_is_same_obj_id_as_trk.any(dim=2)
1274
+ det2trk_assoc_labels[det_is_new_obj] = Q_trk # "Q_trk" label is "new-object"
1275
+
1276
+ # softmax cross-entropy loss for detection-to-tracking association
1277
+ loss_det2trk_assoc = F.cross_entropy(
1278
+ input=det2trk_assoc_logits[:, :-1].flatten(0, 1), # (B*Q_det, Q_trk+1)
1279
+ target=det2trk_assoc_labels.flatten(0, 1), # (B*Q_det)
1280
+ ignore_index=-1,
1281
+ reduction="none",
1282
+ ).view(B, Q_det)
1283
+ # skip det2trk assocation loss on frames w/o any (non-padding) tracking queries
1284
+ loss_det2trk_assoc = loss_det2trk_assoc * frame_has_valid_trk.float()
1285
+ loss_det2trk_assoc = loss_det2trk_assoc.sum() / (B * num_boxes)
1286
+ loss_dict = {"loss_det2trk_assoc": loss_det2trk_assoc}
1287
+
1288
+ # Part C: tracking-to-detection association loss
1289
+ trk2det_assoc_logits = det2trk_assoc_logits.transpose(1, 2)
1290
+ assert trk2det_assoc_logits.shape == (B, Q_trk + 1, Q_det + 1)
1291
+ # assign tracking-to-detection labels (note: -1 label is ignored in the loss below)
1292
+ trk2det_assoc_labels = -torch.ones(B, Q_trk, dtype=torch.long, device=device)
1293
+ trk2det_assoc_labels[batch_idx, trk_idx] = det_idx
1294
+ # if a tracking is matched to GT but not to any detection, assign it a "occluded" label
1295
+ trk_is_occluded = trk_is_matched_to_gt & ~det_is_same_obj_id_as_trk.any(dim=1)
1296
+ trk2det_assoc_labels[trk_is_occluded] = Q_det # "Q_det" label is "occluded"
1297
+
1298
+ # softmax cross-entropy loss for tracking-to-detection association
1299
+ loss_trk2det_assoc = F.cross_entropy(
1300
+ input=trk2det_assoc_logits[:, :-1].flatten(0, 1), # (B*Q_trk, Q_det+1)
1301
+ target=trk2det_assoc_labels.flatten(0, 1), # (B*Q_trk)
1302
+ ignore_index=-1,
1303
+ reduction="none",
1304
+ ).view(B, Q_trk)
1305
+ # skip trk2det association loss on frames w/o any (non-padding) tracking queries
1306
+ loss_trk2det_assoc = loss_trk2det_assoc * frame_has_valid_trk.float()
1307
+ loss_trk2det_assoc = loss_trk2det_assoc.sum() / (B * num_boxes)
1308
+ loss_dict["loss_trk2det_assoc"] = loss_trk2det_assoc
1309
+
1310
+ return loss_dict
1311
+
1312
+
1313
+ def _keep_only_trk_queries_in_match_inds(inds, Q_det):
1314
+ """Keep only the tracking query indices in the indices tuple"""
1315
+ batch_idx, src_idx, tgt_idx = inds
1316
+ if batch_idx.numel() == 0:
1317
+ return (batch_idx, src_idx, tgt_idx) # empty indices, nothing to filter
1318
+
1319
+ # keep only the tracking query indices
1320
+ is_trk_query = src_idx >= Q_det
1321
+ batch_idx_trk = batch_idx[is_trk_query]
1322
+ src_idx_trk = src_idx[is_trk_query]
1323
+ tgt_idx_trk = tgt_idx[is_trk_query] if tgt_idx is not None else None
1324
+ return (batch_idx_trk, src_idx_trk, tgt_idx_trk)
OVOW/third_party/sam3/sam3/train/loss/mask_sampling.py ADDED
@@ -0,0 +1,115 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ # Copyright (c) Meta Platforms, Inc. and affiliates. All Rights Reserved
2
+
3
+ # pyre-unsafe
4
+
5
+ from typing import Callable
6
+
7
+ import torch
8
+ from torch.nn import functional as F
9
+
10
+
11
+ # Adapted from https://github.com/facebookresearch/detectron2/blob/main/projects/PointRend/point_rend/point_features.py
12
+ def point_sample(input, point_coords, **kwargs):
13
+ """
14
+ A wrapper around :function:`torch.nn.functional.grid_sample` to support 3D point_coords tensors.
15
+ Unlike :function:`torch.nn.functional.grid_sample` it assumes `point_coords` to lie inside
16
+ [0, 1] x [0, 1] square.
17
+
18
+ Args:
19
+ input (Tensor): A tensor of shape (N, C, H, W) that contains features map on a H x W grid.
20
+ point_coords (Tensor): A tensor of shape (N, P, 2) or (N, Hgrid, Wgrid, 2) that contains
21
+ [0, 1] x [0, 1] normalized point coordinates.
22
+
23
+ Returns:
24
+ output (Tensor): A tensor of shape (N, C, P) or (N, C, Hgrid, Wgrid) that contains
25
+ features for points in `point_coords`. The features are obtained via bilinear
26
+ interplation from `input` the same way as :function:`torch.nn.functional.grid_sample`.
27
+ """
28
+ add_dim = False
29
+ if point_coords.dim() == 3:
30
+ add_dim = True
31
+ point_coords = point_coords.unsqueeze(2)
32
+ normalized_point_coords = 2.0 * point_coords - 1.0 # Normalize to [-1,1]
33
+ output = F.grid_sample(input, normalized_point_coords, **kwargs)
34
+ if add_dim:
35
+ output = output.squeeze(3)
36
+ return output
37
+
38
+
39
+ # Adapted from https://github.com/facebookresearch/detectron2/blob/main/projects/PointRend/point_rend/point_features.py
40
+ def get_uncertain_point_coords_with_randomness(
41
+ logits: torch.Tensor,
42
+ uncertainty_func: Callable,
43
+ num_points: int,
44
+ oversample_ratio: int,
45
+ importance_sample_ratio: float,
46
+ ) -> torch.Tensor:
47
+ """
48
+ Sample points in [0, 1] x [0, 1] coordinate space based on their uncertainty. The unceratinties
49
+ are calculated for each point using 'uncertainty_func' function that takes point's logit
50
+ prediction as input.
51
+ See PointRend paper for details.
52
+
53
+ Args:
54
+ logits (Tensor): A tensor of shape (N, C, Hmask, Wmask) or (N, 1, Hmask, Wmask) for
55
+ class-specific or class-agnostic prediction.
56
+ uncertainty_func: A function that takes a Tensor of shape (N, C, P) or (N, 1, P) that
57
+ contains logit predictions for P points and returns their uncertainties as a Tensor of
58
+ shape (N, 1, P).
59
+ num_points (int): The number of points P to sample.
60
+ oversample_ratio (int): Oversampling parameter.
61
+ importance_sample_ratio (float): Ratio of points that are sampled via importnace sampling.
62
+
63
+ Returns:
64
+ point_coords (Tensor): A tensor of shape (N, P, 2) that contains the coordinates of P
65
+ sampled points.
66
+ """
67
+ assert oversample_ratio >= 1
68
+ assert importance_sample_ratio <= 1 and importance_sample_ratio >= 0
69
+ num_boxes = logits.shape[0]
70
+ num_sampled = int(num_points * oversample_ratio)
71
+ point_coords = torch.rand(num_boxes, num_sampled, 2, device=logits.device)
72
+ point_logits = point_sample(logits, point_coords, align_corners=False)
73
+ # It is crucial to calculate uncertainty based on the sampled prediction value for the points.
74
+ # Calculating uncertainties of the predictions first and sampling them for points leads
75
+ # to incorrect results.
76
+ # To illustrate this: assume uncertainty_func(logits)=-abs(logits), a sampled point between
77
+ # two predictions with -1 and 1 logits has 0 logits, and therefore 0 uncertainty value.
78
+ # However, if we calculate uncertainties for the predictions first,
79
+ # both will have -1 uncertainty, and the sampled point will get -1 uncertainty.
80
+ point_uncertainties = uncertainty_func(point_logits)
81
+ num_uncertain_points = int(importance_sample_ratio * num_points)
82
+ num_random_points = num_points - num_uncertain_points
83
+ idx = torch.topk(point_uncertainties[:, 0, :], k=num_uncertain_points, dim=1)[1]
84
+ # Flatten the indices
85
+ shift = num_sampled * torch.arange(
86
+ num_boxes, dtype=torch.long, device=logits.device
87
+ )
88
+ idx += shift[:, None]
89
+ point_coords = point_coords.view(-1, 2)[idx.view(-1), :].view(
90
+ num_boxes, num_uncertain_points, 2
91
+ )
92
+ if num_random_points > 0:
93
+ point_coords = torch.cat(
94
+ [
95
+ point_coords,
96
+ torch.rand(num_boxes, num_random_points, 2, device=logits.device),
97
+ ],
98
+ dim=1,
99
+ )
100
+ return point_coords
101
+
102
+
103
+ # Adapted from https://github.com/facebookresearch/Mask2Former/blob/main/mask2former/modeling/criterion.py
104
+ def calculate_uncertainty(logits: torch.Tensor) -> torch.Tensor:
105
+ """
106
+ Estimates uncerainty as L1 distance between 0.0 and the logit prediction.
107
+ Args:
108
+ logits (Tensor): A tensor of shape (R, 1, ...) for class-agnostic
109
+ predicted masks
110
+ Returns:
111
+ scores (Tensor): A tensor of shape (R, 1, ...) that contains uncertainty scores with
112
+ the most uncertain locations having the highest uncertainty score.
113
+ """
114
+ assert logits.shape[1] == 1
115
+ return -(torch.abs(logits))
OVOW/third_party/sam3/sam3/train/loss/sam3_loss.py ADDED
@@ -0,0 +1,203 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ # Copyright (c) Meta Platforms, Inc. and affiliates. All Rights Reserved
2
+
3
+ # pyre-unsafe
4
+
5
+ import torch
6
+ from sam3.model.model_misc import SAM3Output
7
+ from sam3.train.utils.distributed import get_world_size
8
+
9
+ from .loss_fns import CORE_LOSS_KEY, Det2TrkAssoc, Masks
10
+
11
+
12
+ class DummyLoss(torch.nn.Module):
13
+ """A dummy loss that always returns 0 (as a placeholder for eval)"""
14
+
15
+ def __init__(
16
+ self,
17
+ core_loss_key: str = CORE_LOSS_KEY,
18
+ device: str = "cuda",
19
+ **kwargs,
20
+ ):
21
+ super().__init__()
22
+ self.core_loss_key = core_loss_key
23
+ self.device = torch.device(device)
24
+
25
+ def forward(self, *args, **kwargs):
26
+ return {self.core_loss_key: torch.tensor(0.0, device=self.device)}
27
+
28
+ def accumulate(self, out_dict):
29
+ """
30
+ Called by iterative losses.
31
+ """
32
+ if self.core_loss_key not in out_dict:
33
+ out_dict[self.core_loss_key] = torch.tensor(0.0, device=self.device)
34
+ return out_dict
35
+
36
+
37
+ class Sam3LossWrapper(torch.nn.Module):
38
+ def __init__(
39
+ self,
40
+ loss_fns_find,
41
+ normalization="global",
42
+ matcher=None,
43
+ o2m_matcher=None,
44
+ o2m_weight=1.0,
45
+ use_o2m_matcher_on_o2m_aux=True,
46
+ loss_fn_semantic_seg=None,
47
+ normalize_by_valid_object_num=False,
48
+ normalize_by_stage_num=False,
49
+ scale_by_find_batch_size=False,
50
+ ):
51
+ super().__init__()
52
+ self.loss_fns_find = loss_fns_find
53
+ assert normalization in ["global", "local", "none"]
54
+ self.normalization = normalization
55
+ self.normalize_by_valid_object_num = normalize_by_valid_object_num
56
+ self.normalize_by_stage_num = normalize_by_stage_num
57
+ self.matcher = matcher
58
+ self.o2m_matcher = o2m_matcher
59
+ self.o2m_weight = o2m_weight
60
+ # whether to use the o2m matcher on the o2m queries in auxiliary outputs
61
+ self.use_o2m_matcher_on_o2m_aux = use_o2m_matcher_on_o2m_aux
62
+ self.loss_fn_semantic_seg = loss_fn_semantic_seg
63
+ self.scale_by_find_batch_size = scale_by_find_batch_size
64
+
65
+ def _get_num_boxes(self, targets):
66
+ # the average number of target boxes for loss normalization
67
+ if self.normalize_by_valid_object_num:
68
+ # valid boxes are those with non-zero height and width
69
+ # (while padded invisible boxes are )
70
+ boxes_hw = targets["boxes"].view(-1, 4) # cx, cy, w, h
71
+ num_boxes = (boxes_hw[:, 2:] > 0).all(dim=-1).sum().float()
72
+ else:
73
+ num_boxes = targets["num_boxes"].sum().float()
74
+ if self.normalization == "global":
75
+ torch.distributed.all_reduce(num_boxes)
76
+ num_boxes = torch.clamp(num_boxes / get_world_size(), min=1)
77
+ elif self.normalization == "local":
78
+ num_boxes = torch.clamp(num_boxes, min=1)
79
+ elif self.normalization == "none":
80
+ num_boxes = 1
81
+ return num_boxes
82
+
83
+ def compute_loss(self, nested_out, targets):
84
+ num_boxes = self._get_num_boxes(targets)
85
+ o2m_out_is_valid = nested_out.get("o2m_out_is_valid", None)
86
+ o2m_target_is_valid_padded = nested_out.get("o2m_target_is_valid_padded", None)
87
+
88
+ # Get a list of outputs, including auxiliary and first stage outputs
89
+ output_list = [(nested_out, "", False)] # (out, suffix, is_aux)
90
+ if "aux_outputs" in nested_out:
91
+ output_list.extend(
92
+ (aux_out, f"_aux_{i}", True)
93
+ for i, aux_out in enumerate(nested_out["aux_outputs"])
94
+ )
95
+ if "first_stage" in nested_out:
96
+ output_list.append((nested_out["first_stage"], "_fs", True))
97
+
98
+ # Compute all the requested losses
99
+ losses = {}
100
+ total_core_loss = 0.0
101
+ for out, suffix, is_aux in output_list:
102
+ # o2o matcher indices need to be computed by the model (as the video model requires
103
+ # a specific way of matching free and locked indices beyond just calling the matcher)
104
+ indices = out["indices"]
105
+ has_o2m_out = "pred_logits_o2m" in out
106
+ if has_o2m_out:
107
+ o2m_out = {
108
+ k[: -len("_o2m")]: v for k, v in out.items() if k.endswith("_o2m")
109
+ }
110
+ # o2m targets are the same as the o2o targets (assuming repeat=1)
111
+ o2m_targets = targets
112
+ if self.use_o2m_matcher_on_o2m_aux or not is_aux:
113
+ o2m_indices = self.o2m_matcher(
114
+ o2m_out,
115
+ o2m_targets,
116
+ out_is_valid=o2m_out_is_valid,
117
+ target_is_valid_padded=o2m_target_is_valid_padded,
118
+ )
119
+ else:
120
+ o2m_indices = self.matcher(
121
+ o2m_out,
122
+ o2m_targets,
123
+ out_is_valid=o2m_out_is_valid,
124
+ target_is_valid_padded=o2m_target_is_valid_padded,
125
+ )
126
+
127
+ for loss_fn in self.loss_fns_find:
128
+ l_dict = loss_fn(
129
+ outputs=out,
130
+ targets=targets,
131
+ indices=indices,
132
+ num_boxes=num_boxes,
133
+ is_aux=is_aux,
134
+ )
135
+ total_core_loss += l_dict.pop(CORE_LOSS_KEY)
136
+ losses.update({f"{k}{suffix}": v for k, v in l_dict.items()})
137
+
138
+ compute_o2m_loss = has_o2m_out
139
+ # a special handling to allow turning off mask loss in o2m
140
+ # (to be compatible with the original implementation)
141
+ if isinstance(loss_fn, Masks):
142
+ compute_o2m_loss = compute_o2m_loss and "pred_masks" in o2m_out
143
+ if isinstance(loss_fn, Det2TrkAssoc):
144
+ compute_o2m_loss = False # Det2TrkAssoc does not support o2m
145
+ if compute_o2m_loss:
146
+ l_dict = loss_fn(
147
+ outputs=o2m_out,
148
+ targets=o2m_targets,
149
+ indices=o2m_indices,
150
+ num_boxes=num_boxes,
151
+ is_aux=is_aux,
152
+ )
153
+ for k in l_dict:
154
+ l_dict[k] *= self.o2m_weight
155
+ total_core_loss += l_dict.pop(CORE_LOSS_KEY)
156
+ losses.update({f"{k}{suffix}_o2m": v for k, v in l_dict.items()})
157
+
158
+ losses[CORE_LOSS_KEY] = total_core_loss
159
+ return losses
160
+
161
+ def forward(self, find_stages: SAM3Output, find_targets):
162
+ if find_stages.loss_stages is not None:
163
+ find_targets = [find_targets[i] for i in find_stages.loss_stages]
164
+ with SAM3Output.iteration_mode(
165
+ find_stages, iter_mode=SAM3Output.IterMode.ALL_STEPS_PER_STAGE
166
+ ) as find_stages:
167
+ assert len(find_stages) == len(find_targets)
168
+ total_losses = {}
169
+ for stage_outputs, stage_targets in zip(find_stages, find_targets):
170
+ stage_targets = [stage_targets] * len(stage_outputs)
171
+ # If there are multiple steps within a stage, compute the loss for all of them (e.g. interactivity)
172
+ for outputs, targets in zip(stage_outputs, stage_targets):
173
+ cur_losses = self.compute_loss(outputs, targets)
174
+
175
+ if self.loss_fn_semantic_seg is not None:
176
+ cur_losses_semantic = self.loss_fn_semantic_seg(
177
+ outputs, targets
178
+ )
179
+ cur_losses[CORE_LOSS_KEY] += cur_losses_semantic.pop(
180
+ CORE_LOSS_KEY
181
+ )
182
+ # make sure the semantic losses don't overlap with the find losses
183
+ assert set(cur_losses).isdisjoint(set(cur_losses_semantic))
184
+ cur_losses.update(cur_losses_semantic)
185
+
186
+ # Optionally, normalize the loss by the number of find stages (training video frames) so that
187
+ # image batches and video batches have similar loss scales. (Otherwise video batches would
188
+ # have a much higher loss scale due to summing the losses over all the find stages.)
189
+ if self.normalize_by_stage_num:
190
+ cur_losses[CORE_LOSS_KEY] /= len(find_stages)
191
+
192
+ if self.scale_by_find_batch_size:
193
+ bs = targets["num_boxes"].shape[0]
194
+ # sqrt scaling based on the "effective" batch size
195
+ cur_losses[CORE_LOSS_KEY] *= bs**0.5
196
+
197
+ for k, v in cur_losses.items():
198
+ if k not in total_losses:
199
+ total_losses[k] = v
200
+ else:
201
+ total_losses[k] += v
202
+
203
+ return total_losses
OVOW/third_party/sam3/sam3/train/loss/sigmoid_focal_loss.py ADDED
@@ -0,0 +1,323 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ # Copyright (c) Meta Platforms, Inc. and affiliates. All Rights Reserved
2
+
3
+ # pyre-unsafe
4
+
5
+ """Triton kernel for faster and memory efficient sigmoid focal loss"""
6
+
7
+ import torch
8
+ import triton
9
+ import triton.language as tl
10
+ from torch._inductor.runtime.triton_helpers import libdevice
11
+
12
+ """
13
+
14
+ The sigmoid focal loss is defined as:
15
+
16
+ prob = inputs.sigmoid()
17
+ ce_loss = F.binary_cross_entropy_with_logits(inputs, targets, reduction="none")
18
+ p_t = prob * targets + (1 - prob) * (1 - targets)
19
+ alpha_t = alpha * targets + (1 - alpha) * (1 - targets)
20
+ loss = alpha_t * ce_loss * ((1 - p_t) ** gamma)
21
+
22
+ Where alpha and gamma are scalar parameters, inputs are the logits, targets the float targets.
23
+
24
+ We implement two versions of the sigmoid focal loss: with and without sum reduction.
25
+ The latter is implemented with built-in reduction to avoid materializing wrt the output of the loss.
26
+ This can help save a bit of peak memory.
27
+
28
+ The reduction version is implemented using somewhat of a hack. Pytorch's generated kernels usually do the point-wise operation in a first kernel, and implement the reduction another kernel launched on a grid of size 1, where the reduction happens as a for loop in the triton kernel.
29
+ Since we want to fuse those two kernels, that is not a good idea: we'd have to launch the overall kernel on a grid of size 1, which is obviously inefficient.
30
+ On the other hand, typical CUDA algorithms for reduction (eg reduction tree) are hard to implement in triton due to the lack of thread sync primitives.
31
+ We settle for a version that abuses triton's atomic_add: we can have all threads simply add to the same location.
32
+ In practice, this is not good, since it creates a massive bottleneck on the semaphore for that single memory location. So instead, we create M reduction locations. Each thread will simply write to thread_id%M. The python code can finally sum over the M reductions.
33
+ M = 32 works fine in benchmarking tests. The forward is a tiny bit slower compared to the non-reduced kernel, but the backward breaks even due to one less memory allocation.
34
+ """
35
+
36
+
37
+ @triton.jit
38
+ def _inner_focal_loss_fwd(inputs, targets, alpha, gamma):
39
+ inv_targets = 1 - targets
40
+ # Sigmoid
41
+ sig = tl.sigmoid(inputs)
42
+
43
+ # Binary cross entropy with logits
44
+ # In practice, we want the following:
45
+ # bce_loss = -targets * tl.log(sig) - (1 - targets) * tl.log(1 - sig)
46
+ # However, the above is not numerically stable.
47
+ # We're also not directly taking the sum here, so the usual log-sum-exp trick doesn't apply
48
+ # The bce can be reformulated, after algebraic manipulation, to
49
+ # bce_loss = log(1 + exp(-x)) + x * (1-y)
50
+ # This is still not stable, because for large (-x) the exponential will blow up.
51
+ # We'll use the following alternate formulation:
52
+ # bce_loss = max(x, 0) - x * y + log(1 + exp(-abs(x)))
53
+ # Let's show that it's equivalent:
54
+ # Case x>=0: abs(x) = x , max(x, 0) = x
55
+ # so we get x - x * y + log(1 + exp(-x)) which is equivalent
56
+ # Case x<0: abs(x) = -x, max(x, 0) = 0
57
+ # we have log(1 + exp(-abs(x))) = log(1 + exp(x)) = log(exp(x)(1 + exp(-x))) = x+log(1 + exp(-x))
58
+ # plugging it in, we get
59
+ # 0 - x * y + x + log(1 + exp(-x)), which is also equivalent
60
+ # Note that this is stable because now the exponent are guaranteed to be below 0.
61
+ max_val = tl.clamp(inputs, min=0, max=1e9)
62
+ bce_loss = max_val - inputs * targets + tl.log(1 + tl.exp(-tl.abs(inputs)))
63
+
64
+ # Modulating factor
65
+ p_t = sig * targets + (1 - sig) * inv_targets
66
+ mod_factor = libdevice.pow(1 - p_t, gamma)
67
+
68
+ # Alpha factor
69
+ alpha_t = alpha * targets + (1 - alpha) * inv_targets
70
+
71
+ # Final loss calculation
72
+ return alpha_t * mod_factor * bce_loss
73
+
74
+
75
+ # Non-reduced version
76
+ @triton.jit
77
+ def sigmoid_focal_loss_fwd_kernel(
78
+ inputs_ptr,
79
+ targets_ptr,
80
+ loss_ptr,
81
+ alpha: float,
82
+ gamma: float,
83
+ n_elements: int,
84
+ BLOCK_SIZE: tl.constexpr,
85
+ ):
86
+ pid = tl.program_id(axis=0)
87
+ block_start = pid * BLOCK_SIZE
88
+ offset = block_start + tl.arange(0, BLOCK_SIZE)
89
+ mask = offset < n_elements
90
+
91
+ # Load data
92
+ inputs = tl.load(inputs_ptr + offset, mask=mask).to(tl.float32)
93
+ targets = tl.load(targets_ptr + offset, mask=mask)
94
+
95
+ final_loss = _inner_focal_loss_fwd(inputs, targets, alpha, gamma)
96
+
97
+ # Store result
98
+ tl.store(loss_ptr + offset, final_loss, mask=mask)
99
+
100
+
101
+ # version with reduction
102
+ @triton.jit
103
+ def sigmoid_focal_loss_fwd_kernel_reduce(
104
+ inputs_ptr,
105
+ targets_ptr,
106
+ loss_ptr,
107
+ alpha: float,
108
+ gamma: float,
109
+ n_elements: int,
110
+ BLOCK_SIZE: tl.constexpr,
111
+ REDUCE_SIZE: tl.constexpr,
112
+ ):
113
+ pid = tl.program_id(axis=0)
114
+ block_start = pid * BLOCK_SIZE
115
+ reduce_loc = pid % REDUCE_SIZE
116
+ offset = block_start + tl.arange(0, BLOCK_SIZE)
117
+ mask = offset < n_elements
118
+ # Load data
119
+ inputs = tl.load(inputs_ptr + offset, mask=mask).to(tl.float32)
120
+ targets = tl.load(targets_ptr + offset, mask=mask)
121
+
122
+ final_loss = _inner_focal_loss_fwd(inputs, targets, alpha, gamma) * mask
123
+
124
+ fl = tl.sum(final_loss)
125
+
126
+ # Store result
127
+ tl.atomic_add(loss_ptr + reduce_loc, fl)
128
+
129
+
130
+ @triton.jit
131
+ def _inner_focal_loss_bwd(inputs, targets, alpha, gamma):
132
+ inv_targets = 1 - targets
133
+
134
+ # Recompute forward
135
+ max_val = tl.clamp(inputs, min=0, max=1e9)
136
+ bce_loss = max_val - inputs * targets + tl.log(1 + tl.exp(-tl.abs(inputs)))
137
+
138
+ # Sigmoid
139
+ sig = tl.sigmoid(inputs)
140
+ inv_sig = 1 - sig
141
+
142
+ # Modulating factor
143
+ p_t = sig * targets + inv_sig * inv_targets
144
+ tmp = libdevice.pow(1 - p_t, gamma - 1)
145
+ mod_factor = tmp * (1 - p_t)
146
+
147
+ # Alpha factor
148
+ alpha_t = alpha * targets + (1 - alpha) * inv_targets
149
+
150
+ # Now computing the derivatives
151
+ d_pt = (2 * targets - 1) * sig * inv_sig
152
+ d_mod_factor = -gamma * d_pt * tmp
153
+
154
+ d_bce_loss = sig - targets
155
+
156
+ return alpha_t * (d_bce_loss * mod_factor + d_mod_factor * bce_loss)
157
+
158
+
159
+ @triton.jit
160
+ def sigmoid_focal_loss_bwd_kernel(
161
+ inputs_ptr,
162
+ targets_ptr,
163
+ grad_inputs_ptr,
164
+ grad_out_ptr,
165
+ alpha: float,
166
+ gamma: float,
167
+ n_elements: int,
168
+ BLOCK_SIZE: tl.constexpr,
169
+ ):
170
+ pid = tl.program_id(axis=0)
171
+ block_start = pid * BLOCK_SIZE
172
+ offset = block_start + tl.arange(0, BLOCK_SIZE)
173
+ mask = offset < n_elements
174
+ input_ptrs = inputs_ptr + offset
175
+ target_ptrs = targets_ptr + offset
176
+ grad_input_ptrs = grad_inputs_ptr + offset
177
+ grad_out_ptrs = grad_out_ptr + offset
178
+ # Load data
179
+ inputs = tl.load(input_ptrs, mask=mask).to(tl.float32)
180
+ targets = tl.load(target_ptrs, mask=mask)
181
+ grad_out = tl.load(grad_out_ptrs, mask=mask)
182
+ d_loss = grad_out * _inner_focal_loss_bwd(inputs, targets, alpha, gamma)
183
+ tl.store(grad_input_ptrs, d_loss, mask=mask)
184
+
185
+
186
+ @triton.jit
187
+ def sigmoid_focal_loss_bwd_kernel_reduce(
188
+ inputs_ptr,
189
+ targets_ptr,
190
+ grad_inputs_ptr,
191
+ grad_out_ptr,
192
+ alpha: float,
193
+ gamma: float,
194
+ n_elements: int,
195
+ BLOCK_SIZE: tl.constexpr,
196
+ ):
197
+ # The only difference is that the gradient is now a single scalar
198
+ pid = tl.program_id(axis=0)
199
+ block_start = pid * BLOCK_SIZE
200
+ offset = block_start + tl.arange(0, BLOCK_SIZE)
201
+ mask = offset < n_elements
202
+ input_ptrs = inputs_ptr + offset
203
+ target_ptrs = targets_ptr + offset
204
+ grad_input_ptrs = grad_inputs_ptr + offset
205
+ # Load data
206
+ inputs = tl.load(input_ptrs, mask=mask).to(tl.float32)
207
+ targets = tl.load(target_ptrs, mask=mask)
208
+ grad_out = tl.load(grad_out_ptr)
209
+ d_loss = grad_out * _inner_focal_loss_bwd(inputs, targets, alpha, gamma)
210
+ tl.store(grad_input_ptrs, d_loss, mask=mask)
211
+
212
+
213
+ class SigmoidFocalLoss(torch.autograd.Function):
214
+ BLOCK_SIZE = 256
215
+
216
+ @staticmethod
217
+ def forward(ctx, inputs, targets, alpha=0.25, gamma=2):
218
+ n_elements = inputs.numel()
219
+ assert targets.numel() == n_elements
220
+ input_shape = inputs.shape
221
+ inputs = inputs.view(-1).contiguous()
222
+ targets = targets.view(-1).contiguous()
223
+ loss = torch.empty(inputs.shape, dtype=torch.float32, device=inputs.device)
224
+ grid = lambda meta: (triton.cdiv(n_elements, meta["BLOCK_SIZE"]),)
225
+ sigmoid_focal_loss_fwd_kernel[grid](
226
+ inputs, targets, loss, alpha, gamma, n_elements, SigmoidFocalLoss.BLOCK_SIZE
227
+ )
228
+ ctx.save_for_backward(inputs.view(input_shape), targets.view(input_shape))
229
+ ctx.alpha = alpha
230
+ ctx.gamma = gamma
231
+ return loss.view(input_shape)
232
+
233
+ @staticmethod
234
+ def backward(ctx, grad_output):
235
+ inputs, targets = ctx.saved_tensors
236
+ alpha = ctx.alpha
237
+ gamma = ctx.gamma
238
+ n_elements = inputs.numel()
239
+ input_shape = inputs.shape
240
+ grad_inputs = torch.empty(
241
+ inputs.shape, dtype=grad_output.dtype, device=grad_output.device
242
+ )
243
+ inputs_ptr = inputs.view(-1).contiguous()
244
+ targets_ptr = targets.view(-1).contiguous()
245
+ grad_output_ptr = grad_output.view(-1).contiguous()
246
+ grad_inputs_ptr = grad_inputs
247
+ assert grad_output.numel() == n_elements
248
+ grid = lambda meta: (triton.cdiv(n_elements, meta["BLOCK_SIZE"]),)
249
+ sigmoid_focal_loss_bwd_kernel[grid](
250
+ inputs_ptr,
251
+ targets_ptr,
252
+ grad_inputs_ptr,
253
+ grad_output_ptr,
254
+ alpha,
255
+ gamma,
256
+ n_elements,
257
+ SigmoidFocalLoss.BLOCK_SIZE,
258
+ )
259
+ return grad_inputs.view(input_shape), None, None, None
260
+
261
+
262
+ triton_sigmoid_focal_loss = SigmoidFocalLoss.apply
263
+
264
+
265
+ class SigmoidFocalLossReduced(torch.autograd.Function):
266
+ BLOCK_SIZE = 256
267
+ REDUCE_SIZE = 32
268
+
269
+ @staticmethod
270
+ def forward(ctx, inputs, targets, alpha=0.25, gamma=2):
271
+ n_elements = inputs.numel()
272
+ input_shape = inputs.shape
273
+ inputs = inputs.view(-1).contiguous()
274
+ targets = targets.view(-1).contiguous()
275
+ loss = torch.zeros(
276
+ SigmoidFocalLossReduced.REDUCE_SIZE,
277
+ device=inputs.device,
278
+ dtype=torch.float32,
279
+ )
280
+ grid = lambda meta: (triton.cdiv(n_elements, meta["BLOCK_SIZE"]),)
281
+ sigmoid_focal_loss_fwd_kernel_reduce[grid](
282
+ inputs,
283
+ targets,
284
+ loss,
285
+ alpha,
286
+ gamma,
287
+ n_elements,
288
+ SigmoidFocalLossReduced.BLOCK_SIZE,
289
+ SigmoidFocalLossReduced.REDUCE_SIZE,
290
+ )
291
+ ctx.save_for_backward(inputs.view(input_shape), targets.view(input_shape))
292
+ ctx.alpha = alpha
293
+ ctx.gamma = gamma
294
+ return loss.sum()
295
+
296
+ @staticmethod
297
+ def backward(ctx, grad_output):
298
+ inputs, targets = ctx.saved_tensors
299
+ alpha = ctx.alpha
300
+ gamma = ctx.gamma
301
+ n_elements = inputs.numel()
302
+ input_shape = inputs.shape
303
+ grad_inputs = torch.empty(
304
+ inputs.shape, dtype=grad_output.dtype, device=grad_output.device
305
+ )
306
+ inputs_ptr = inputs.view(-1).contiguous()
307
+ targets_ptr = targets.reshape(-1).contiguous()
308
+ assert grad_output.numel() == 1
309
+ grid = lambda meta: (triton.cdiv(n_elements, meta["BLOCK_SIZE"]),)
310
+ sigmoid_focal_loss_bwd_kernel_reduce[grid](
311
+ inputs_ptr,
312
+ targets_ptr,
313
+ grad_inputs,
314
+ grad_output,
315
+ alpha,
316
+ gamma,
317
+ n_elements,
318
+ SigmoidFocalLossReduced.BLOCK_SIZE,
319
+ )
320
+ return grad_inputs.view(input_shape), None, None, None
321
+
322
+
323
+ triton_sigmoid_focal_loss_reduce = SigmoidFocalLossReduced.apply
OVOW/third_party/sam3/sam3/train/masks_ops.py ADDED
@@ -0,0 +1,274 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ # Copyright (c) Meta Platforms, Inc. and affiliates. All Rights Reserved
2
+
3
+ # pyre-unsafe
4
+
5
+ """Utilities for masks manipulation"""
6
+
7
+ import numpy as np
8
+ import pycocotools.mask as maskUtils
9
+ import torch
10
+ from pycocotools import mask as mask_util
11
+
12
+
13
+ def instance_masks_to_semantic_masks(
14
+ instance_masks: torch.Tensor, num_instances: torch.Tensor
15
+ ) -> torch.Tensor:
16
+ """This function converts instance masks to semantic masks.
17
+ It accepts a collapsed batch of instances masks (ie all instance masks are concatenated in a single tensor) and
18
+ the number of instances in each image of the batch.
19
+ It returns a mask with the same spatial dimensions as the input instance masks, where for each batch element the
20
+ semantic mask is the union of all the instance masks in the batch element.
21
+
22
+ If for a given batch element there are no instances (ie num_instances[i]==0), the corresponding semantic mask will be a tensor of zeros.
23
+
24
+ Args:
25
+ instance_masks (torch.Tensor): A tensor of shape (N, H, W) where N is the number of instances in the batch.
26
+ num_instances (torch.Tensor): A tensor of shape (B,) where B is the batch size. It contains the number of instances
27
+ in each image of the batch.
28
+
29
+ Returns:
30
+ torch.Tensor: A tensor of shape (B, H, W) where B is the batch size and H, W are the spatial dimensions of the
31
+ input instance masks.
32
+ """
33
+
34
+ masks_per_query = torch.split(instance_masks, num_instances.tolist())
35
+
36
+ return torch.stack([torch.any(masks, dim=0) for masks in masks_per_query], dim=0)
37
+
38
+
39
+ def mask_intersection(masks1, masks2, block_size=16):
40
+ """Compute the intersection of two sets of masks, without blowing the memory"""
41
+
42
+ assert masks1.shape[1:] == masks2.shape[1:]
43
+ assert masks1.dtype == torch.bool and masks2.dtype == torch.bool
44
+
45
+ result = torch.zeros(
46
+ masks1.shape[0], masks2.shape[0], device=masks1.device, dtype=torch.long
47
+ )
48
+ for i in range(0, masks1.shape[0], block_size):
49
+ for j in range(0, masks2.shape[0], block_size):
50
+ intersection = (
51
+ (masks1[i : i + block_size, None] * masks2[None, j : j + block_size])
52
+ .flatten(-2)
53
+ .sum(-1)
54
+ )
55
+ result[i : i + block_size, j : j + block_size] = intersection
56
+ return result
57
+
58
+
59
+ def mask_iom(masks1, masks2):
60
+ """
61
+ Similar to IoU, except the denominator is the area of the smallest mask
62
+ """
63
+ assert masks1.shape[1:] == masks2.shape[1:]
64
+ assert masks1.dtype == torch.bool and masks2.dtype == torch.bool
65
+
66
+ # intersection = (masks1[:, None] * masks2[None]).flatten(-2).sum(-1)
67
+ intersection = mask_intersection(masks1, masks2)
68
+ area1 = masks1.flatten(-2).sum(-1)
69
+ area2 = masks2.flatten(-2).sum(-1)
70
+ min_area = torch.min(area1[:, None], area2[None, :])
71
+ return intersection / (min_area + 1e-8)
72
+
73
+
74
+ def compute_boundary(seg):
75
+ """
76
+ Adapted from https://github.com/JonathonLuiten/TrackEval/blob/master/trackeval/metrics/j_and_f.py#L148
77
+ Return a 1pix wide boundary of the given mask
78
+ """
79
+ assert seg.ndim >= 2
80
+ e = torch.zeros_like(seg)
81
+ s = torch.zeros_like(seg)
82
+ se = torch.zeros_like(seg)
83
+
84
+ e[..., :, :-1] = seg[..., :, 1:]
85
+ s[..., :-1, :] = seg[..., 1:, :]
86
+ se[..., :-1, :-1] = seg[..., 1:, 1:]
87
+
88
+ b = seg ^ e | seg ^ s | seg ^ se
89
+ b[..., -1, :] = seg[..., -1, :] ^ e[..., -1, :]
90
+ b[..., :, -1] = seg[..., :, -1] ^ s[..., :, -1]
91
+ b[..., -1, -1] = 0
92
+ return b
93
+
94
+
95
+ def dilation(mask, kernel_size):
96
+ """
97
+ Implements the dilation operation. If the input is on cpu, we call the cv2 version.
98
+ Otherwise, we implement it using a convolution
99
+
100
+ The kernel is assumed to be a square kernel
101
+
102
+ """
103
+
104
+ assert mask.ndim == 3
105
+ kernel_size = int(kernel_size)
106
+ assert kernel_size % 2 == 1, (
107
+ f"Dilation expects a odd kernel size, got {kernel_size}"
108
+ )
109
+
110
+ if mask.is_cuda:
111
+ m = mask.unsqueeze(1).to(torch.float16)
112
+ k = torch.ones(1, 1, kernel_size, 1, dtype=m.dtype, device=m.device)
113
+
114
+ result = torch.nn.functional.conv2d(m, k, padding="same")
115
+ result = torch.nn.functional.conv2d(result, k.transpose(-1, -2), padding="same")
116
+ return result.view_as(mask) > 0
117
+
118
+ all_masks = mask.view(-1, mask.size(-2), mask.size(-1)).numpy().astype(np.uint8)
119
+ kernel = np.ones((kernel_size, kernel_size), dtype=np.uint8)
120
+
121
+ import cv2
122
+
123
+ processed = [torch.from_numpy(cv2.dilate(m, kernel)) for m in all_masks]
124
+ return torch.stack(processed).view_as(mask).to(mask)
125
+
126
+
127
+ def compute_F_measure(
128
+ gt_boundary_rle, gt_dilated_boundary_rle, dt_boundary_rle, dt_dilated_boundary_rle
129
+ ):
130
+ """Adapted from https://github.com/JonathonLuiten/TrackEval/blob/master/trackeval/metrics/j_and_f.py#L207
131
+
132
+ Assumes the boundary and dilated boundaries have already been computed and converted to RLE
133
+ """
134
+ gt_match = maskUtils.merge([gt_boundary_rle, dt_dilated_boundary_rle], True)
135
+ dt_match = maskUtils.merge([dt_boundary_rle, gt_dilated_boundary_rle], True)
136
+
137
+ n_dt = maskUtils.area(dt_boundary_rle)
138
+ n_gt = maskUtils.area(gt_boundary_rle)
139
+ # % Compute precision and recall
140
+ if n_dt == 0 and n_gt > 0:
141
+ precision = 1
142
+ recall = 0
143
+ elif n_dt > 0 and n_gt == 0:
144
+ precision = 0
145
+ recall = 1
146
+ elif n_dt == 0 and n_gt == 0:
147
+ precision = 1
148
+ recall = 1
149
+ else:
150
+ precision = maskUtils.area(dt_match) / float(n_dt)
151
+ recall = maskUtils.area(gt_match) / float(n_gt)
152
+
153
+ # Compute F measure
154
+ if precision + recall == 0:
155
+ f_val = 0
156
+ else:
157
+ f_val = 2 * precision * recall / (precision + recall)
158
+
159
+ return f_val
160
+
161
+
162
+ @torch.no_grad()
163
+ def rle_encode(orig_mask, return_areas=False):
164
+ """Encodes a collection of masks in RLE format
165
+
166
+ This function emulates the behavior of the COCO API's encode function, but
167
+ is executed partially on the GPU for faster execution.
168
+
169
+ Args:
170
+ mask (torch.Tensor): A mask of shape (N, H, W) with dtype=torch.bool
171
+ return_areas (bool): If True, add the areas of the masks as a part of
172
+ the RLE output dict under the "area" key. Default is False.
173
+
174
+ Returns:
175
+ str: The RLE encoded masks
176
+ """
177
+ assert orig_mask.ndim == 3, "Mask must be of shape (N, H, W)"
178
+ assert orig_mask.dtype == torch.bool, "Mask must have dtype=torch.bool"
179
+
180
+ if orig_mask.numel() == 0:
181
+ return []
182
+
183
+ # First, transpose the spatial dimensions.
184
+ # This is necessary because the COCO API uses Fortran order
185
+ mask = orig_mask.transpose(1, 2)
186
+
187
+ # Flatten the mask
188
+ flat_mask = mask.reshape(mask.shape[0], -1)
189
+ if return_areas:
190
+ mask_areas = flat_mask.sum(-1).tolist()
191
+ # Find the indices where the mask changes
192
+ differences = torch.ones(
193
+ mask.shape[0], flat_mask.shape[1] + 1, device=mask.device, dtype=torch.bool
194
+ )
195
+ differences[:, 1:-1] = flat_mask[:, :-1] != flat_mask[:, 1:]
196
+ differences[:, 0] = flat_mask[:, 0]
197
+ _, change_indices = torch.where(differences)
198
+
199
+ try:
200
+ boundaries = torch.cumsum(differences.sum(-1), 0).cpu()
201
+ except RuntimeError as _:
202
+ boundaries = torch.cumsum(differences.cpu().sum(-1), 0)
203
+
204
+ change_indices_clone = change_indices.clone()
205
+ # First pass computes the RLEs on GPU, in a flatten format
206
+ for i in range(mask.shape[0]):
207
+ # Get the change indices for this batch item
208
+ beg = 0 if i == 0 else boundaries[i - 1].item()
209
+ end = boundaries[i].item()
210
+ change_indices[beg + 1 : end] -= change_indices_clone[beg : end - 1]
211
+
212
+ # Now we can split the RLES of each batch item, and convert them to strings
213
+ # No more gpu at this point
214
+ change_indices = change_indices.tolist()
215
+
216
+ batch_rles = []
217
+ # Process each mask in the batch separately
218
+ for i in range(mask.shape[0]):
219
+ beg = 0 if i == 0 else boundaries[i - 1].item()
220
+ end = boundaries[i].item()
221
+ run_lengths = change_indices[beg:end]
222
+
223
+ uncompressed_rle = {"counts": run_lengths, "size": list(orig_mask.shape[1:])}
224
+ h, w = uncompressed_rle["size"]
225
+ rle = mask_util.frPyObjects(uncompressed_rle, h, w)
226
+ rle["counts"] = rle["counts"].decode("utf-8")
227
+ if return_areas:
228
+ rle["area"] = mask_areas[i]
229
+ batch_rles.append(rle)
230
+
231
+ return batch_rles
232
+
233
+
234
+ def robust_rle_encode(masks):
235
+ """Encodes a collection of masks in RLE format. Uses the gpu version fist, falls back to the cpu version if it fails"""
236
+
237
+ assert masks.ndim == 3, "Mask must be of shape (N, H, W)"
238
+ assert masks.dtype == torch.bool, "Mask must have dtype=torch.bool"
239
+
240
+ try:
241
+ return rle_encode(masks)
242
+ except RuntimeError as _:
243
+ masks = masks.cpu().numpy()
244
+ rles = [
245
+ mask_util.encode(
246
+ np.array(mask[:, :, np.newaxis], dtype=np.uint8, order="F")
247
+ )[0]
248
+ for mask in masks
249
+ ]
250
+ for rle in rles:
251
+ rle["counts"] = rle["counts"].decode("utf-8")
252
+ return rles
253
+
254
+
255
+ def ann_to_rle(segm, im_info):
256
+ """Convert annotation which can be polygons, uncompressed RLE to RLE.
257
+ Args:
258
+ ann (dict) : annotation object
259
+ Returns:
260
+ ann (rle)
261
+ """
262
+ h, w = im_info["height"], im_info["width"]
263
+ if isinstance(segm, list):
264
+ # polygon -- a single object might consist of multiple parts
265
+ # we merge all parts into one mask rle code
266
+ rles = mask_util.frPyObjects(segm, h, w)
267
+ rle = mask_util.merge(rles)
268
+ elif isinstance(segm["counts"], list):
269
+ # uncompressed RLE
270
+ rle = mask_util.frPyObjects(segm, h, w)
271
+ else:
272
+ # rle
273
+ rle = segm
274
+ return rle
OVOW/third_party/sam3/sam3/train/matcher.py ADDED
@@ -0,0 +1,807 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ # Copyright (c) Meta Platforms, Inc. and affiliates. All Rights Reserved
2
+
3
+ # pyre-unsafe
4
+
5
+ """
6
+ Modules to compute the matching cost and solve the corresponding LSAP.
7
+ """
8
+
9
+ import numpy as np
10
+ import torch
11
+ from sam3.model.box_ops import box_cxcywh_to_xyxy, box_iou, generalized_box_iou
12
+ from scipy.optimize import linear_sum_assignment
13
+ from torch import nn
14
+
15
+
16
+ def _do_matching(cost, repeats=1, return_tgt_indices=False, do_filtering=False):
17
+ if repeats > 1:
18
+ cost = np.tile(cost, (1, repeats))
19
+
20
+ i, j = linear_sum_assignment(cost)
21
+ if do_filtering:
22
+ # filter out invalid entries (i.e. those with cost > 1e8)
23
+ valid_thresh = 1e8
24
+ valid_ijs = [(ii, jj) for ii, jj in zip(i, j) if cost[ii, jj] < valid_thresh]
25
+ i, j = zip(*valid_ijs) if len(valid_ijs) > 0 else ([], [])
26
+ i, j = np.array(i, dtype=np.int64), np.array(j, dtype=np.int64)
27
+ if return_tgt_indices:
28
+ return i, j
29
+ order = np.argsort(j)
30
+ return i[order]
31
+
32
+
33
+ class HungarianMatcher(nn.Module):
34
+ """This class computes an assignment between the targets and the predictions of the network
35
+
36
+ For efficiency reasons, the targets don't include the no_object. Because of this, in general,
37
+ there are more predictions than targets. In this case, we do a 1-to-1 matching of the best predictions,
38
+ while the others are un-matched (and thus treated as non-objects).
39
+ """
40
+
41
+ def __init__(
42
+ self,
43
+ cost_class: float = 1,
44
+ cost_bbox: float = 1,
45
+ cost_giou: float = 1,
46
+ focal_loss: bool = False,
47
+ focal_alpha: float = 0.25,
48
+ focal_gamma: float = 2,
49
+ ):
50
+ """Creates the matcher
51
+
52
+ Params:
53
+ cost_class: This is the relative weight of the classification error in the matching cost
54
+ cost_bbox: This is the relative weight of the L1 error of the bounding box coordinates in the matching cost
55
+ cost_giou: This is the relative weight of the giou loss of the bounding box in the matching cost
56
+ """
57
+ super().__init__()
58
+ self.cost_class = cost_class
59
+ self.cost_bbox = cost_bbox
60
+ self.cost_giou = cost_giou
61
+ self.norm = nn.Sigmoid() if focal_loss else nn.Softmax(-1)
62
+ assert cost_class != 0 or cost_bbox != 0 or cost_giou != 0, (
63
+ "all costs cant be 0"
64
+ )
65
+ self.focal_loss = focal_loss
66
+ self.focal_alpha = focal_alpha
67
+ self.focal_gamma = focal_gamma
68
+
69
+ @torch.no_grad()
70
+ def forward(self, outputs, batched_targets):
71
+ """Performs the matching
72
+
73
+ Params:
74
+ outputs: This is a dict that contains at least these entries:
75
+ "pred_logits": Tensor of dim [batch_size, num_queries, num_classes] with the classification logits
76
+ "pred_boxes": Tensor of dim [batch_size, num_queries, 4] with the predicted box coordinates
77
+
78
+ targets: This is a list of targets (len(targets) = batch_size), where each target is a dict containing:
79
+ "labels": Tensor of dim [num_target_boxes] (where num_target_boxes is the number of ground-truth
80
+ objects in the target) containing the class labels
81
+ "boxes": Tensor of dim [num_target_boxes, 4] containing the target box coordinates
82
+
83
+ Returns:
84
+ A list of size batch_size, containing tuples of (index_i, index_j) where:
85
+ - index_i is the indices of the selected predictions (in order)
86
+ - index_j is the indices of the corresponding selected targets (in order)
87
+ For each batch element, it holds:
88
+ len(index_i) = len(index_j) = min(num_queries, num_target_boxes)
89
+ """
90
+ bs, num_queries = outputs["pred_logits"].shape[:2]
91
+
92
+ # We flatten to compute the cost matrices in a batch
93
+ out_prob = self.norm(
94
+ outputs["pred_logits"].flatten(0, 1)
95
+ ) # [batch_size * num_queries, num_classes]
96
+ out_bbox = outputs["pred_boxes"].flatten(0, 1) # [batch_size * num_queries, 4]
97
+
98
+ # Also concat the target labels and boxes
99
+ tgt_bbox = batched_targets["boxes"]
100
+
101
+ if "positive_map" in batched_targets:
102
+ # In this case we have a multi-hot target
103
+ positive_map = batched_targets["positive_map"]
104
+ assert len(tgt_bbox) == len(positive_map)
105
+
106
+ if self.focal_loss:
107
+ positive_map = positive_map > 1e-4
108
+ alpha = self.focal_alpha
109
+ gamma = self.focal_gamma
110
+ neg_cost_class = (
111
+ (1 - alpha) * (out_prob**gamma) * (-(1 - out_prob + 1e-8).log())
112
+ )
113
+ pos_cost_class = (
114
+ alpha * ((1 - out_prob) ** gamma) * (-(out_prob + 1e-8).log())
115
+ )
116
+ cost_class = (
117
+ (pos_cost_class - neg_cost_class).unsqueeze(1)
118
+ * positive_map.unsqueeze(0)
119
+ ).sum(-1)
120
+ else:
121
+ # Compute the soft-cross entropy between the predicted token alignment and the GT one for each box
122
+ cost_class = -(out_prob.unsqueeze(1) * positive_map.unsqueeze(0)).sum(
123
+ -1
124
+ )
125
+ else:
126
+ # In this case we are doing a "standard" cross entropy
127
+ tgt_ids = batched_targets["labels"]
128
+ assert len(tgt_bbox) == len(tgt_ids)
129
+
130
+ if self.focal_loss:
131
+ alpha = self.focal_alpha
132
+ gamma = self.focal_gamma
133
+ neg_cost_class = (
134
+ (1 - alpha) * (out_prob**gamma) * (-(1 - out_prob + 1e-8).log())
135
+ )
136
+ pos_cost_class = (
137
+ alpha * ((1 - out_prob) ** gamma) * (-(out_prob + 1e-8).log())
138
+ )
139
+ cost_class = pos_cost_class[:, tgt_ids] - neg_cost_class[:, tgt_ids]
140
+ else:
141
+ # Compute the classification cost. Contrary to the loss, we don't use the NLL,
142
+ # but approximate it in 1 - proba[target class].
143
+ # The 1 is a constant that doesn't change the matching, it can be omitted.
144
+ cost_class = -out_prob[:, tgt_ids]
145
+
146
+ # Compute the L1 cost between boxes
147
+ cost_bbox = torch.cdist(out_bbox, tgt_bbox, p=1)
148
+ assert cost_class.shape == cost_bbox.shape
149
+
150
+ # Compute the giou cost betwen boxes
151
+ cost_giou = -generalized_box_iou(
152
+ box_cxcywh_to_xyxy(out_bbox), box_cxcywh_to_xyxy(tgt_bbox)
153
+ )
154
+
155
+ # Final cost matrix
156
+ C = (
157
+ self.cost_bbox * cost_bbox
158
+ + self.cost_class * cost_class
159
+ + self.cost_giou * cost_giou
160
+ )
161
+ C = C.view(bs, num_queries, -1).cpu().numpy()
162
+
163
+ sizes = torch.cumsum(batched_targets["num_boxes"], -1)[:-1]
164
+ costs = [c[i] for i, c in enumerate(np.split(C, sizes.cpu().numpy(), axis=-1))]
165
+ indices = [_do_matching(c) for c in costs]
166
+ batch_idx = torch.as_tensor(
167
+ sum([[i] * len(src) for i, src in enumerate(indices)], []), dtype=torch.long
168
+ )
169
+ src_idx = torch.from_numpy(np.concatenate(indices)).long()
170
+ return batch_idx, src_idx
171
+
172
+
173
+ class BinaryHungarianMatcher(nn.Module):
174
+ """This class computes an assignment between the targets and the predictions of the network
175
+
176
+ For efficiency reasons, the targets don't include the no_object. Because of this, in general,
177
+ there are more predictions than targets. In this case, we do a 1-to-1 matching of the best predictions,
178
+ while the others are un-matched (and thus treated as non-objects).
179
+ """
180
+
181
+ def __init__(
182
+ self,
183
+ cost_class: float = 1,
184
+ cost_bbox: float = 1,
185
+ cost_giou: float = 1,
186
+ ):
187
+ """Creates the matcher
188
+
189
+ Params:
190
+ cost_class: This is the relative weight of the classification error in the matching cost
191
+ cost_bbox: This is the relative weight of the L1 error of the bounding box coordinates in the matching cost
192
+ cost_giou: This is the relative weight of the giou loss of the bounding box in the matching cost
193
+ """
194
+ super().__init__()
195
+ self.cost_class = cost_class
196
+ self.cost_bbox = cost_bbox
197
+ self.cost_giou = cost_giou
198
+ self.norm = nn.Sigmoid()
199
+ assert cost_class != 0 or cost_bbox != 0 or cost_giou != 0, (
200
+ "all costs cant be 0"
201
+ )
202
+
203
+ @torch.no_grad()
204
+ def forward(self, outputs, batched_targets, repeats=0, repeat_batch=1):
205
+ """Performs the matching
206
+
207
+ Params:
208
+ outputs: This is a dict that contains at least these entries:
209
+ "pred_logits": Tensor of dim [batch_size, num_queries, num_classes] with the classification logits
210
+ "pred_boxes": Tensor of dim [batch_size, num_queries, 4] with the predicted box coordinates
211
+
212
+ targets: This is a list of targets (len(targets) = batch_size), where each target is a dict containing:
213
+ "labels": Tensor of dim [num_target_boxes] (where num_target_boxes is the number of ground-truth
214
+ objects in the target) containing the class labels
215
+ "boxes": Tensor of dim [num_target_boxes, 4] containing the target box coordinates
216
+
217
+ Returns:
218
+ A list of size batch_size, containing tuples of (index_i, index_j) where:
219
+ - index_i is the indices of the selected predictions (in order)
220
+ - index_j is the indices of the corresponding selected targets (in order)
221
+ For each batch element, it holds:
222
+ len(index_i) = len(index_j) = min(num_queries, num_target_boxes)
223
+ """
224
+ if repeat_batch != 1:
225
+ raise NotImplementedError("please use BinaryHungarianMatcherV2 instead")
226
+
227
+ bs, num_queries = outputs["pred_logits"].shape[:2]
228
+
229
+ # We flatten to compute the cost matrices in a batch
230
+ out_prob = self.norm(outputs["pred_logits"].flatten(0, 1)).squeeze(
231
+ -1
232
+ ) # [batch_size * num_queries]
233
+ out_bbox = outputs["pred_boxes"].flatten(0, 1) # [batch_size * num_queries, 4]
234
+
235
+ # Also concat the target labels and boxes
236
+ tgt_bbox = batched_targets["boxes"]
237
+
238
+ # Compute the L1 cost between boxes
239
+ cost_bbox = torch.cdist(out_bbox, tgt_bbox, p=1)
240
+
241
+ cost_class = -out_prob.unsqueeze(-1).expand_as(cost_bbox)
242
+
243
+ assert cost_class.shape == cost_bbox.shape
244
+
245
+ # Compute the giou cost betwen boxes
246
+ cost_giou = -generalized_box_iou(
247
+ box_cxcywh_to_xyxy(out_bbox), box_cxcywh_to_xyxy(tgt_bbox)
248
+ )
249
+
250
+ # Final cost matrix
251
+ C = (
252
+ self.cost_bbox * cost_bbox
253
+ + self.cost_class * cost_class
254
+ + self.cost_giou * cost_giou
255
+ )
256
+ C = C.view(bs, num_queries, -1).cpu().numpy()
257
+
258
+ sizes = torch.cumsum(batched_targets["num_boxes"], -1)[:-1]
259
+ costs = [c[i] for i, c in enumerate(np.split(C, sizes.cpu().numpy(), axis=-1))]
260
+ return_tgt_indices = False
261
+ for c in costs:
262
+ n_targ = c.shape[1]
263
+ if repeats > 1:
264
+ n_targ *= repeats
265
+ if c.shape[0] < n_targ:
266
+ return_tgt_indices = True
267
+ break
268
+ if return_tgt_indices:
269
+ indices, tgt_indices = zip(
270
+ *(
271
+ _do_matching(
272
+ c, repeats=repeats, return_tgt_indices=return_tgt_indices
273
+ )
274
+ for c in costs
275
+ )
276
+ )
277
+ tgt_indices = list(tgt_indices)
278
+ for i in range(1, len(tgt_indices)):
279
+ tgt_indices[i] += sizes[i - 1].item()
280
+ tgt_idx = torch.from_numpy(np.concatenate(tgt_indices)).long()
281
+ else:
282
+ indices = [_do_matching(c, repeats=repeats) for c in costs]
283
+ tgt_idx = None
284
+
285
+ batch_idx = torch.as_tensor(
286
+ sum([[i] * len(src) for i, src in enumerate(indices)], []), dtype=torch.long
287
+ )
288
+ src_idx = torch.from_numpy(np.concatenate(indices)).long()
289
+ return batch_idx, src_idx, tgt_idx
290
+
291
+
292
+ class BinaryFocalHungarianMatcher(nn.Module):
293
+ """This class computes an assignment between the targets and the predictions of the network
294
+
295
+ For efficiency reasons, the targets don't include the no_object. Because of this, in general,
296
+ there are more predictions than targets. In this case, we do a 1-to-1 matching of the best predictions,
297
+ while the others are un-matched (and thus treated as non-objects).
298
+ """
299
+
300
+ def __init__(
301
+ self,
302
+ cost_class: float = 1,
303
+ cost_bbox: float = 1,
304
+ cost_giou: float = 1,
305
+ alpha: float = 0.25,
306
+ gamma: float = 2.0,
307
+ stable: bool = False,
308
+ ):
309
+ """Creates the matcher
310
+
311
+ Params:
312
+ cost_class: This is the relative weight of the classification error in the matching cost
313
+ cost_bbox: This is the relative weight of the L1 error of the bounding box coordinates in the matching cost
314
+ cost_giou: This is the relative weight of the giou loss of the bounding box in the matching cost
315
+ """
316
+ super().__init__()
317
+ self.cost_class = cost_class
318
+ self.cost_bbox = cost_bbox
319
+ self.cost_giou = cost_giou
320
+ self.norm = nn.Sigmoid()
321
+ self.alpha = alpha
322
+ self.gamma = gamma
323
+ self.stable = stable
324
+ assert cost_class != 0 or cost_bbox != 0 or cost_giou != 0, (
325
+ "all costs cant be 0"
326
+ )
327
+
328
+ @torch.no_grad()
329
+ def forward(self, outputs, batched_targets, repeats=1, repeat_batch=1):
330
+ """Performs the matching
331
+
332
+ Params:
333
+ outputs: This is a dict that contains at least these entries:
334
+ "pred_logits": Tensor of dim [batch_size, num_queries, num_classes] with the classification logits
335
+ "pred_boxes": Tensor of dim [batch_size, num_queries, 4] with the predicted box coordinates
336
+
337
+ targets: This is a list of targets (len(targets) = batch_size), where each target is a dict containing:
338
+ "labels": Tensor of dim [num_target_boxes] (where num_target_boxes is the number of ground-truth
339
+ objects in the target) containing the class labels
340
+ "boxes": Tensor of dim [num_target_boxes, 4] containing the target box coordinates
341
+
342
+ Returns:
343
+ A list of size batch_size, containing tuples of (index_i, index_j) where:
344
+ - index_i is the indices of the selected predictions (in order)
345
+ - index_j is the indices of the corresponding selected targets (in order)
346
+ For each batch element, it holds:
347
+ len(index_i) = len(index_j) = min(num_queries, num_target_boxes)
348
+ """
349
+ if repeat_batch != 1:
350
+ raise NotImplementedError("please use BinaryHungarianMatcherV2 instead")
351
+
352
+ bs, num_queries = outputs["pred_logits"].shape[:2]
353
+
354
+ # We flatten to compute the cost matrices in a batch
355
+ out_score = outputs["pred_logits"].flatten(0, 1).squeeze(-1)
356
+ out_prob = self.norm(out_score) # [batch_size * num_queries]
357
+ out_bbox = outputs["pred_boxes"].flatten(0, 1) # [batch_size * num_queries, 4]
358
+
359
+ # Also concat the target labels and boxes
360
+ tgt_bbox = batched_targets["boxes"]
361
+
362
+ # Compute the L1 cost between boxes
363
+ cost_bbox = torch.cdist(out_bbox, tgt_bbox, p=1)
364
+
365
+ # Compute the giou cost betwen boxes
366
+ cost_giou = -generalized_box_iou(
367
+ box_cxcywh_to_xyxy(out_bbox), box_cxcywh_to_xyxy(tgt_bbox)
368
+ )
369
+
370
+ # cost_class = -out_prob.unsqueeze(-1).expand_as(cost_bbox)
371
+ if self.stable:
372
+ rescaled_giou = (-cost_giou + 1) / 2
373
+ out_prob = out_prob.unsqueeze(-1).expand_as(cost_bbox) * rescaled_giou
374
+ cost_class = -self.alpha * (1 - out_prob) ** self.gamma * torch.log(
375
+ out_prob
376
+ ) + (1 - self.alpha) * out_prob**self.gamma * torch.log(1 - out_prob)
377
+ else:
378
+ # directly computing log sigmoid (more numerically stable)
379
+ log_out_prob = torch.nn.functional.logsigmoid(out_score)
380
+ log_one_minus_out_prob = torch.nn.functional.logsigmoid(-out_score)
381
+ cost_class = (
382
+ -self.alpha * (1 - out_prob) ** self.gamma * log_out_prob
383
+ + (1 - self.alpha) * out_prob**self.gamma * log_one_minus_out_prob
384
+ )
385
+ if not self.stable:
386
+ cost_class = cost_class.unsqueeze(-1).expand_as(cost_bbox)
387
+
388
+ assert cost_class.shape == cost_bbox.shape
389
+
390
+ # Final cost matrix
391
+ C = (
392
+ self.cost_bbox * cost_bbox
393
+ + self.cost_class * cost_class
394
+ + self.cost_giou * cost_giou
395
+ )
396
+ C = C.view(bs, num_queries, -1).cpu().numpy()
397
+
398
+ sizes = torch.cumsum(batched_targets["num_boxes"], -1)[:-1]
399
+ costs = [c[i] for i, c in enumerate(np.split(C, sizes.cpu().numpy(), axis=-1))]
400
+ return_tgt_indices = False
401
+ for c in costs:
402
+ n_targ = c.shape[1]
403
+ if repeats > 1:
404
+ n_targ *= repeats
405
+ if c.shape[0] < n_targ:
406
+ return_tgt_indices = True
407
+ break
408
+ if return_tgt_indices:
409
+ indices, tgt_indices = zip(
410
+ *(
411
+ _do_matching(
412
+ c, repeats=repeats, return_tgt_indices=return_tgt_indices
413
+ )
414
+ for c in costs
415
+ )
416
+ )
417
+ tgt_indices = list(tgt_indices)
418
+ for i in range(1, len(tgt_indices)):
419
+ tgt_indices[i] += sizes[i - 1].item()
420
+ tgt_idx = torch.from_numpy(np.concatenate(tgt_indices)).long()
421
+ else:
422
+ indices = [_do_matching(c, repeats=repeats) for c in costs]
423
+ tgt_idx = None
424
+
425
+ batch_idx = torch.as_tensor(
426
+ sum([[i] * len(src) for i, src in enumerate(indices)], []), dtype=torch.long
427
+ )
428
+ src_idx = torch.from_numpy(np.concatenate(indices)).long()
429
+ return batch_idx, src_idx, tgt_idx
430
+
431
+
432
+ class BinaryHungarianMatcherV2(nn.Module):
433
+ """
434
+ This class computes an assignment between the targets and the predictions
435
+ of the network
436
+
437
+ For efficiency reasons, the targets don't include the no_object. Because of
438
+ this, in general, there are more predictions than targets. In this case, we
439
+ do a 1-to-1 matching of the best predictions, while the others are
440
+ un-matched (and thus treated as non-objects).
441
+
442
+ This is a more efficient implementation of BinaryHungarianMatcher.
443
+ """
444
+
445
+ def __init__(
446
+ self,
447
+ cost_class: float = 1,
448
+ cost_bbox: float = 1,
449
+ cost_giou: float = 1,
450
+ focal: bool = False,
451
+ alpha: float = 0.25,
452
+ gamma: float = 2.0,
453
+ stable: bool = False,
454
+ remove_samples_with_0_gt: bool = True,
455
+ ):
456
+ """
457
+ Creates the matcher
458
+
459
+ Params:
460
+ - cost_class: Relative weight of the classification error in the
461
+ matching cost
462
+ - cost_bbox: Relative weight of the L1 error of the bounding box
463
+ coordinates in the matching cost
464
+ - cost_giou: This is the relative weight of the giou loss of the
465
+ bounding box in the matching cost
466
+ """
467
+ super().__init__()
468
+ self.cost_class = cost_class
469
+ self.cost_bbox = cost_bbox
470
+ self.cost_giou = cost_giou
471
+ self.norm = nn.Sigmoid()
472
+ assert cost_class != 0 or cost_bbox != 0 or cost_giou != 0, (
473
+ "all costs cant be 0"
474
+ )
475
+ self.focal = focal
476
+ if focal:
477
+ self.alpha = alpha
478
+ self.gamma = gamma
479
+ self.stable = stable
480
+ self.remove_samples_with_0_gt = remove_samples_with_0_gt
481
+
482
+ @torch.no_grad()
483
+ def forward(
484
+ self,
485
+ outputs,
486
+ batched_targets,
487
+ repeats=1,
488
+ repeat_batch=1,
489
+ out_is_valid=None,
490
+ target_is_valid_padded=None,
491
+ ):
492
+ """
493
+ Performs the matching. The inputs and outputs are the same as
494
+ BinaryHungarianMatcher.forward, except for the optional cached_padded
495
+ flag and the optional "_boxes_padded" entry of batched_targets.
496
+
497
+ Inputs:
498
+ - outputs: A dict with the following keys:
499
+ - "pred_logits": Tensor of shape (batch_size, num_queries, 1) with
500
+ classification logits
501
+ - "pred_boxes": Tensor of shape (batch_size, num_queries, 4) with
502
+ predicted box coordinates in cxcywh format.
503
+ - batched_targets: A dict of targets. There may be a variable number of
504
+ targets per batch entry; suppose that there are T_b targets for batch
505
+ entry 0 <= b < batch_size. It should have the following keys:
506
+ - "boxes": Tensor of shape (sum_b T_b, 4) giving ground-truth boxes
507
+ in cxcywh format for all batch entries packed into a single tensor
508
+ - "num_boxes": int64 Tensor of shape (batch_size,) giving the number
509
+ of ground-truth boxes per batch entry: num_boxes[b] = T_b
510
+ - "_boxes_padded": Tensor of shape (batch_size, max_b T_b, 4) giving
511
+ a padded version of ground-truth boxes. If this is not present then
512
+ it will be computed from batched_targets["boxes"] instead, but
513
+ caching it here can improve performance for repeated calls with the
514
+ same targets.
515
+ - out_is_valid: If not None, it should be a boolean tensor of shape
516
+ (batch_size, num_queries) indicating which predictions are valid.
517
+ Invalid predictions are ignored during matching and won't appear in
518
+ the output indices.
519
+ - target_is_valid_padded: If not None, it should be a boolean tensor of
520
+ shape (batch_size, max_num_gt_boxes) in padded format indicating
521
+ which GT boxes are valid. Invalid GT boxes are ignored during matching
522
+ and won't appear in the output indices.
523
+
524
+ Returns:
525
+ A list of size batch_size, containing tuples of (idx_i, idx_j):
526
+ - idx_i is the indices of the selected predictions (in order)
527
+ - idx_j is the indices of the corresponding selected targets
528
+ (in order)
529
+ For each batch element, it holds:
530
+ len(index_i) = len(index_j)
531
+ = min(num_queries, num_target_boxes)
532
+ """
533
+ _, num_queries = outputs["pred_logits"].shape[:2]
534
+
535
+ out_score = outputs["pred_logits"].squeeze(-1) # (B, Q)
536
+ out_bbox = outputs["pred_boxes"] # (B, Q, 4))
537
+
538
+ device = out_score.device
539
+
540
+ num_boxes = batched_targets["num_boxes"].cpu()
541
+ # Get a padded version of target boxes (as precomputed in the collator).
542
+ # It should work for both repeat==1 (o2o) and repeat>1 (o2m) matching.
543
+ tgt_bbox = batched_targets["boxes_padded"]
544
+ if self.remove_samples_with_0_gt:
545
+ # keep only samples w/ at least 1 GT box in targets (num_boxes and tgt_bbox)
546
+ batch_keep = num_boxes > 0
547
+ num_boxes = num_boxes[batch_keep]
548
+ tgt_bbox = tgt_bbox[batch_keep]
549
+ if target_is_valid_padded is not None:
550
+ target_is_valid_padded = target_is_valid_padded[batch_keep]
551
+ # Repeat the targets (for the case of batched aux outputs in the matcher)
552
+ if repeat_batch > 1:
553
+ # In this case, out_prob and out_bbox will be a concatenation of
554
+ # both final and auxiliary outputs, so we also repeat the targets
555
+ num_boxes = num_boxes.repeat(repeat_batch)
556
+ tgt_bbox = tgt_bbox.repeat(repeat_batch, 1, 1)
557
+ if target_is_valid_padded is not None:
558
+ target_is_valid_padded = target_is_valid_padded.repeat(repeat_batch, 1)
559
+
560
+ # keep only samples w/ at least 1 GT box in outputs
561
+ if self.remove_samples_with_0_gt:
562
+ if repeat_batch > 1:
563
+ batch_keep = batch_keep.repeat(repeat_batch)
564
+ out_score = out_score[batch_keep]
565
+ out_bbox = out_bbox[batch_keep]
566
+ if out_is_valid is not None:
567
+ out_is_valid = out_is_valid[batch_keep]
568
+ assert out_bbox.shape[0] == tgt_bbox.shape[0]
569
+ assert out_bbox.shape[0] == num_boxes.shape[0]
570
+
571
+ # Compute the L1 cost between boxes
572
+ cost_bbox = torch.cdist(out_bbox, tgt_bbox, p=1)
573
+
574
+ # Compute the giou cost betwen boxes
575
+ cost_giou = -generalized_box_iou(
576
+ box_cxcywh_to_xyxy(out_bbox), box_cxcywh_to_xyxy(tgt_bbox)
577
+ )
578
+
579
+ out_prob = self.norm(out_score)
580
+ if not self.focal:
581
+ cost_class = -out_prob.unsqueeze(-1).expand_as(cost_bbox)
582
+ else:
583
+ if self.stable:
584
+ rescaled_giou = (-cost_giou + 1) / 2
585
+ out_prob = out_prob.unsqueeze(-1).expand_as(cost_bbox) * rescaled_giou
586
+ cost_class = -self.alpha * (1 - out_prob) ** self.gamma * torch.log(
587
+ out_prob
588
+ ) + (1 - self.alpha) * out_prob**self.gamma * torch.log(1 - out_prob)
589
+ else:
590
+ # directly computing log sigmoid (more numerically stable)
591
+ log_out_prob = torch.nn.functional.logsigmoid(out_score)
592
+ log_one_minus_out_prob = torch.nn.functional.logsigmoid(-out_score)
593
+ cost_class = (
594
+ -self.alpha * (1 - out_prob) ** self.gamma * log_out_prob
595
+ + (1 - self.alpha) * out_prob**self.gamma * log_one_minus_out_prob
596
+ )
597
+ if not self.stable:
598
+ cost_class = cost_class.unsqueeze(-1).expand_as(cost_bbox)
599
+
600
+ assert cost_class.shape == cost_bbox.shape
601
+
602
+ # Final cost matrix
603
+ C = (
604
+ self.cost_bbox * cost_bbox
605
+ + self.cost_class * cost_class
606
+ + self.cost_giou * cost_giou
607
+ )
608
+ # assign a very high cost (1e9) to invalid outputs and targets, so that we can
609
+ # filter them out (in `_do_matching`) from bipartite matching results
610
+ do_filtering = out_is_valid is not None or target_is_valid_padded is not None
611
+ if out_is_valid is not None:
612
+ C = torch.where(out_is_valid[:, :, None], C, 1e9)
613
+ if target_is_valid_padded is not None:
614
+ C = torch.where(target_is_valid_padded[:, None, :], C, 1e9)
615
+ C = C.cpu().numpy()
616
+ costs = [C[i, :, :s] for i, s in enumerate(num_boxes.tolist())]
617
+ return_tgt_indices = (
618
+ do_filtering or torch.any(num_queries < num_boxes * max(repeats, 1)).item()
619
+ )
620
+ if len(costs) == 0:
621
+ # We have size 0 in the batch dimension, so we return empty matching indices
622
+ # (note that this can happen due to `remove_samples_with_0_gt=True` even if
623
+ # the original input batch size is not 0, when all queries have empty GTs).
624
+ indices = []
625
+ tgt_idx = torch.zeros(0).long().to(device) if return_tgt_indices else None
626
+ elif return_tgt_indices:
627
+ indices, tgt_indices = zip(
628
+ *(
629
+ _do_matching(
630
+ c,
631
+ repeats=repeats,
632
+ return_tgt_indices=return_tgt_indices,
633
+ do_filtering=do_filtering,
634
+ )
635
+ for c in costs
636
+ )
637
+ )
638
+ tgt_indices = list(tgt_indices)
639
+ sizes = torch.cumsum(num_boxes, -1)[:-1]
640
+ for i in range(1, len(tgt_indices)):
641
+ tgt_indices[i] += sizes[i - 1].item()
642
+ tgt_idx = torch.from_numpy(np.concatenate(tgt_indices)).long().to(device)
643
+ else:
644
+ indices = [
645
+ _do_matching(c, repeats=repeats, do_filtering=do_filtering)
646
+ for c in costs
647
+ ]
648
+ tgt_idx = None
649
+
650
+ if self.remove_samples_with_0_gt:
651
+ kept_inds = batch_keep.nonzero().squeeze(1)
652
+ batch_idx = torch.as_tensor(
653
+ sum([[kept_inds[i]] * len(src) for i, src in enumerate(indices)], []),
654
+ dtype=torch.long,
655
+ device=device,
656
+ )
657
+ else:
658
+ batch_idx = torch.as_tensor(
659
+ sum([[i] * len(src) for i, src in enumerate(indices)], []),
660
+ dtype=torch.long,
661
+ device=device,
662
+ )
663
+
664
+ # indices could be an empty list (since we remove samples w/ 0 GT boxes)
665
+ if len(indices) > 0:
666
+ src_idx = torch.from_numpy(np.concatenate(indices)).long().to(device)
667
+ else:
668
+ src_idx = torch.empty(0, dtype=torch.long, device=device)
669
+ return batch_idx, src_idx, tgt_idx
670
+
671
+
672
+ class BinaryOneToManyMatcher(nn.Module):
673
+ """
674
+ This class computes a greedy assignment between the targets and the predictions of the network.
675
+ In this formulation, several predictions can be assigned to each target, but each prediction can be assigned to
676
+ at most one target.
677
+
678
+ See DAC-Detr for details
679
+ """
680
+
681
+ def __init__(
682
+ self,
683
+ alpha: float = 0.3,
684
+ threshold: float = 0.4,
685
+ topk: int = 6,
686
+ ):
687
+ """
688
+ Creates the matcher
689
+
690
+ Params:
691
+ alpha: relative balancing between classification and localization
692
+ threshold: threshold used to select positive predictions
693
+ topk: number of top scoring predictions to consider
694
+ """
695
+ super().__init__()
696
+ self.norm = nn.Sigmoid()
697
+ self.alpha = alpha
698
+ self.threshold = threshold
699
+ self.topk = topk
700
+
701
+ @torch.no_grad()
702
+ def forward(
703
+ self,
704
+ outputs,
705
+ batched_targets,
706
+ repeats=1,
707
+ repeat_batch=1,
708
+ out_is_valid=None,
709
+ target_is_valid_padded=None,
710
+ ):
711
+ """
712
+ Performs the matching. The inputs and outputs are the same as
713
+ BinaryHungarianMatcher.forward
714
+
715
+ Inputs:
716
+ - outputs: A dict with the following keys:
717
+ - "pred_logits": Tensor of shape (batch_size, num_queries, 1) with
718
+ classification logits
719
+ - "pred_boxes": Tensor of shape (batch_size, num_queries, 4) with
720
+ predicted box coordinates in cxcywh format.
721
+ - batched_targets: A dict of targets. There may be a variable number of
722
+ targets per batch entry; suppose that there are T_b targets for batch
723
+ entry 0 <= b < batch_size. It should have the following keys:
724
+ - "num_boxes": int64 Tensor of shape (batch_size,) giving the number
725
+ of ground-truth boxes per batch entry: num_boxes[b] = T_b
726
+ - "_boxes_padded": Tensor of shape (batch_size, max_b T_b, 4) giving
727
+ a padded version of ground-truth boxes. If this is not present then
728
+ it will be computed from batched_targets["boxes"] instead, but
729
+ caching it here can improve performance for repeated calls with the
730
+ same targets.
731
+ - out_is_valid: If not None, it should be a boolean tensor of shape
732
+ (batch_size, num_queries) indicating which predictions are valid.
733
+ Invalid predictions are ignored during matching and won't appear in
734
+ the output indices.
735
+ - target_is_valid_padded: If not None, it should be a boolean tensor of
736
+ shape (batch_size, max_num_gt_boxes) in padded format indicating
737
+ which GT boxes are valid. Invalid GT boxes are ignored during matching
738
+ and won't appear in the output indices.
739
+ Returns:
740
+ A list of size batch_size, containing tuples of (idx_i, idx_j):
741
+ - idx_i is the indices of the selected predictions (in order)
742
+ - idx_j is the indices of the corresponding selected targets
743
+ (in order)
744
+ For each batch element, it holds:
745
+ len(index_i) = len(index_j)
746
+ = min(num_queries, num_target_boxes)
747
+ """
748
+ assert repeats <= 1 and repeat_batch <= 1
749
+ bs, num_queries = outputs["pred_logits"].shape[:2]
750
+
751
+ out_prob = self.norm(outputs["pred_logits"]).squeeze(-1) # (B, Q)
752
+ out_bbox = outputs["pred_boxes"] # (B, Q, 4))
753
+
754
+ num_boxes = batched_targets["num_boxes"]
755
+
756
+ # Get a padded version of target boxes (as precomputed in the collator).
757
+ tgt_bbox = batched_targets["boxes_padded"]
758
+ assert len(tgt_bbox) == bs
759
+ num_targets = tgt_bbox.shape[1]
760
+ if num_targets == 0:
761
+ return (
762
+ torch.empty(0, dtype=torch.long, device=out_prob.device),
763
+ torch.empty(0, dtype=torch.long, device=out_prob.device),
764
+ torch.empty(0, dtype=torch.long, device=out_prob.device),
765
+ )
766
+
767
+ iou, _ = box_iou(box_cxcywh_to_xyxy(out_bbox), box_cxcywh_to_xyxy(tgt_bbox))
768
+
769
+ assert iou.shape == (bs, num_queries, num_targets)
770
+
771
+ # Final cost matrix (higher is better in `C`; this is unlike the case
772
+ # of BinaryHungarianMatcherV2 above where lower is better in its `C`)
773
+ C = self.alpha * out_prob.unsqueeze(-1) + (1 - self.alpha) * iou
774
+ if out_is_valid is not None:
775
+ C = torch.where(out_is_valid[:, :, None], C, -1e9)
776
+ if target_is_valid_padded is not None:
777
+ C = torch.where(target_is_valid_padded[:, None, :], C, -1e9)
778
+
779
+ # Selecting topk predictions
780
+ matches = C > torch.quantile(
781
+ C, 1 - self.topk / num_queries, dim=1, keepdim=True
782
+ )
783
+
784
+ # Selecting predictions above threshold
785
+ matches = matches & (C > self.threshold)
786
+ if out_is_valid is not None:
787
+ matches = matches & out_is_valid[:, :, None]
788
+ if target_is_valid_padded is not None:
789
+ matches = matches & target_is_valid_padded[:, None, :]
790
+
791
+ # Removing padding
792
+ matches = matches & (
793
+ torch.arange(0, num_targets, device=num_boxes.device)[None]
794
+ < num_boxes[:, None]
795
+ ).unsqueeze(1)
796
+
797
+ batch_idx, src_idx, tgt_idx = torch.nonzero(matches, as_tuple=True)
798
+
799
+ cum_num_boxes = torch.cat(
800
+ [
801
+ torch.zeros(1, dtype=num_boxes.dtype, device=num_boxes.device),
802
+ num_boxes.cumsum(-1)[:-1],
803
+ ]
804
+ )
805
+ tgt_idx += cum_num_boxes[batch_idx]
806
+
807
+ return batch_idx, src_idx, tgt_idx
OVOW/third_party/sam3/sam3/train/nms_helper.py ADDED
@@ -0,0 +1,308 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ # Copyright (c) Meta Platforms, Inc. and affiliates. All Rights Reserved
2
+
3
+ # pyre-unsafe
4
+ import warnings
5
+ from typing import Dict, List
6
+
7
+ import numpy as np
8
+
9
+ # Check if Numba is available
10
+ HAS_NUMBA = False
11
+ try:
12
+ import numba as nb
13
+
14
+ HAS_NUMBA = True
15
+ except ImportError:
16
+ warnings.warn(
17
+ "Numba not found. Using slower pure Python implementations.", UserWarning
18
+ )
19
+
20
+
21
+ # -------------------- Helper Functions --------------------
22
+ def is_zero_box(bbox: list) -> bool:
23
+ """Check if bounding box is invalid"""
24
+ if bbox is None:
25
+ return True
26
+ return all(x <= 0 for x in bbox[:4]) or len(bbox) < 4
27
+
28
+
29
+ def convert_bbox_format(bbox: list) -> List[float]:
30
+ """Convert bbox from (x,y,w,h) to (x1,y1,x2,y2)"""
31
+ x, y, w, h = bbox
32
+ return [x, y, x + w, y + h]
33
+
34
+
35
+ # -------------------- Track-level NMS --------------------
36
+ def process_track_level_nms(video_groups: Dict, nms_threshold: float) -> Dict:
37
+ """Apply track-level NMS to all videos"""
38
+ for tracks in video_groups.values():
39
+ track_detections = []
40
+
41
+ # Process tracks
42
+ for track_idx, track in enumerate(tracks):
43
+ if not track["bboxes"]:
44
+ continue
45
+
46
+ converted_bboxes = []
47
+ valid_frames = []
48
+ for bbox in track["bboxes"]:
49
+ if bbox and not is_zero_box(bbox):
50
+ converted_bboxes.append(convert_bbox_format(bbox))
51
+ valid_frames.append(True)
52
+ else:
53
+ converted_bboxes.append([np.nan] * 4)
54
+ valid_frames.append(False)
55
+
56
+ if any(valid_frames):
57
+ track_detections.append(
58
+ {
59
+ "track_idx": track_idx,
60
+ "bboxes": np.array(converted_bboxes, dtype=np.float32),
61
+ "score": track["score"],
62
+ }
63
+ )
64
+
65
+ # Apply NMS
66
+ if track_detections:
67
+ scores = np.array([d["score"] for d in track_detections], dtype=np.float32)
68
+ keep = apply_track_nms(track_detections, scores, nms_threshold)
69
+
70
+ # Suppress non-kept tracks
71
+ for idx, track in enumerate(track_detections):
72
+ if idx not in keep:
73
+ tracks[track["track_idx"]]["bboxes"] = [None] * len(track["bboxes"])
74
+
75
+ return video_groups
76
+
77
+
78
+ # -------------------- Frame-level NMS --------------------
79
+ def process_frame_level_nms(video_groups: Dict, nms_threshold: float) -> Dict:
80
+ """Apply frame-level NMS to all videos"""
81
+ for tracks in video_groups.values():
82
+ if not tracks:
83
+ continue
84
+
85
+ num_frames = len(tracks[0]["bboxes"])
86
+
87
+ for frame_idx in range(num_frames):
88
+ frame_detections = []
89
+
90
+ # Collect valid detections
91
+ for track_idx, track in enumerate(tracks):
92
+ bbox = track["bboxes"][frame_idx]
93
+ if bbox and not is_zero_box(bbox):
94
+ frame_detections.append(
95
+ {
96
+ "track_idx": track_idx,
97
+ "bbox": np.array(
98
+ convert_bbox_format(bbox), dtype=np.float32
99
+ ),
100
+ "score": track["score"],
101
+ }
102
+ )
103
+
104
+ # Apply NMS
105
+ if frame_detections:
106
+ bboxes = np.stack([d["bbox"] for d in frame_detections])
107
+ scores = np.array(
108
+ [d["score"] for d in frame_detections], dtype=np.float32
109
+ )
110
+ keep = apply_frame_nms(bboxes, scores, nms_threshold)
111
+
112
+ # Suppress non-kept detections
113
+ for i, d in enumerate(frame_detections):
114
+ if i not in keep:
115
+ tracks[d["track_idx"]]["bboxes"][frame_idx] = None
116
+
117
+ return video_groups
118
+
119
+
120
+ # Track-level NMS helpers ------------------------------------------------------
121
+ def compute_track_iou_matrix(
122
+ bboxes_stacked: np.ndarray, valid_masks: np.ndarray, areas: np.ndarray
123
+ ) -> np.ndarray:
124
+ """IoU matrix computation for track-level NMS with fallback to pure Python"""
125
+ num_tracks = bboxes_stacked.shape[0]
126
+ iou_matrix = np.zeros((num_tracks, num_tracks), dtype=np.float32)
127
+ if HAS_NUMBA:
128
+ iou_matrix = _compute_track_iou_matrix_numba(bboxes_stacked, valid_masks, areas)
129
+ else:
130
+ # Pure Python implementation
131
+ for i in range(num_tracks):
132
+ for j in range(i + 1, num_tracks):
133
+ valid_ij = valid_masks[i] & valid_masks[j]
134
+ if not valid_ij.any():
135
+ continue
136
+ bboxes_i = bboxes_stacked[i, valid_ij]
137
+ bboxes_j = bboxes_stacked[j, valid_ij]
138
+ area_i = areas[i, valid_ij]
139
+ area_j = areas[j, valid_ij]
140
+ inter_total = 0.0
141
+ union_total = 0.0
142
+ for k in range(bboxes_i.shape[0]):
143
+ x1 = max(bboxes_i[k, 0], bboxes_j[k, 0])
144
+ y1 = max(bboxes_i[k, 1], bboxes_j[k, 1])
145
+ x2 = min(bboxes_i[k, 2], bboxes_j[k, 2])
146
+ y2 = min(bboxes_i[k, 3], bboxes_j[k, 3])
147
+ inter = max(0, x2 - x1) * max(0, y2 - y1)
148
+ union = area_i[k] + area_j[k] - inter
149
+ inter_total += inter
150
+ union_total += union
151
+ if union_total > 0:
152
+ iou_matrix[i, j] = inter_total / union_total
153
+ iou_matrix[j, i] = iou_matrix[i, j]
154
+ return iou_matrix
155
+
156
+
157
+ if HAS_NUMBA:
158
+
159
+ @nb.jit(nopython=True, parallel=True)
160
+ def _compute_track_iou_matrix_numba(bboxes_stacked, valid_masks, areas):
161
+ """Numba-optimized IoU matrix computation for track-level NMS"""
162
+ num_tracks = bboxes_stacked.shape[0]
163
+ iou_matrix = np.zeros((num_tracks, num_tracks), dtype=np.float32)
164
+ for i in nb.prange(num_tracks):
165
+ for j in range(i + 1, num_tracks):
166
+ valid_ij = valid_masks[i] & valid_masks[j]
167
+ if not valid_ij.any():
168
+ continue
169
+ bboxes_i = bboxes_stacked[i, valid_ij]
170
+ bboxes_j = bboxes_stacked[j, valid_ij]
171
+ area_i = areas[i, valid_ij]
172
+ area_j = areas[j, valid_ij]
173
+ inter_total = 0.0
174
+ union_total = 0.0
175
+ for k in range(bboxes_i.shape[0]):
176
+ x1 = max(bboxes_i[k, 0], bboxes_j[k, 0])
177
+ y1 = max(bboxes_i[k, 1], bboxes_j[k, 1])
178
+ x2 = min(bboxes_i[k, 2], bboxes_j[k, 2])
179
+ y2 = min(bboxes_i[k, 3], bboxes_j[k, 3])
180
+ inter = max(0, x2 - x1) * max(0, y2 - y1)
181
+ union = area_i[k] + area_j[k] - inter
182
+ inter_total += inter
183
+ union_total += union
184
+ if union_total > 0:
185
+ iou_matrix[i, j] = inter_total / union_total
186
+ iou_matrix[j, i] = iou_matrix[i, j]
187
+ return iou_matrix
188
+
189
+
190
+ def apply_track_nms(
191
+ track_detections: List[dict], scores: np.ndarray, nms_threshold: float
192
+ ) -> List[int]:
193
+ """Vectorized track-level NMS implementation"""
194
+ if not track_detections:
195
+ return []
196
+ bboxes_stacked = np.stack([d["bboxes"] for d in track_detections], axis=0)
197
+ valid_masks = ~np.isnan(bboxes_stacked).any(axis=2)
198
+ areas = (bboxes_stacked[:, :, 2] - bboxes_stacked[:, :, 0]) * (
199
+ bboxes_stacked[:, :, 3] - bboxes_stacked[:, :, 1]
200
+ )
201
+ areas[~valid_masks] = 0
202
+ iou_matrix = compute_track_iou_matrix(bboxes_stacked, valid_masks, areas)
203
+ keep = []
204
+ order = np.argsort(-scores)
205
+ suppress = np.zeros(len(track_detections), dtype=bool)
206
+ for i in range(len(order)):
207
+ if not suppress[order[i]]:
208
+ keep.append(order[i])
209
+ suppress[order[i:]] = suppress[order[i:]] | (
210
+ iou_matrix[order[i], order[i:]] >= nms_threshold
211
+ )
212
+ return keep
213
+
214
+
215
+ # Frame-level NMS helpers ------------------------------------------------------
216
+ def compute_frame_ious(bbox: np.ndarray, bboxes: np.ndarray) -> np.ndarray:
217
+ """IoU computation for frame-level NMS with fallback to pure Python"""
218
+ if HAS_NUMBA:
219
+ return _compute_frame_ious_numba(bbox, bboxes)
220
+ else:
221
+ # Pure Python implementation
222
+ ious = np.zeros(len(bboxes), dtype=np.float32)
223
+ for i in range(len(bboxes)):
224
+ x1 = max(bbox[0], bboxes[i, 0])
225
+ y1 = max(bbox[1], bboxes[i, 1])
226
+ x2 = min(bbox[2], bboxes[i, 2])
227
+ y2 = min(bbox[3], bboxes[i, 3])
228
+
229
+ inter = max(0, x2 - x1) * max(0, y2 - y1)
230
+ area1 = (bbox[2] - bbox[0]) * (bbox[3] - bbox[1])
231
+ area2 = (bboxes[i, 2] - bboxes[i, 0]) * (bboxes[i, 3] - bboxes[i, 1])
232
+ union = area1 + area2 - inter
233
+
234
+ ious[i] = inter / union if union > 0 else 0.0
235
+ return ious
236
+
237
+
238
+ if HAS_NUMBA:
239
+
240
+ @nb.jit(nopython=True, parallel=True)
241
+ def _compute_frame_ious_numba(bbox, bboxes):
242
+ """Numba-optimized IoU computation"""
243
+ ious = np.zeros(len(bboxes), dtype=np.float32)
244
+ for i in nb.prange(len(bboxes)):
245
+ x1 = max(bbox[0], bboxes[i, 0])
246
+ y1 = max(bbox[1], bboxes[i, 1])
247
+ x2 = min(bbox[2], bboxes[i, 2])
248
+ y2 = min(bbox[3], bboxes[i, 3])
249
+
250
+ inter = max(0, x2 - x1) * max(0, y2 - y1)
251
+ area1 = (bbox[2] - bbox[0]) * (bbox[3] - bbox[1])
252
+ area2 = (bboxes[i, 2] - bboxes[i, 0]) * (bboxes[i, 3] - bboxes[i, 1])
253
+ union = area1 + area2 - inter
254
+
255
+ ious[i] = inter / union if union > 0 else 0.0
256
+ return ious
257
+
258
+
259
+ def apply_frame_nms(
260
+ bboxes: np.ndarray, scores: np.ndarray, nms_threshold: float
261
+ ) -> List[int]:
262
+ """Frame-level NMS implementation with fallback to pure Python"""
263
+ if HAS_NUMBA:
264
+ return _apply_frame_nms_numba(bboxes, scores, nms_threshold)
265
+ else:
266
+ # Pure Python implementation
267
+ order = np.argsort(-scores)
268
+ keep = []
269
+ suppress = np.zeros(len(bboxes), dtype=bool)
270
+
271
+ for i in range(len(order)):
272
+ if not suppress[order[i]]:
273
+ keep.append(order[i])
274
+ current_bbox = bboxes[order[i]]
275
+
276
+ remaining_bboxes = bboxes[order[i + 1 :]]
277
+ if len(remaining_bboxes) > 0: # Check if there are any remaining boxes
278
+ ious = compute_frame_ious(current_bbox, remaining_bboxes)
279
+ suppress[order[i + 1 :]] = suppress[order[i + 1 :]] | (
280
+ ious >= nms_threshold
281
+ )
282
+
283
+ return keep
284
+
285
+
286
+ if HAS_NUMBA:
287
+
288
+ @nb.jit(nopython=True)
289
+ def _apply_frame_nms_numba(bboxes, scores, nms_threshold):
290
+ """Numba-optimized NMS implementation"""
291
+ order = np.argsort(-scores)
292
+ keep = []
293
+ suppress = np.zeros(len(bboxes), dtype=nb.boolean)
294
+
295
+ for i in range(len(order)):
296
+ if not suppress[order[i]]:
297
+ keep.append(order[i])
298
+ current_bbox = bboxes[order[i]]
299
+
300
+ if i + 1 < len(order): # Check bounds
301
+ ious = _compute_frame_ious_numba(
302
+ current_bbox, bboxes[order[i + 1 :]]
303
+ )
304
+ suppress[order[i + 1 :]] = suppress[order[i + 1 :]] | (
305
+ ious >= nms_threshold
306
+ )
307
+
308
+ return keep
OVOW/third_party/sam3/sam3/train/optim/__init__.py ADDED
@@ -0,0 +1,3 @@
 
 
 
 
1
+ # Copyright (c) Meta Platforms, Inc. and affiliates. All Rights Reserved
2
+
3
+ # pyre-unsafe
OVOW/third_party/sam3/sam3/train/optim/optimizer.py ADDED
@@ -0,0 +1,499 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ # Copyright (c) Meta Platforms, Inc. and affiliates. All Rights Reserved
2
+
3
+ # pyre-unsafe
4
+
5
+ import fnmatch
6
+ import inspect
7
+ import itertools
8
+ import logging
9
+ import types
10
+ from typing import (
11
+ Any,
12
+ Callable,
13
+ Dict,
14
+ Iterable,
15
+ List,
16
+ Mapping,
17
+ Optional,
18
+ Set,
19
+ Tuple,
20
+ Type,
21
+ Union,
22
+ )
23
+
24
+ import hydra
25
+ import torch
26
+ import torch.nn as nn
27
+ from omegaconf import DictConfig
28
+ from torch import Tensor
29
+
30
+
31
+ class Optimizer:
32
+ def __init__(self, optimizer, schedulers=None) -> None:
33
+ self.optimizer = optimizer
34
+ self.schedulers = schedulers
35
+ self._validate_optimizer_schedulers()
36
+ self.step_schedulers(0.0, 0)
37
+
38
+ def _validate_optimizer_schedulers(self):
39
+ if self.schedulers is None:
40
+ return
41
+ for _, set_of_schedulers in enumerate(self.schedulers):
42
+ for option, _ in set_of_schedulers.items():
43
+ assert option in self.optimizer.defaults, (
44
+ "Optimizer option "
45
+ f"{option} not found in {self.optimizer}. Valid options are "
46
+ f"{self.optimizer.defaults.keys()}"
47
+ )
48
+
49
+ def step_schedulers(self, where: float, step: int) -> None:
50
+ if self.schedulers is None:
51
+ return
52
+ for i, param_group in enumerate(self.optimizer.param_groups):
53
+ for option, scheduler in self.schedulers[i].items():
54
+ if "step" in inspect.signature(scheduler.__call__).parameters:
55
+ new_value = scheduler(step=step, where=where)
56
+ elif (
57
+ hasattr(scheduler, "scheduler")
58
+ and "step"
59
+ in inspect.signature(scheduler.scheduler.__call__).parameters
60
+ ):
61
+ # To handle ValueScaler wrappers
62
+ new_value = scheduler(step=step, where=where)
63
+ else:
64
+ new_value = scheduler(where)
65
+ param_group[option] = new_value
66
+
67
+ def step(self, where, step, closure=None):
68
+ self.step_schedulers(where, step)
69
+ return self.optimizer.step(closure)
70
+
71
+ def zero_grad(self, *args, **kwargs):
72
+ return self.optimizer.zero_grad(*args, **kwargs)
73
+
74
+
75
+ def set_default_parameters(
76
+ scheduler_cfgs: List[DictConfig], all_parameter_names: Set[str]
77
+ ) -> None:
78
+ """Set up the "default" scheduler with the right parameters.
79
+
80
+ Args:
81
+ scheduler_cgfs: A list of scheduler configs, where each scheduler also
82
+ specifies which parameters it applies to, based on the names of parameters
83
+ or the class of the modules. At most one scheduler is allowed to skip this
84
+ specification, which is used as a "default" specification for any remaining
85
+ parameters.
86
+ all_parameter_names: Names of all the parameters to consider.
87
+ """
88
+ constraints = [
89
+ scheduler_cfg.parameter_names
90
+ for scheduler_cfg in scheduler_cfgs
91
+ if scheduler_cfg.parameter_names is not None
92
+ ]
93
+ if len(constraints) == 0:
94
+ default_params = set(all_parameter_names)
95
+ else:
96
+ default_params = all_parameter_names - set.union(*constraints)
97
+ default_count = 0
98
+ for scheduler_cfg in scheduler_cfgs:
99
+ if scheduler_cfg.parameter_names is None:
100
+ scheduler_cfg.parameter_names = default_params
101
+ default_count += 1
102
+ assert default_count <= 1, "Only one scheduler per option can be default"
103
+ if default_count == 0:
104
+ # No default scheduler specified, add a default, but without any scheduler
105
+ # for that option
106
+ scheduler_cfgs.append({"parameter_names": default_params})
107
+
108
+
109
+ def name_constraints_to_parameters(
110
+ param_constraints: List[Set[str]], named_parameters: Dict[str, Tensor]
111
+ ) -> List[torch.nn.Parameter]:
112
+ """Return parameters which match the intersection of parameter constraints.
113
+
114
+ Note that this returns the parameters themselves, not their names.
115
+
116
+ Args:
117
+ param_constraints: A list, with each element being a set of allowed parameters.
118
+ named_parameters: Mapping from a parameter name to the parameter itself.
119
+
120
+ Returns:
121
+ A list containing the parameters which overlap with _each_ constraint set from
122
+ param_constraints.
123
+ """
124
+ matching_names = set.intersection(*param_constraints)
125
+ return [value for name, value in named_parameters.items() if name in matching_names]
126
+
127
+
128
+ def map_scheduler_cfgs_to_param_groups(
129
+ all_scheduler_cfgs: Iterable[List[Dict]],
130
+ named_parameters: Dict[str, Tensor],
131
+ ) -> Tuple[List[Dict[Any, Any]], List[Dict[str, List[torch.nn.Parameter]]]]:
132
+ """Produce parameter groups corresponding to all the scheduler configs.
133
+
134
+ Takes all the scheduler configs, each of which applies to a specific optimizer
135
+ option (like "lr" or "weight_decay") and has a set of parameter names which it
136
+ applies to, and produces a final set of param groups where each param group
137
+ covers all the options which apply to a particular set of parameters.
138
+
139
+ Args:
140
+ all_scheduler_cfgs: All the scheduler configs covering every option.
141
+ named_parameters: Mapping from a parameter name to the parameter itself.
142
+ Returns:
143
+ Tuple of lists of schedulers and param_groups, where schedulers[i]
144
+ applies to param_groups[i].
145
+ """
146
+
147
+ scheduler_cfgs_per_param_group = itertools.product(*all_scheduler_cfgs)
148
+ schedulers = []
149
+ param_groups = []
150
+ for scheduler_cfgs in scheduler_cfgs_per_param_group:
151
+ param_constraints = [
152
+ scheduler_cfg["parameter_names"] for scheduler_cfg in scheduler_cfgs
153
+ ]
154
+ matching_parameters = name_constraints_to_parameters(
155
+ param_constraints, named_parameters
156
+ )
157
+ if len(matching_parameters) == 0: # If no overlap of parameters, skip
158
+ continue
159
+ schedulers_for_group = {
160
+ scheduler_cfg["option"]: scheduler_cfg["scheduler"]
161
+ for scheduler_cfg in scheduler_cfgs
162
+ if "option" in scheduler_cfg
163
+ }
164
+ schedulers.append(schedulers_for_group)
165
+ param_groups.append({"params": matching_parameters})
166
+ return schedulers, param_groups
167
+
168
+
169
+ def validate_param_group_params(param_groups: List[Dict], model: nn.Module):
170
+ """Check that the param groups are non-overlapping and cover all the parameters.
171
+
172
+ Args:
173
+ param_groups: List of all param groups
174
+ model: Model to validate against. The check ensures that all the model
175
+ parameters are part of param_groups
176
+ """
177
+ for pg in param_groups:
178
+ # no param should be repeated within a group
179
+ assert len(pg["params"]) == len(set(pg["params"]))
180
+ parameters = [set(param_group["params"]) for param_group in param_groups]
181
+ model_parameters = {parameter for _, parameter in model.named_parameters()}
182
+ for p1, p2 in itertools.permutations(parameters, 2):
183
+ assert p1.isdisjoint(p2), "Scheduler generated param_groups should be disjoint"
184
+ assert set.union(*parameters) == model_parameters, (
185
+ "Scheduler generated param_groups must include all parameters of the model."
186
+ f" Found {len(set.union(*parameters))} params whereas model has"
187
+ f" {len(model_parameters)} params"
188
+ )
189
+
190
+
191
+ def unix_module_cls_pattern_to_parameter_names(
192
+ filter_module_cls_names: List[str],
193
+ module_cls_to_param_names: Dict[Type, str],
194
+ ) -> Union[None, Set[str]]:
195
+ """Returns param names which pass the filters specified in filter_module_cls_names.
196
+
197
+ Args:
198
+ filter_module_cls_names: A list of filter strings containing class names, like
199
+ ["torch.nn.LayerNorm", "torch.nn.BatchNorm2d"]
200
+ module_cls_to_param_names: Mapping from module classes to the parameter names
201
+ they contain. See `get_module_cls_to_param_names`.
202
+ """
203
+ if filter_module_cls_names is None:
204
+ return set()
205
+ allowed_parameter_names = []
206
+ for module_cls_name in filter_module_cls_names:
207
+ module_cls = hydra.utils.get_class(module_cls_name)
208
+ if module_cls not in module_cls_to_param_names:
209
+ raise AssertionError(
210
+ f"module_cls_name {module_cls_name} does not "
211
+ "match any classes in the model"
212
+ )
213
+ matching_parameters = module_cls_to_param_names[module_cls]
214
+ assert len(matching_parameters) > 0, (
215
+ f"module_cls_name {module_cls_name} does not contain any parameters in the model"
216
+ )
217
+ logging.info(
218
+ f"Matches for module_cls_name [{module_cls_name}]: {matching_parameters} "
219
+ )
220
+ allowed_parameter_names.append(matching_parameters)
221
+ return set.union(*allowed_parameter_names)
222
+
223
+
224
+ def unix_param_pattern_to_parameter_names(
225
+ filter_param_names: Optional[List[str]],
226
+ parameter_names: Dict[str, torch.Tensor],
227
+ ) -> Union[None, Set[str]]:
228
+ """Returns param names which pass the filters specified in filter_param_names.
229
+
230
+ Args:
231
+ filter_param_names: A list of unix-style filter strings with optional
232
+ wildcards, like ["block.2.*", "block.2.linear.weight"]
233
+ module_cls_to_param_names: Mapping from module classes to the parameter names
234
+ they contain. See `get_module_cls_to_param_names`.
235
+ """
236
+
237
+ if filter_param_names is None:
238
+ return set()
239
+ allowed_parameter_names = []
240
+ for param_name in filter_param_names:
241
+ matching_parameters = set(fnmatch.filter(parameter_names, param_name))
242
+ assert len(matching_parameters) >= 1, (
243
+ f"param_name {param_name} does not match any parameters in the model"
244
+ )
245
+ logging.info(f"Matches for param_name [{param_name}]: {matching_parameters}")
246
+ allowed_parameter_names.append(matching_parameters)
247
+ return set.union(*allowed_parameter_names)
248
+
249
+
250
+ def _unix_pattern_to_parameter_names(
251
+ scheduler_cfg: DictConfig,
252
+ parameter_names: Set[str],
253
+ module_cls_to_param_names: Dict[Type, str],
254
+ ) -> Union[None, Set[str]]:
255
+ """Returns param names which pass the filters specified in scheduler_cfg.
256
+
257
+ Args:
258
+ scheduler_cfg: The config for the scheduler
259
+ parameter_names: The set of all parameter names which will be filtered
260
+ """
261
+ if "param_names" not in scheduler_cfg and "module_cls_names" not in scheduler_cfg:
262
+ return None
263
+ return unix_param_pattern_to_parameter_names(
264
+ scheduler_cfg.get("param_names"), parameter_names
265
+ ).union(
266
+ unix_module_cls_pattern_to_parameter_names(
267
+ scheduler_cfg.get("module_cls_names"), module_cls_to_param_names
268
+ )
269
+ )
270
+
271
+
272
+ def get_module_cls_to_param_names(
273
+ model: nn.Module, param_allowlist: Set[str] = None
274
+ ) -> Dict[Type, str]:
275
+ """Produce a mapping from all the modules classes to the names of parames they own.
276
+
277
+ Only counts a parameter as part of the immediate parent module, i.e. recursive
278
+ parents do not count.
279
+
280
+ Args:
281
+ model: Model to iterate over
282
+ param_allowlist: If specified, only these param names will be processed
283
+ """
284
+
285
+ module_cls_to_params = {}
286
+ for module_name, module in model.named_modules():
287
+ module_cls = type(module)
288
+ module_cls_to_params.setdefault(module_cls, set())
289
+ for param_name, _ in module.named_parameters(recurse=False):
290
+ full_param_name = get_full_parameter_name(module_name, param_name)
291
+ if param_allowlist is None or full_param_name in param_allowlist:
292
+ module_cls_to_params[module_cls].add(full_param_name)
293
+ return module_cls_to_params
294
+
295
+
296
+ def construct_optimizer(
297
+ model: torch.nn.Module,
298
+ optimizer_conf: Any,
299
+ options_conf: Mapping[str, List] = None,
300
+ param_group_modifiers_conf: List[Callable] = None,
301
+ param_allowlist: Optional[Set[str]] = None,
302
+ validate_param_groups=True,
303
+ ) -> Optimizer:
304
+ """
305
+ Constructs a stochastic gradient descent or ADAM (or ADAMw) optimizer
306
+ with momentum. i.e, constructs a torch.optim.Optimizer with zero-weight decay
307
+ Batchnorm and/or no-update 1-D parameters support, based on the config.
308
+
309
+ Supports wrapping the optimizer with Layer-wise Adaptive Rate Scaling
310
+ (LARS): https://arxiv.org/abs/1708.03888
311
+
312
+ Args:
313
+ model: model to perform stochastic gradient descent
314
+ optimization or ADAM optimization.
315
+ optimizer_conf: Hydra config consisting a partial torch optimizer like SGD or
316
+ ADAM, still missing the params argument which this function provides to
317
+ produce the final optimizer
318
+ param_group_modifiers_conf: Optional user specified functions which can modify
319
+ the final scheduler configs before the optimizer's param groups are built
320
+ param_allowlist: The parameters to optimize. Parameters which are not part of
321
+ this allowlist will be skipped.
322
+ validate_param_groups: If enabled, valides that the produced param_groups don't
323
+ overlap and cover all the model parameters.
324
+ """
325
+ if param_allowlist is None:
326
+ param_allowlist = {name for name, _ in model.named_parameters()}
327
+
328
+ named_parameters = {
329
+ name: param
330
+ for name, param in model.named_parameters()
331
+ if name in param_allowlist
332
+ }
333
+
334
+ if not options_conf:
335
+ optimizer = hydra.utils.instantiate(optimizer_conf, named_parameters.values())
336
+ return Optimizer(optimizer)
337
+
338
+ all_parameter_names = {
339
+ name for name, _ in model.named_parameters() if name in param_allowlist
340
+ }
341
+ module_cls_to_all_param_names = get_module_cls_to_param_names(
342
+ model, param_allowlist
343
+ )
344
+
345
+ scheduler_cfgs_per_option = hydra.utils.instantiate(options_conf)
346
+ all_scheduler_cfgs = []
347
+ for option, scheduler_cfgs in scheduler_cfgs_per_option.items():
348
+ for config in scheduler_cfgs:
349
+ config.option = option
350
+ config.parameter_names = _unix_pattern_to_parameter_names(
351
+ config, all_parameter_names, module_cls_to_all_param_names
352
+ )
353
+ set_default_parameters(scheduler_cfgs, all_parameter_names)
354
+ all_scheduler_cfgs.append(scheduler_cfgs)
355
+
356
+ if param_group_modifiers_conf:
357
+ for custom_param_modifier in param_group_modifiers_conf:
358
+ custom_param_modifier = hydra.utils.instantiate(custom_param_modifier)
359
+ all_scheduler_cfgs = custom_param_modifier(
360
+ scheduler_cfgs=all_scheduler_cfgs, model=model
361
+ )
362
+ schedulers, param_groups = map_scheduler_cfgs_to_param_groups(
363
+ all_scheduler_cfgs, named_parameters
364
+ )
365
+ if validate_param_groups:
366
+ validate_param_group_params(param_groups, model)
367
+ optimizer = hydra.utils.instantiate(optimizer_conf, param_groups)
368
+ return Optimizer(optimizer, schedulers)
369
+
370
+
371
+ def get_full_parameter_name(module_name, param_name):
372
+ if module_name == "":
373
+ return param_name
374
+ return f"{module_name}.{param_name}"
375
+
376
+
377
+ class GradientClipper:
378
+ """
379
+ Gradient clipping utils that works for DDP
380
+ """
381
+
382
+ def __init__(self, max_norm: float = 1.0, norm_type: int = 2):
383
+ assert isinstance(max_norm, (int, float)) or max_norm is None
384
+ self.max_norm = max_norm if max_norm is None else float(max_norm)
385
+ self.norm_type = norm_type
386
+
387
+ def __call__(self, model: nn.Module):
388
+ if self.max_norm is None:
389
+ return # no-op
390
+
391
+ nn.utils.clip_grad_norm_(
392
+ model.parameters(), max_norm=self.max_norm, norm_type=self.norm_type
393
+ )
394
+
395
+
396
+ class ValueScaler:
397
+ def __init__(self, scheduler, mult_val: float):
398
+ self.scheduler = scheduler
399
+ self.mult_val = mult_val
400
+
401
+ def __call__(self, *args, **kwargs):
402
+ val = self.scheduler(*args, **kwargs)
403
+ return val * self.mult_val
404
+
405
+
406
+ def rgetattr(obj, rattrs: str = None):
407
+ """
408
+ Like getattr(), but supports dotted notation for nested objects.
409
+ rattrs is a str of form 'attr1.attr2', returns obj.attr1.attr2
410
+ """
411
+ if rattrs is None:
412
+ return obj
413
+ attrs = rattrs.split(".")
414
+ for attr in attrs:
415
+ obj = getattr(obj, attr)
416
+ return obj
417
+
418
+
419
+ def layer_decay_param_modifier(
420
+ scheduler_cfgs: List[List[Dict]],
421
+ model,
422
+ layer_decay_value: float,
423
+ layer_decay_min: Optional[float] = None,
424
+ apply_to: Optional[str] = None,
425
+ overrides: List[Dict] = (),
426
+ ) -> List[List[Dict]]:
427
+ """
428
+ Args
429
+ - scheduler_cfgs: a list of omegaconf.ListConfigs.
430
+ Each element in the list is a omegaconfg.DictConfig with the following structure
431
+ {
432
+ "scheduler": <some fvcore scheduler>
433
+ "option": <value> possible options are "lr", "weight_decay" etc.
434
+ "parameter_names": Set of str indicating param names that this scheduler applies to
435
+ }
436
+ - model: a model that implements a method `get_layer_id` that maps layer_name to an integer and
437
+ and a method get_num_layers.
438
+ Alternatively, use apply_to argument to select a specific component of the model.
439
+ - layer_decay_value: float
440
+ - layer_decay_min: min val for layer decay
441
+ - apply_to: optional arg to select which component of the model to apply the the layer decay modifier to
442
+ - overrides: to manually override lr for specific patterns. Is a list of dicts. Each dict, has keys "pattern", "value".
443
+ Returns
444
+ - scheduler_configs: same structure as the input, elements can be modified
445
+ """
446
+ model = rgetattr(model, apply_to)
447
+ num_layers = model.get_num_layers() + 1
448
+ layer_decays = [
449
+ layer_decay_value ** (num_layers - i) for i in range(num_layers + 1)
450
+ ]
451
+ if layer_decay_min is not None:
452
+ layer_decays = [max(val, layer_decay_min) for val in layer_decays]
453
+ final_scheduler_cfgs = []
454
+ # scheduler_cfgs is a list of lists
455
+ for scheduler_cfg_group in scheduler_cfgs:
456
+ curr_cfg_group = []
457
+ # scheduler_cfg_group is a list of dictionaries
458
+ for scheduler_cfg in scheduler_cfg_group:
459
+ if scheduler_cfg["option"] != "lr":
460
+ curr_cfg_group.append(scheduler_cfg)
461
+ continue
462
+ # Need sorted so that the list of parameter names is deterministic and consistent
463
+ # across re-runs of this job. Else it was causing issues with loading the optimizer
464
+ # state during a job restart
465
+ parameter_names = sorted(scheduler_cfg["parameter_names"])
466
+
467
+ # Only want one cfg group per layer
468
+ layer_cfg_groups = {}
469
+ for param_name in parameter_names:
470
+ layer_id = num_layers
471
+ this_scale = layer_decays[layer_id]
472
+ if param_name.startswith(apply_to):
473
+ layer_id = model.get_layer_id(param_name)
474
+ this_scale = layer_decays[layer_id]
475
+ # Overrides
476
+ for override in overrides:
477
+ if fnmatch.fnmatchcase(param_name, override["pattern"]):
478
+ this_scale = float(override["value"])
479
+ layer_id = override["pattern"]
480
+ break
481
+
482
+ if layer_id not in layer_cfg_groups:
483
+ curr_param = {
484
+ "option": scheduler_cfg["option"],
485
+ "scheduler": ValueScaler(
486
+ scheduler_cfg["scheduler"], this_scale
487
+ ),
488
+ "parameter_names": {param_name},
489
+ }
490
+ else:
491
+ curr_param = layer_cfg_groups[layer_id]
492
+ curr_param["parameter_names"].add(param_name)
493
+ layer_cfg_groups[layer_id] = curr_param
494
+
495
+ for layer_cfg in layer_cfg_groups.values():
496
+ curr_cfg_group.append(layer_cfg)
497
+
498
+ final_scheduler_cfgs.append(curr_cfg_group)
499
+ return final_scheduler_cfgs
OVOW/third_party/sam3/sam3/train/optim/schedulers.py ADDED
@@ -0,0 +1,43 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ # Copyright (c) Meta Platforms, Inc. and affiliates. All Rights Reserved
2
+
3
+ # pyre-unsafe
4
+
5
+ import math
6
+
7
+
8
+ class InverseSquareRootParamScheduler:
9
+ def __init__(
10
+ self,
11
+ base_lr: float,
12
+ warmup_steps: int,
13
+ cooldown_steps: int,
14
+ timescale: int,
15
+ ):
16
+ self.base_lr = base_lr
17
+ self.warmup_steps = warmup_steps
18
+ self.cooldown_steps = cooldown_steps
19
+ self.timescale = timescale
20
+
21
+ def __call__(self, step: int, where: float):
22
+ lr = self.base_lr
23
+
24
+ if where > 0:
25
+ total_steps = step / where
26
+ progress = (step - self.warmup_steps) / float(
27
+ total_steps - self.warmup_steps
28
+ )
29
+ progress = max(min(progress, 1), 0)
30
+ else:
31
+ progress = 0
32
+ total_steps = 1
33
+
34
+ shift = self.timescale - self.warmup_steps
35
+ if self.warmup_steps < step:
36
+ lr = lr / math.sqrt((step + shift) / self.timescale)
37
+
38
+ if self.warmup_steps:
39
+ lr = lr * min(1.0, step / self.warmup_steps)
40
+ if self.cooldown_steps:
41
+ lr = lr * min(1.0, (total_steps - step) / self.cooldown_steps)
42
+
43
+ return lr
OVOW/third_party/sam3/sam3/train/train.py ADDED
@@ -0,0 +1,338 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ # Copyright (c) Meta Platforms, Inc. and affiliates. All Rights Reserved
2
+
3
+ # pyre-unsafe
4
+
5
+ import logging
6
+ import os
7
+ import random
8
+ import sys
9
+ import traceback
10
+ from argparse import ArgumentParser
11
+ from copy import deepcopy
12
+
13
+ import submitit
14
+ import torch
15
+ from hydra import compose, initialize_config_module
16
+ from hydra.utils import instantiate
17
+ from iopath.common.file_io import g_pathmgr
18
+ from omegaconf import OmegaConf
19
+ from sam3.train.utils.train_utils import makedir, register_omegaconf_resolvers
20
+ from tqdm import tqdm
21
+
22
+
23
+ os.environ["HYDRA_FULL_ERROR"] = "1"
24
+
25
+
26
+ class SlurmEvent:
27
+ QUEUED = "QUEUED"
28
+ START = "START"
29
+ FINISH = "FINISH"
30
+ JOB_ERROR = "JOB_ERROR"
31
+ SLURM_SIGNAL = "SLURM_SIGNAL"
32
+
33
+
34
+ def handle_custom_resolving(cfg):
35
+ # We'll resolve the config here, so we can catch mistakes early.
36
+ # However, we need to pass the un-resolved config to the launcher
37
+ # (because DVC resolving needs to be done on the node it will run on)
38
+ # First, do a copy without triggering resolving
39
+ cfg_resolved = OmegaConf.to_container(cfg, resolve=False)
40
+ cfg_resolved = OmegaConf.create(cfg_resolved)
41
+ return cfg_resolved
42
+
43
+
44
+ def single_proc_run(local_rank, main_port, cfg, world_size):
45
+ """Single GPU process"""
46
+ os.environ["MASTER_ADDR"] = "localhost"
47
+ os.environ["MASTER_PORT"] = str(main_port)
48
+ os.environ["RANK"] = str(local_rank)
49
+ os.environ["LOCAL_RANK"] = str(local_rank)
50
+ os.environ["WORLD_SIZE"] = str(world_size)
51
+ try:
52
+ register_omegaconf_resolvers()
53
+ except Exception as e:
54
+ logging.info(e)
55
+
56
+ trainer = instantiate(cfg.trainer, _recursive_=False)
57
+ trainer.run()
58
+
59
+
60
+ def single_node_runner(cfg, main_port: int):
61
+ assert cfg.launcher.num_nodes == 1
62
+ # assert cfg.launcher.gpus_per_node == 1
63
+ num_proc = cfg.launcher.gpus_per_node
64
+ torch.multiprocessing.set_start_method(
65
+ "spawn"
66
+ ) # CUDA runtime does not support `fork`
67
+ if num_proc == 1:
68
+ # directly call single_proc so we can easily set breakpoints
69
+ # mp.spawn does not let us set breakpoints
70
+ single_proc_run(local_rank=0, main_port=main_port, cfg=cfg, world_size=num_proc)
71
+ else:
72
+ mp_runner = torch.multiprocessing.start_processes
73
+ args = (main_port, cfg, num_proc)
74
+ # Note: using "fork" below, "spawn" causes time and error regressions. Using
75
+ # spawn changes the default multiprocessing context to spawn, which doesn't
76
+ # interact well with the dataloaders (likely due to the use of OpenCV).
77
+ mp_runner(single_proc_run, args=args, nprocs=num_proc, start_method="spawn")
78
+
79
+
80
+ def format_exception(e: Exception, limit=20):
81
+ traceback_str = "".join(traceback.format_tb(e.__traceback__, limit=limit))
82
+ return f"{type(e).__name__}: {e}\nTraceback:\n{traceback_str}"
83
+
84
+
85
+ class SubmititRunner(submitit.helpers.Checkpointable):
86
+ """A callable which is passed to submitit to launch the jobs."""
87
+
88
+ def __init__(self, port, cfg):
89
+ self.cfg = cfg
90
+ self.port = port
91
+ self.has_setup = False
92
+
93
+ def run_trainer(self):
94
+ job_env = submitit.JobEnvironment()
95
+ # Need to add this again so the hydra.job.set_env PYTHONPATH
96
+ # is also set when launching jobs.
97
+ add_pythonpath_to_sys_path()
98
+ os.environ["MASTER_ADDR"] = job_env.hostnames[0]
99
+ os.environ["MASTER_PORT"] = str(self.port)
100
+ os.environ["RANK"] = str(job_env.global_rank)
101
+ os.environ["LOCAL_RANK"] = str(job_env.local_rank)
102
+ os.environ["WORLD_SIZE"] = str(job_env.num_tasks)
103
+
104
+ register_omegaconf_resolvers()
105
+ cfg_resolved = OmegaConf.to_container(self.cfg, resolve=False)
106
+ cfg_resolved = OmegaConf.create(cfg_resolved)
107
+
108
+ trainer = instantiate(cfg_resolved.trainer, _recursive_=False)
109
+ trainer.run()
110
+
111
+ def __call__(self):
112
+ job_env = submitit.JobEnvironment()
113
+ self.setup_job_info(job_env.job_id, job_env.global_rank)
114
+ try:
115
+ self.run_trainer()
116
+ except Exception as e:
117
+ # Log the exception. Then raise it again (as what SubmititRunner currently does).
118
+ message = format_exception(e)
119
+ logging.error(message)
120
+ raise e
121
+
122
+ def setup_job_info(self, job_id, rank):
123
+ """Set up slurm job info"""
124
+ self.job_info = {
125
+ "job_id": job_id,
126
+ "rank": rank,
127
+ "cluster": self.cfg.get("cluster", None),
128
+ "experiment_log_dir": self.cfg.launcher.experiment_log_dir,
129
+ }
130
+
131
+ self.has_setup = True
132
+
133
+
134
+ def add_pythonpath_to_sys_path():
135
+ if "PYTHONPATH" not in os.environ or not os.environ["PYTHONPATH"]:
136
+ return
137
+ sys.path = os.environ["PYTHONPATH"].split(":") + sys.path
138
+
139
+
140
+ def main(args) -> None:
141
+ cfg = compose(config_name=args.config)
142
+ if cfg.launcher.experiment_log_dir is None:
143
+ cfg.launcher.experiment_log_dir = os.path.join(
144
+ os.getcwd(), "sam3_logs", args.config
145
+ )
146
+ print("###################### Train App Config ####################")
147
+ print(OmegaConf.to_yaml(cfg))
148
+ print("############################################################")
149
+
150
+ add_pythonpath_to_sys_path()
151
+ makedir(cfg.launcher.experiment_log_dir)
152
+ with g_pathmgr.open(
153
+ os.path.join(cfg.launcher.experiment_log_dir, "config.yaml"), "w"
154
+ ) as f:
155
+ f.write(OmegaConf.to_yaml(cfg))
156
+
157
+ cfg_resolved = OmegaConf.to_container(cfg, resolve=False)
158
+ cfg_resolved = OmegaConf.create(cfg_resolved)
159
+
160
+ with g_pathmgr.open(
161
+ os.path.join(cfg.launcher.experiment_log_dir, "config_resolved.yaml"), "w"
162
+ ) as f:
163
+ f.write(OmegaConf.to_yaml(cfg_resolved, resolve=True))
164
+
165
+ submitit_conf = cfg.get("submitit", None)
166
+ assert submitit_conf is not None, "Missing submitit config"
167
+
168
+ experiment_log_dir = cfg.launcher.experiment_log_dir
169
+ print(f"Experiment Log Dir:\n{experiment_log_dir}")
170
+ submitit_dir = os.path.join(experiment_log_dir, "submitit_logs")
171
+
172
+ # Prioritize cmd line args
173
+ cfg.launcher.gpus_per_node = (
174
+ args.num_gpus if args.num_gpus is not None else cfg.launcher.gpus_per_node
175
+ )
176
+ cfg.launcher.num_nodes = (
177
+ args.num_nodes if args.num_nodes is not None else cfg.launcher.num_nodes
178
+ )
179
+ submitit_conf.use_cluster = (
180
+ args.use_cluster if args.use_cluster is not None else submitit_conf.use_cluster
181
+ )
182
+ if submitit_conf.use_cluster:
183
+ executor = submitit.AutoExecutor(folder=submitit_dir)
184
+ submitit_conf.partition = (
185
+ args.partition
186
+ if args.partition is not None
187
+ else submitit_conf.get("partition", None)
188
+ )
189
+ submitit_conf.account = (
190
+ args.account
191
+ if args.account is not None
192
+ else submitit_conf.get("account", None)
193
+ )
194
+ submitit_conf.qos = (
195
+ args.qos if args.qos is not None else submitit_conf.get("qos", None)
196
+ )
197
+ job_kwargs = {
198
+ "timeout_min": 60 * submitit_conf.timeout_hour,
199
+ "name": (
200
+ submitit_conf.name if hasattr(submitit_conf, "name") else args.config
201
+ ),
202
+ "slurm_partition": submitit_conf.partition,
203
+ "gpus_per_node": cfg.launcher.gpus_per_node,
204
+ "tasks_per_node": cfg.launcher.gpus_per_node, # one task per GPU
205
+ "cpus_per_task": submitit_conf.cpus_per_task,
206
+ "nodes": cfg.launcher.num_nodes,
207
+ "slurm_additional_parameters": {
208
+ "exclude": " ".join(submitit_conf.get("exclude_nodes", [])),
209
+ },
210
+ }
211
+ if "include_nodes" in submitit_conf:
212
+ assert len(submitit_conf["include_nodes"]) >= cfg.launcher.num_nodes, (
213
+ "Not enough nodes"
214
+ )
215
+ job_kwargs["slurm_additional_parameters"]["nodelist"] = " ".join(
216
+ submitit_conf["include_nodes"]
217
+ )
218
+ if submitit_conf.account is not None:
219
+ job_kwargs["slurm_additional_parameters"]["account"] = submitit_conf.account
220
+ if submitit_conf.qos is not None:
221
+ job_kwargs["slurm_additional_parameters"]["qos"] = submitit_conf.qos
222
+
223
+ if submitit_conf.get("mem_gb", None) is not None:
224
+ job_kwargs["mem_gb"] = submitit_conf.mem_gb
225
+ elif submitit_conf.get("mem", None) is not None:
226
+ job_kwargs["slurm_mem"] = submitit_conf.mem
227
+
228
+ if submitit_conf.get("constraints", None) is not None:
229
+ job_kwargs["slurm_constraint"] = submitit_conf.constraints
230
+
231
+ if submitit_conf.get("comment", None) is not None:
232
+ job_kwargs["slurm_comment"] = submitit_conf.comment
233
+
234
+ # Supports only cpu-bind option within srun_args. New options can be added here
235
+ if submitit_conf.get("srun_args", None) is not None:
236
+ job_kwargs["slurm_srun_args"] = []
237
+ if submitit_conf.srun_args.get("cpu_bind", None) is not None:
238
+ job_kwargs["slurm_srun_args"].extend(
239
+ ["--cpu-bind", submitit_conf.srun_args.cpu_bind]
240
+ )
241
+
242
+ print("###################### SLURM Config ####################")
243
+ print(job_kwargs)
244
+ print("##########################################")
245
+ executor.update_parameters(**job_kwargs)
246
+
247
+ if (
248
+ "job_array" in submitit_conf
249
+ and submitit_conf.job_array.get("num_tasks", -1) > 0
250
+ ):
251
+ num_tasks = submitit_conf.job_array.num_tasks
252
+ job_array_config_dir = os.path.join(
253
+ cfg.launcher.experiment_log_dir, "job_array_configs"
254
+ )
255
+ makedir(job_array_config_dir)
256
+
257
+ job_indices = range(num_tasks)
258
+ ports = random.sample(
259
+ range(submitit_conf.port_range[0], submitit_conf.port_range[1] + 1),
260
+ k=len(job_indices),
261
+ )
262
+
263
+ jobs_runners_configs = []
264
+ with executor.batch():
265
+ task_index = 0
266
+ for indices, main_port in tqdm(zip(job_indices, ports)):
267
+ curr_cfg = deepcopy(cfg)
268
+ curr_cfg.submitit.job_array["task_index"] = task_index
269
+ curr_cfg_resolved = handle_custom_resolving(cfg)
270
+ runner = SubmititRunner(main_port, curr_cfg)
271
+ job = executor.submit(runner)
272
+ jobs_runners_configs.append(
273
+ (job, runner, curr_cfg, curr_cfg_resolved)
274
+ )
275
+ task_index += 1
276
+
277
+ for job, runner, job_cfg, job_cfg_resolved in jobs_runners_configs:
278
+ print("Submitit Job ID:", job.job_id)
279
+
280
+ # Save job specific config
281
+ job_array_config_file = os.path.join(
282
+ job_array_config_dir, "{}.config.yaml".format(job.job_id)
283
+ )
284
+ with g_pathmgr.open(job_array_config_file, "w") as f:
285
+ f.write(OmegaConf.to_yaml(job_cfg))
286
+
287
+ job_array_config_resolved_file = os.path.join(
288
+ job_array_config_dir, "{}.config_resolved.yaml".format(job.job_id)
289
+ )
290
+ with g_pathmgr.open(job_array_config_resolved_file, "w") as f:
291
+ f.write(OmegaConf.to_yaml(job_cfg_resolved, resolve=True))
292
+
293
+ runner.setup_job_info(job.job_id, rank=0)
294
+ # runner.log_event(event_type=SlurmEvent.QUEUED)
295
+ else:
296
+ main_port = random.randint(
297
+ submitit_conf.port_range[0], submitit_conf.port_range[1]
298
+ )
299
+ runner = SubmititRunner(main_port, cfg)
300
+ job = executor.submit(runner)
301
+ print(f"Submitit Job ID: {job.job_id}")
302
+ runner.setup_job_info(job.job_id, rank=0)
303
+
304
+ else:
305
+ cfg.launcher.num_nodes = 1
306
+ main_port = random.randint(
307
+ submitit_conf.port_range[0], submitit_conf.port_range[1]
308
+ )
309
+ single_node_runner(cfg, main_port)
310
+
311
+
312
+ if __name__ == "__main__":
313
+ initialize_config_module("sam3.train", version_base="1.2")
314
+ parser = ArgumentParser()
315
+ parser.add_argument(
316
+ "-c",
317
+ "--config",
318
+ required=True,
319
+ type=str,
320
+ help="path to config file (e.g. configs/roboflow_v100_full_ft_100_images.yaml)",
321
+ )
322
+ parser.add_argument(
323
+ "--use-cluster",
324
+ type=int,
325
+ default=None,
326
+ help="whether to launch on a cluster, 0: run locally, 1: run on a cluster",
327
+ )
328
+ parser.add_argument("--partition", type=str, default=None, help="SLURM partition")
329
+ parser.add_argument("--account", type=str, default=None, help="SLURM account")
330
+ parser.add_argument("--qos", type=str, default=None, help="SLURM qos")
331
+ parser.add_argument(
332
+ "--num-gpus", type=int, default=None, help="number of GPUS per node"
333
+ )
334
+ parser.add_argument("--num-nodes", type=int, default=None, help="Number of nodes")
335
+ args = parser.parse_args()
336
+ args.use_cluster = bool(args.use_cluster) if args.use_cluster is not None else None
337
+ register_omegaconf_resolvers()
338
+ main(args)
OVOW/third_party/sam3/sam3/train/trainer.py ADDED
@@ -0,0 +1,1189 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ # Copyright (c) Meta Platforms, Inc. and affiliates. All Rights Reserved
2
+
3
+ # pyre-unsafe
4
+
5
+ import contextlib
6
+ import fnmatch
7
+ import gc
8
+ import json
9
+ import logging
10
+ import math
11
+ import os
12
+ import time
13
+ from collections import OrderedDict
14
+ from dataclasses import dataclass, field
15
+ from typing import Any, Dict, List, Mapping, Optional
16
+
17
+ import numpy as np
18
+ import torch
19
+ import torch.distributed as dist
20
+ import torch.nn as nn
21
+ from hydra.utils import instantiate
22
+ from iopath.common.file_io import g_pathmgr
23
+ from sam3.model.data_misc import BatchedDatapoint
24
+ from sam3.model.model_misc import SAM3Output
25
+ from sam3.model.utils.misc import copy_data_to_device
26
+ from sam3.train.optim.optimizer import construct_optimizer
27
+ from sam3.train.utils.checkpoint_utils import (
28
+ assert_skipped_parameters_are_frozen,
29
+ exclude_params_matching_unix_pattern,
30
+ load_state_dict_into_model,
31
+ with_check_parameter_frozen,
32
+ )
33
+ from sam3.train.utils.distributed import all_reduce_max, barrier, get_rank
34
+ from sam3.train.utils.logger import Logger, setup_logging
35
+ from sam3.train.utils.train_utils import (
36
+ AverageMeter,
37
+ collect_dict_keys,
38
+ DurationMeter,
39
+ get_amp_type,
40
+ get_machine_local_and_dist_rank,
41
+ get_resume_checkpoint,
42
+ human_readable_time,
43
+ is_dist_avail_and_initialized,
44
+ log_env_variables,
45
+ makedir,
46
+ MemMeter,
47
+ Phase,
48
+ ProgressMeter,
49
+ set_seeds,
50
+ setup_distributed_backend,
51
+ )
52
+
53
+
54
+ CORE_LOSS_KEY = "core_loss"
55
+
56
+
57
+ def unwrap_ddp_if_wrapped(model):
58
+ if isinstance(model, torch.nn.parallel.DistributedDataParallel):
59
+ return model.module
60
+ return model
61
+
62
+
63
+ @dataclass
64
+ class OptimAMPConf:
65
+ enabled: bool = False
66
+ amp_dtype: str = "float16"
67
+
68
+
69
+ @dataclass
70
+ class OptimConf:
71
+ optimizer: torch.optim.Optimizer = None
72
+ options: Optional[Dict[str, Any]] = None
73
+ param_group_modifiers: Optional[List] = None
74
+ amp: Optional[Dict[str, Any]] = None
75
+ gradient_clip: Any = None
76
+ gradient_logger: Any = None
77
+
78
+ def __post_init__(self):
79
+ # amp
80
+ if not isinstance(self.amp, OptimAMPConf):
81
+ if self.amp is None:
82
+ self.amp = {}
83
+ assert isinstance(self.amp, Mapping)
84
+ self.amp = OptimAMPConf(**self.amp)
85
+
86
+
87
+ @dataclass
88
+ class DistributedConf:
89
+ backend: Optional[str] = None # inferred from accelerator type
90
+ comms_dtype: Optional[str] = None
91
+ find_unused_parameters: bool = False
92
+ timeout_mins: int = 30
93
+ gradient_as_bucket_view: bool = False # PyTorch DDP default is False
94
+ static_graph: bool = False # PyTorch DDP default is False
95
+
96
+
97
+ @dataclass
98
+ class CudaConf:
99
+ cudnn_deterministic: bool = False
100
+ cudnn_benchmark: bool = True
101
+ allow_tf32: bool = False
102
+ # if not None, `matmul_allow_tf32` key will override `allow_tf32` for matmul
103
+ matmul_allow_tf32: Optional[bool] = None
104
+ # if not None, `cudnn_allow_tf32` key will override `allow_tf32` for cudnn
105
+ cudnn_allow_tf32: Optional[bool] = None
106
+
107
+
108
+ @dataclass
109
+ class CheckpointConf:
110
+ save_dir: str
111
+ save_freq: int
112
+ save_list: List[int] = field(default_factory=list)
113
+ model_weight_initializer: Any = None
114
+ save_best_meters: List[str] = None
115
+ skip_saving_parameters: List[str] = field(default_factory=list)
116
+ initialize_after_preemption: Optional[bool] = None
117
+ # if not None, training will be resumed from this checkpoint
118
+ resume_from: Optional[str] = None
119
+
120
+ def infer_missing(self):
121
+ if self.initialize_after_preemption is None:
122
+ with_skip_saving = len(self.skip_saving_parameters) > 0
123
+ self.initialize_after_preemption = with_skip_saving
124
+ return self
125
+
126
+
127
+ @dataclass
128
+ class LoggingConf:
129
+ log_dir: str
130
+ log_freq: int # In iterations
131
+ tensorboard_writer: Any
132
+ log_level_primary: str = "INFO"
133
+ log_level_secondary: str = "ERROR"
134
+ log_scalar_frequency: int = 100
135
+ log_visual_frequency: int = 100
136
+ scalar_keys_to_log: Optional[Dict[str, Any]] = None
137
+ log_batch_stats: bool = False
138
+ wandb_writer: Optional[Any] = None
139
+
140
+
141
+ class Trainer:
142
+ """
143
+ Trainer supporting the DDP training strategies.
144
+ """
145
+
146
+ EPSILON = 1e-8
147
+
148
+ def __init__(
149
+ self,
150
+ *, # the order of these args can change at any time, so they are keyword-only
151
+ data: Dict[str, Any],
152
+ model: Dict[str, Any],
153
+ logging: Dict[str, Any],
154
+ checkpoint: Dict[str, Any],
155
+ max_epochs: int,
156
+ mode: str = "train",
157
+ accelerator: str = "cuda",
158
+ seed_value: int = 123,
159
+ val_epoch_freq: int = 1,
160
+ distributed: Dict[str, bool] = None,
161
+ cuda: Dict[str, bool] = None,
162
+ env_variables: Optional[Dict[str, Any]] = None,
163
+ optim: Optional[Dict[str, Any]] = None,
164
+ optim_overrides: Optional[List[Dict[str, Any]]] = None,
165
+ meters: Optional[Dict[str, Any]] = None,
166
+ loss: Optional[Dict[str, Any]] = None,
167
+ skip_first_val: bool = False,
168
+ skip_saving_ckpts: bool = False,
169
+ empty_gpu_mem_cache_after_eval: bool = True,
170
+ gradient_accumulation_steps: int = 1,
171
+ ):
172
+ self._setup_env_variables(env_variables)
173
+ self._setup_timers()
174
+
175
+ self.data_conf = data
176
+ self.model_conf = model
177
+ self.logging_conf = LoggingConf(**logging)
178
+ self.checkpoint_conf = CheckpointConf(**checkpoint).infer_missing()
179
+ self.max_epochs = max_epochs
180
+ self.mode = mode
181
+ self.val_epoch_freq = val_epoch_freq
182
+ self.optim_conf = OptimConf(**optim) if optim is not None else OptimConf()
183
+ self.meters_conf = meters
184
+ self.loss_conf = loss
185
+ self.gradient_accumulation_steps = gradient_accumulation_steps
186
+ distributed = DistributedConf(**distributed or {})
187
+ cuda = CudaConf(**cuda or {})
188
+ self.where = 0.0
189
+
190
+ self.skip_first_val = skip_first_val
191
+ self.skip_saving_ckpts = skip_saving_ckpts
192
+ self.empty_gpu_mem_cache_after_eval = empty_gpu_mem_cache_after_eval
193
+
194
+ self._infer_distributed_backend_if_none(distributed, accelerator)
195
+
196
+ self._setup_device(accelerator)
197
+
198
+ self._setup_torch_dist_and_backend(cuda, distributed)
199
+
200
+ makedir(self.logging_conf.log_dir)
201
+ setup_logging(
202
+ __name__,
203
+ output_dir=self.logging_conf.log_dir,
204
+ rank=self.rank,
205
+ log_level_primary=self.logging_conf.log_level_primary,
206
+ log_level_secondary=self.logging_conf.log_level_secondary,
207
+ )
208
+
209
+ set_seeds(seed_value, self.max_epochs, self.distributed_rank)
210
+ log_env_variables()
211
+
212
+ assert is_dist_avail_and_initialized(), (
213
+ "Torch distributed needs to be initialized before calling the trainer."
214
+ )
215
+
216
+ self._setup_components() # Except Optimizer everything is setup here.
217
+ self._move_to_device()
218
+ self._construct_optimizers()
219
+ self._setup_dataloaders()
220
+
221
+ self.time_elapsed_meter = DurationMeter("Time Elapsed", self.device, ":.2f")
222
+
223
+ if self.checkpoint_conf.resume_from is not None:
224
+ assert os.path.exists(self.checkpoint_conf.resume_from), (
225
+ f"The 'resume_from' checkpoint {self.checkpoint_conf.resume_from} does not exist!"
226
+ )
227
+ dst = os.path.join(self.checkpoint_conf.save_dir, "checkpoint.pt")
228
+ if self.distributed_rank == 0 and not os.path.exists(dst):
229
+ # Copy the "resume_from" checkpoint to the checkpoint folder
230
+ # if there is not a checkpoint to resume from already there
231
+ makedir(self.checkpoint_conf.save_dir)
232
+ g_pathmgr.copy(self.checkpoint_conf.resume_from, dst)
233
+ barrier()
234
+
235
+ self.load_checkpoint()
236
+ self._setup_ddp_distributed_training(distributed, accelerator)
237
+ barrier()
238
+
239
+ def _setup_timers(self):
240
+ """
241
+ Initializes counters for elapsed time and eta.
242
+ """
243
+ self.start_time = time.time()
244
+ self.ckpt_time_elapsed = 0
245
+ self.est_epoch_time = dict.fromkeys([Phase.TRAIN, Phase.VAL], 0)
246
+
247
+ def _get_meters(self, phase_filters=None):
248
+ if self.meters is None:
249
+ return {}
250
+ meters = {}
251
+ for phase, phase_meters in self.meters.items():
252
+ if phase_filters is not None and phase not in phase_filters:
253
+ continue
254
+ for key, key_meters in phase_meters.items():
255
+ if key_meters is None:
256
+ continue
257
+ for name, meter in key_meters.items():
258
+ meters[f"{phase}_{key}/{name}"] = meter
259
+ return meters
260
+
261
+ def _infer_distributed_backend_if_none(self, distributed_conf, accelerator):
262
+ if distributed_conf.backend is None:
263
+ distributed_conf.backend = "nccl" if accelerator == "cuda" else "gloo"
264
+
265
+ def _setup_env_variables(self, env_variables_conf) -> None:
266
+ if env_variables_conf is not None:
267
+ for variable_name, value in env_variables_conf.items():
268
+ os.environ[variable_name] = value
269
+
270
+ def _setup_torch_dist_and_backend(self, cuda_conf, distributed_conf) -> None:
271
+ if torch.cuda.is_available():
272
+ torch.backends.cudnn.deterministic = cuda_conf.cudnn_deterministic
273
+ torch.backends.cudnn.benchmark = cuda_conf.cudnn_benchmark
274
+ torch.backends.cuda.matmul.allow_tf32 = (
275
+ cuda_conf.matmul_allow_tf32
276
+ if cuda_conf.matmul_allow_tf32 is not None
277
+ else cuda_conf.allow_tf32
278
+ )
279
+ torch.backends.cudnn.allow_tf32 = (
280
+ cuda_conf.cudnn_allow_tf32
281
+ if cuda_conf.cudnn_allow_tf32 is not None
282
+ else cuda_conf.allow_tf32
283
+ )
284
+
285
+ self.rank = setup_distributed_backend(
286
+ distributed_conf.backend, distributed_conf.timeout_mins
287
+ )
288
+
289
+ def _setup_device(self, accelerator):
290
+ self.local_rank, self.distributed_rank = get_machine_local_and_dist_rank()
291
+ if accelerator == "cuda":
292
+ self.device = torch.device("cuda", self.local_rank)
293
+ torch.cuda.set_device(self.local_rank)
294
+ elif accelerator == "cpu":
295
+ self.device = torch.device("cpu")
296
+ else:
297
+ raise ValueError(f"Unsupported accelerator: {accelerator}")
298
+
299
+ def _setup_ddp_distributed_training(self, distributed_conf, accelerator):
300
+ assert isinstance(self.model, torch.nn.Module)
301
+
302
+ self.model = nn.parallel.DistributedDataParallel(
303
+ self.model,
304
+ device_ids=[self.local_rank] if accelerator == "cuda" else [],
305
+ find_unused_parameters=distributed_conf.find_unused_parameters,
306
+ gradient_as_bucket_view=distributed_conf.gradient_as_bucket_view,
307
+ static_graph=distributed_conf.static_graph,
308
+ )
309
+ if distributed_conf.comms_dtype is not None: # noqa
310
+ from torch.distributed.algorithms import ddp_comm_hooks
311
+
312
+ amp_type = get_amp_type(distributed_conf.comms_dtype)
313
+ if amp_type == torch.bfloat16:
314
+ hook = ddp_comm_hooks.default_hooks.bf16_compress_hook
315
+ logging.info("Enabling bfloat16 grad communication")
316
+ else:
317
+ hook = ddp_comm_hooks.default_hooks.fp16_compress_hook
318
+ logging.info("Enabling fp16 grad communication")
319
+ process_group = None
320
+ self.model.register_comm_hook(process_group, hook)
321
+
322
+ def _move_to_device(self):
323
+ logging.info(
324
+ f"Moving components to device {self.device} and local rank {self.local_rank}."
325
+ )
326
+
327
+ self.model.to(self.device)
328
+
329
+ logging.info(
330
+ f"Done moving components to device {self.device} and local rank {self.local_rank}."
331
+ )
332
+
333
+ def save_checkpoint(self, epoch, checkpoint_names=None):
334
+ if self.skip_saving_ckpts:
335
+ logging.info(
336
+ "skip_saving_ckpts is set to True. So, no checkpoints have been saved."
337
+ )
338
+ return
339
+ checkpoint_folder = self.checkpoint_conf.save_dir
340
+ makedir(checkpoint_folder)
341
+ if checkpoint_names is None:
342
+ checkpoint_names = ["checkpoint"]
343
+ if (
344
+ self.checkpoint_conf.save_freq > 0
345
+ and (int(epoch) % self.checkpoint_conf.save_freq == 0)
346
+ ) or int(epoch) in self.checkpoint_conf.save_list:
347
+ checkpoint_names.append(f"checkpoint_{int(epoch)}")
348
+
349
+ checkpoint_paths = []
350
+ for ckpt_name in checkpoint_names:
351
+ checkpoint_paths.append(os.path.join(checkpoint_folder, f"{ckpt_name}.pt"))
352
+
353
+ state_dict = unwrap_ddp_if_wrapped(self.model).state_dict()
354
+ state_dict = exclude_params_matching_unix_pattern(
355
+ patterns=self.checkpoint_conf.skip_saving_parameters, state_dict=state_dict
356
+ )
357
+
358
+ checkpoint = {
359
+ "model": state_dict,
360
+ "optimizer": self.optim.optimizer.state_dict(),
361
+ "epoch": epoch,
362
+ "loss": self.loss.state_dict(),
363
+ "steps": self.steps,
364
+ "time_elapsed": self.time_elapsed_meter.val,
365
+ "best_meter_values": self.best_meter_values,
366
+ }
367
+ if self.optim_conf.amp.enabled:
368
+ checkpoint["scaler"] = self.scaler.state_dict()
369
+
370
+ # DDP checkpoints are only saved on rank 0 (all workers are identical)
371
+ if self.distributed_rank != 0:
372
+ return
373
+
374
+ for checkpoint_path in checkpoint_paths:
375
+ self._save_checkpoint(checkpoint, checkpoint_path)
376
+
377
+ def _save_checkpoint(self, checkpoint, checkpoint_path):
378
+ """
379
+ Save a checkpoint while guarding against the job being killed in the middle
380
+ of checkpoint saving (which corrupts the checkpoint file and ruins the
381
+ entire training since usually only the last checkpoint is kept per run).
382
+
383
+ We first save the new checkpoint to a temp file (with a '.tmp' suffix), and
384
+ and move it to overwrite the old checkpoint_path.
385
+ """
386
+ checkpoint_path_tmp = f"{checkpoint_path}.tmp"
387
+ with g_pathmgr.open(checkpoint_path_tmp, "wb") as f:
388
+ torch.save(checkpoint, f)
389
+ # after torch.save is completed, replace the old checkpoint with the new one
390
+ if g_pathmgr.exists(checkpoint_path):
391
+ # remove the old checkpoint_path file first (otherwise g_pathmgr.mv fails)
392
+ g_pathmgr.rm(checkpoint_path)
393
+ success = g_pathmgr.mv(checkpoint_path_tmp, checkpoint_path)
394
+ assert success
395
+
396
+ def load_checkpoint(self):
397
+ ckpt_path = get_resume_checkpoint(self.checkpoint_conf.save_dir)
398
+ if ckpt_path is None:
399
+ self._init_model_state()
400
+ else:
401
+ if self.checkpoint_conf.initialize_after_preemption:
402
+ self._call_model_initializer()
403
+ self._load_resuming_checkpoint(ckpt_path)
404
+
405
+ def _init_model_state(self):
406
+ # Checking that parameters that won't be saved are indeed frozen
407
+ # We do this check here before even saving the model to catch errors
408
+ # are early as possible and not at the end of the first epoch
409
+ assert_skipped_parameters_are_frozen(
410
+ patterns=self.checkpoint_conf.skip_saving_parameters,
411
+ model=self.model,
412
+ )
413
+
414
+ # Checking that parameters that won't be saved are initialized from
415
+ # within the model definition, unless `initialize_after_preemption`
416
+ # is explicitly set to `True`. If not, this is a bug, and after
417
+ # preemption, the `skip_saving_parameters` will have random values
418
+ allow_init_skip_parameters = self.checkpoint_conf.initialize_after_preemption
419
+ with with_check_parameter_frozen(
420
+ patterns=self.checkpoint_conf.skip_saving_parameters,
421
+ model=self.model,
422
+ disabled=allow_init_skip_parameters,
423
+ ):
424
+ self._call_model_initializer()
425
+
426
+ def _call_model_initializer(self):
427
+ model_weight_initializer = instantiate(
428
+ self.checkpoint_conf.model_weight_initializer
429
+ )
430
+ if model_weight_initializer is not None:
431
+ logging.info(
432
+ f"Loading pretrained checkpoint from {self.checkpoint_conf.model_weight_initializer}"
433
+ )
434
+ self.model = model_weight_initializer(model=self.model)
435
+
436
+ def _load_resuming_checkpoint(self, ckpt_path: str):
437
+ logging.info(f"Resuming training from {ckpt_path}")
438
+
439
+ with g_pathmgr.open(ckpt_path, "rb") as f:
440
+ checkpoint = torch.load(f, map_location="cpu")
441
+ load_state_dict_into_model(
442
+ model=self.model,
443
+ state_dict=checkpoint["model"],
444
+ ignore_missing_keys=self.checkpoint_conf.skip_saving_parameters,
445
+ )
446
+
447
+ self.optim.optimizer.load_state_dict(checkpoint["optimizer"])
448
+ self.loss.load_state_dict(checkpoint["loss"], strict=True)
449
+ self.epoch = checkpoint["epoch"]
450
+ self.steps = checkpoint["steps"]
451
+ self.ckpt_time_elapsed = checkpoint.get("time_elapsed")
452
+
453
+ if self.optim_conf.amp.enabled and "scaler" in checkpoint:
454
+ self.scaler.load_state_dict(checkpoint["scaler"])
455
+
456
+ self.best_meter_values = checkpoint.get("best_meter_values", {})
457
+
458
+ if "train_dataset" in checkpoint and self.train_dataset is not None:
459
+ self.train_dataset.load_checkpoint_state(checkpoint["train_dataset"])
460
+
461
+ def is_intermediate_val_epoch(self, epoch):
462
+ skip_epoch = self.skip_first_val and epoch == 0
463
+ return (
464
+ epoch % self.val_epoch_freq == 0
465
+ and epoch < self.max_epochs - 1
466
+ and not skip_epoch
467
+ )
468
+
469
+ def _find_loss(self, key: str):
470
+ if key in self.loss:
471
+ return self.loss[key]
472
+
473
+ assert key != "all", "Loss must be specified for key='all'"
474
+ assert "default" in self.loss, (
475
+ f"Key {key} not found in losss, and no default provided"
476
+ )
477
+ return self.loss["default"]
478
+
479
+ def _find_meter(self, phase: str, key: str):
480
+ if key in self.meters[phase]:
481
+ return self.meters[phase][key]
482
+
483
+ for cand_key, meter in self.meters[phase].items():
484
+ if fnmatch.fnmatch(key, cand_key):
485
+ return meter
486
+ return None
487
+
488
+ def _step(
489
+ self,
490
+ batch: BatchedDatapoint,
491
+ model: nn.Module,
492
+ phase: str,
493
+ ):
494
+ key, batch = batch.popitem()
495
+ batch = copy_data_to_device(batch, self.device, non_blocking=True)
496
+
497
+ find_stages = model(batch)
498
+ find_targets = [
499
+ unwrap_ddp_if_wrapped(model).back_convert(x) for x in batch.find_targets
500
+ ]
501
+ batch_size = len(batch.img_batch)
502
+ loss = self._find_loss(key)(find_stages, find_targets)
503
+
504
+ loss_str = f"Losses/{phase}_{key}_loss"
505
+
506
+ loss_log_str = os.path.join("Step_Losses", loss_str)
507
+
508
+ # loss contains multiple sub-components we wish to log
509
+ step_losses = {}
510
+ if isinstance(loss, dict):
511
+ step_losses.update(
512
+ {f"Losses/{phase}_{key}_{k}": v for k, v in loss.items()}
513
+ )
514
+ loss = self._log_loss_detailed_and_return_core_loss(
515
+ loss, loss_log_str, self.steps[phase]
516
+ )
517
+
518
+ if self.steps[phase] % self.logging_conf.log_scalar_frequency == 0:
519
+ self.logger.log(
520
+ loss_log_str,
521
+ loss,
522
+ self.steps[phase],
523
+ )
524
+
525
+ self.steps[phase] += 1
526
+
527
+ ret_tuple = {loss_str: loss}, batch_size, step_losses
528
+
529
+ if phase not in self.meters:
530
+ return ret_tuple
531
+
532
+ meters_dict = self._find_meter(phase, key)
533
+ if meters_dict is None:
534
+ return ret_tuple
535
+ if meters_dict is not None:
536
+ for _, meter in meters_dict.items():
537
+ meter.update(
538
+ find_stages=find_stages,
539
+ find_metadatas=batch.find_metadatas,
540
+ model=model,
541
+ batch=batch,
542
+ key=key,
543
+ )
544
+ # Cleanup memory
545
+ if isinstance(find_stages, SAM3Output):
546
+ for fs in find_stages:
547
+ for k in list(fs.keys()):
548
+ del fs[k]
549
+
550
+ return ret_tuple
551
+
552
+ def run(self):
553
+ assert self.mode in ["train", "train_only", "val"]
554
+ if self.mode == "train":
555
+ if self.epoch > 0:
556
+ logging.info(f"Resuming training from epoch: {self.epoch}")
557
+ # resuming from a checkpoint
558
+ if self.is_intermediate_val_epoch(self.epoch - 1):
559
+ logging.info("Running previous val epoch")
560
+ self.epoch -= 1
561
+ self.run_val()
562
+ self.epoch += 1
563
+ self.run_train()
564
+ self.run_val()
565
+ elif self.mode == "val":
566
+ self.run_val()
567
+ elif self.mode == "train_only":
568
+ self.run_train()
569
+
570
+ def _setup_dataloaders(self):
571
+ self.train_dataset = None
572
+ self.val_dataset = None
573
+
574
+ if self.mode in ["train", "val"]:
575
+ self.val_dataset = instantiate(self.data_conf.get(Phase.VAL, None))
576
+
577
+ if self.mode in ["train", "train_only"]:
578
+ self.train_dataset = instantiate(self.data_conf.train)
579
+
580
+ def run_train(self):
581
+ while self.epoch < self.max_epochs:
582
+ dataloader = self.train_dataset.get_loader(epoch=int(self.epoch))
583
+ barrier()
584
+ outs = self.train_epoch(dataloader)
585
+ self.logger.log_dict(outs, self.epoch) # Logged only on rank 0
586
+
587
+ # log train to text file.
588
+ if self.distributed_rank == 0:
589
+ with g_pathmgr.open(
590
+ os.path.join(self.logging_conf.log_dir, "train_stats.json"),
591
+ "a",
592
+ ) as f:
593
+ f.write(json.dumps(outs) + "\n")
594
+
595
+ # Save checkpoint before validating
596
+ self.save_checkpoint(self.epoch + 1)
597
+
598
+ del dataloader
599
+ gc.collect()
600
+
601
+ # Run val, not running on last epoch since will run after the
602
+ # loop anyway
603
+ if self.is_intermediate_val_epoch(self.epoch):
604
+ self.run_val()
605
+ if torch.cuda.is_available() and self.empty_gpu_mem_cache_after_eval:
606
+ # release memory buffers held by the model during eval (which typically
607
+ # involves a lot more frames in video grounding that during training)
608
+ torch.cuda.empty_cache()
609
+
610
+ if self.distributed_rank == 0:
611
+ self.best_meter_values.update(self._get_trainer_state("train"))
612
+ with g_pathmgr.open(
613
+ os.path.join(self.logging_conf.log_dir, "best_stats.json"),
614
+ "a",
615
+ ) as f:
616
+ f.write(json.dumps(self.best_meter_values) + "\n")
617
+
618
+ self.epoch += 1
619
+ # epoch was incremented in the loop but the val step runs out of the loop
620
+ self.epoch -= 1
621
+
622
+ def run_val(self):
623
+ if not self.val_dataset:
624
+ return
625
+
626
+ dataloader = self.val_dataset.get_loader(epoch=int(self.epoch))
627
+ outs = self.val_epoch(dataloader, phase=Phase.VAL)
628
+ del dataloader
629
+ gc.collect()
630
+ self.logger.log_dict(outs, self.epoch) # Logged only on rank 0
631
+
632
+ if self.distributed_rank == 0:
633
+ with g_pathmgr.open(
634
+ os.path.join(self.logging_conf.log_dir, "val_stats.json"),
635
+ "a",
636
+ ) as f:
637
+ f.write(json.dumps(outs) + "\n")
638
+
639
+ def val_epoch(self, val_loader, phase):
640
+ batch_time = AverageMeter("Batch Time", self.device, ":.2f")
641
+ data_time = AverageMeter("Data Time", self.device, ":.2f")
642
+ mem = MemMeter("Mem (GB)", self.device, ":.2f")
643
+
644
+ iters_per_epoch = len(val_loader)
645
+
646
+ curr_phases = [phase]
647
+ curr_models = [self.model]
648
+
649
+ loss_names = []
650
+ for p in curr_phases:
651
+ for key in self.loss.keys():
652
+ loss_names.append(f"Losses/{p}_{key}_loss")
653
+
654
+ loss_mts = OrderedDict(
655
+ [(name, AverageMeter(name, self.device, ":.2e")) for name in loss_names]
656
+ )
657
+ extra_loss_mts = {}
658
+
659
+ for model in curr_models:
660
+ model.eval()
661
+ if hasattr(unwrap_ddp_if_wrapped(model), "on_validation_epoch_start"):
662
+ unwrap_ddp_if_wrapped(model).on_validation_epoch_start()
663
+
664
+ progress = ProgressMeter(
665
+ iters_per_epoch,
666
+ [batch_time, data_time, mem, self.time_elapsed_meter, *loss_mts.values()],
667
+ self._get_meters(curr_phases),
668
+ prefix="Val Epoch: [{}]".format(self.epoch),
669
+ )
670
+
671
+ end = time.time()
672
+
673
+ for data_iter, batch in enumerate(val_loader):
674
+ # measure data loading time
675
+ data_time.update(time.time() - end)
676
+
677
+ # batch = batch.to(self.device, non_blocking=True)
678
+
679
+ # compute output
680
+ with torch.no_grad():
681
+ with torch.amp.autocast(
682
+ device_type="cuda",
683
+ enabled=(self.optim_conf.amp.enabled if self.optim_conf else False),
684
+ dtype=(
685
+ get_amp_type(self.optim_conf.amp.amp_dtype)
686
+ if self.optim_conf
687
+ else None
688
+ ),
689
+ ):
690
+ for phase, model in zip(curr_phases, curr_models):
691
+ loss_dict, batch_size, extra_losses = self._step(
692
+ batch,
693
+ model,
694
+ phase,
695
+ )
696
+
697
+ assert len(loss_dict) == 1
698
+ loss_key, loss = loss_dict.popitem()
699
+
700
+ if loss_key in loss_mts:
701
+ loss_mts[loss_key].update(loss.item(), batch_size)
702
+
703
+ for k, v in extra_losses.items():
704
+ if k not in extra_loss_mts:
705
+ extra_loss_mts[k] = AverageMeter(k, self.device, ":.2e")
706
+ extra_loss_mts[k].update(v.item(), batch_size)
707
+
708
+ # measure elapsed time
709
+ batch_time.update(time.time() - end)
710
+ end = time.time()
711
+
712
+ self.time_elapsed_meter.update(
713
+ time.time() - self.start_time + self.ckpt_time_elapsed
714
+ )
715
+
716
+ if torch.cuda.is_available():
717
+ mem.update(reset_peak_usage=True)
718
+
719
+ if data_iter % self.logging_conf.log_freq == 0:
720
+ progress.display(data_iter)
721
+
722
+ if data_iter % self.logging_conf.log_scalar_frequency == 0:
723
+ # Log progress meters.
724
+ for progress_meter in progress.meters:
725
+ self.logger.log(
726
+ os.path.join("Step_Stats", phase, progress_meter.name),
727
+ progress_meter.val,
728
+ self.steps[Phase.VAL],
729
+ )
730
+
731
+ if data_iter % 10 == 0:
732
+ dist.barrier()
733
+
734
+ self.est_epoch_time[phase] = batch_time.avg * iters_per_epoch
735
+ self._log_timers(phase)
736
+ for model in curr_models:
737
+ if hasattr(unwrap_ddp_if_wrapped(model), "on_validation_epoch_end"):
738
+ unwrap_ddp_if_wrapped(model).on_validation_epoch_end()
739
+
740
+ out_dict = self._log_meters_and_save_best_ckpts(curr_phases)
741
+
742
+ for k, v in loss_mts.items():
743
+ out_dict[k] = v.avg
744
+ for k, v in extra_loss_mts.items():
745
+ out_dict[k] = v.avg
746
+
747
+ for phase in curr_phases:
748
+ out_dict.update(self._get_trainer_state(phase))
749
+ self._reset_meters(curr_phases)
750
+ logging.info(f"Meters: {out_dict}")
751
+ return out_dict
752
+
753
+ def _get_trainer_state(self, phase):
754
+ return {
755
+ "Trainer/where": self.where,
756
+ "Trainer/epoch": self.epoch,
757
+ f"Trainer/steps_{phase}": self.steps[phase],
758
+ }
759
+
760
+ def train_epoch(self, train_loader):
761
+ # Init stat meters
762
+ batch_time_meter = AverageMeter("Batch Time", self.device, ":.2f")
763
+ data_time_meter = AverageMeter("Data Time", self.device, ":.2f")
764
+ mem_meter = MemMeter("Mem (GB)", self.device, ":.2f")
765
+ data_times = []
766
+ phase = Phase.TRAIN
767
+
768
+ iters_per_epoch = len(train_loader)
769
+
770
+ loss_names = []
771
+ for batch_key in self.loss.keys():
772
+ loss_names.append(f"Losses/{phase}_{batch_key}_loss")
773
+
774
+ loss_mts = OrderedDict(
775
+ [(name, AverageMeter(name, self.device, ":.2e")) for name in loss_names]
776
+ )
777
+ extra_loss_mts = {}
778
+
779
+ progress = ProgressMeter(
780
+ iters_per_epoch,
781
+ [
782
+ batch_time_meter,
783
+ data_time_meter,
784
+ mem_meter,
785
+ self.time_elapsed_meter,
786
+ *loss_mts.values(),
787
+ ],
788
+ self._get_meters([phase]),
789
+ prefix="Train Epoch: [{}]".format(self.epoch),
790
+ )
791
+
792
+ # Model training loop
793
+ self.model.train()
794
+ end = time.time()
795
+
796
+ for data_iter, batch in enumerate(train_loader):
797
+ # measure data loading time
798
+ data_time_meter.update(time.time() - end)
799
+ data_times.append(data_time_meter.val)
800
+ # batch = batch.to(
801
+ # self.device, non_blocking=True
802
+ # ) # move tensors in a tensorclass
803
+
804
+ try:
805
+ self._run_step(batch, phase, loss_mts, extra_loss_mts)
806
+
807
+ # compute gradient and do optim step
808
+ exact_epoch = self.epoch + float(data_iter) / iters_per_epoch
809
+ self.where = float(exact_epoch) / self.max_epochs
810
+ assert self.where <= 1 + self.EPSILON
811
+ if self.where < 1.0:
812
+ self.optim.step_schedulers(
813
+ self.where, step=int(exact_epoch * iters_per_epoch)
814
+ )
815
+ else:
816
+ logging.warning(
817
+ f"Skipping scheduler update since the training is at the end, i.e, {self.where} of [0,1]."
818
+ )
819
+
820
+ # Log schedulers
821
+ if data_iter % self.logging_conf.log_scalar_frequency == 0:
822
+ for j, param_group in enumerate(self.optim.optimizer.param_groups):
823
+ for option in self.optim.schedulers[j]:
824
+ optim_prefix = (
825
+ "" + f"{j}_"
826
+ if len(self.optim.optimizer.param_groups) > 1
827
+ else ""
828
+ )
829
+ self.logger.log(
830
+ os.path.join("Optim", f"{optim_prefix}", option),
831
+ param_group[option],
832
+ self.steps[phase],
833
+ )
834
+
835
+ # Clipping gradients and detecting diverging gradients
836
+ if self.gradient_clipper is not None:
837
+ self.scaler.unscale_(self.optim.optimizer)
838
+ self.gradient_clipper(model=self.model)
839
+
840
+ if self.gradient_logger is not None:
841
+ self.gradient_logger(
842
+ self.model, rank=self.distributed_rank, where=self.where
843
+ )
844
+
845
+ # Optimizer step: the scaler will make sure gradients are not
846
+ # applied if the gradients are infinite
847
+ self.scaler.step(self.optim.optimizer)
848
+ self.scaler.update()
849
+
850
+ # measure elapsed time
851
+ batch_time_meter.update(time.time() - end)
852
+ end = time.time()
853
+
854
+ self.time_elapsed_meter.update(
855
+ time.time() - self.start_time + self.ckpt_time_elapsed
856
+ )
857
+
858
+ mem_meter.update(reset_peak_usage=True)
859
+ if data_iter % self.logging_conf.log_freq == 0:
860
+ progress.display(data_iter)
861
+
862
+ if data_iter % self.logging_conf.log_scalar_frequency == 0:
863
+ # Log progress meters.
864
+ for progress_meter in progress.meters:
865
+ self.logger.log(
866
+ os.path.join("Step_Stats", phase, progress_meter.name),
867
+ progress_meter.val,
868
+ self.steps[phase],
869
+ )
870
+
871
+ # Catching NaN/Inf errors in the loss
872
+ except FloatingPointError as e:
873
+ raise e
874
+
875
+ self.est_epoch_time[Phase.TRAIN] = batch_time_meter.avg * iters_per_epoch
876
+ self._log_timers(Phase.TRAIN)
877
+ self._log_sync_data_times(Phase.TRAIN, data_times)
878
+
879
+ out_dict = self._log_meters_and_save_best_ckpts([Phase.TRAIN])
880
+
881
+ for k, v in loss_mts.items():
882
+ out_dict[k] = v.avg
883
+ for k, v in extra_loss_mts.items():
884
+ out_dict[k] = v.avg
885
+ out_dict.update(self._get_trainer_state(phase))
886
+ logging.info(f"Losses and meters: {out_dict}")
887
+ self._reset_meters([phase])
888
+ return out_dict
889
+
890
+ def _log_sync_data_times(self, phase, data_times):
891
+ data_times = all_reduce_max(torch.tensor(data_times)).tolist()
892
+ steps = range(self.steps[phase] - len(data_times), self.steps[phase])
893
+ for step, data_time in zip(steps, data_times):
894
+ if step % self.logging_conf.log_scalar_frequency == 0:
895
+ self.logger.log(
896
+ os.path.join("Step_Stats", phase, "Data Time Synced"),
897
+ data_time,
898
+ step,
899
+ )
900
+
901
+ def _run_step(
902
+ self,
903
+ batch: BatchedDatapoint,
904
+ phase: str,
905
+ loss_mts: Dict[str, AverageMeter],
906
+ extra_loss_mts: Dict[str, AverageMeter],
907
+ raise_on_error: bool = True,
908
+ ):
909
+ """
910
+ Run the forward / backward
911
+ """
912
+
913
+ # it's important to set grads to None, especially with Adam since 0
914
+ # grads will also update a model even if the step doesn't produce
915
+ # gradients
916
+ self.optim.zero_grad(set_to_none=True)
917
+
918
+ if self.gradient_accumulation_steps > 1:
919
+ assert isinstance(batch, list), (
920
+ f"Expected a list of batches, got {type(batch)}"
921
+ )
922
+ assert len(batch) == self.gradient_accumulation_steps, (
923
+ f"Expected {self.gradient_accumulation_steps} batches, got {len(batch)}"
924
+ )
925
+ accum_steps = len(batch)
926
+ else:
927
+ accum_steps = 1
928
+ batch = [batch]
929
+
930
+ for i, chunked_batch in enumerate(batch):
931
+ ddp_context = (
932
+ self.model.no_sync()
933
+ if i < accum_steps - 1
934
+ else contextlib.nullcontext()
935
+ )
936
+ with ddp_context:
937
+ with torch.amp.autocast(
938
+ device_type="cuda",
939
+ enabled=self.optim_conf.amp.enabled,
940
+ dtype=get_amp_type(self.optim_conf.amp.amp_dtype),
941
+ ):
942
+ loss_dict, batch_size, extra_losses = self._step(
943
+ chunked_batch,
944
+ self.model,
945
+ phase,
946
+ )
947
+
948
+ assert len(loss_dict) == 1
949
+ loss_key, loss = loss_dict.popitem()
950
+
951
+ if not math.isfinite(loss.item()):
952
+ error_msg = f"Loss is {loss.item()}, attempting to stop training"
953
+ logging.error(error_msg)
954
+ if raise_on_error:
955
+ raise FloatingPointError(error_msg)
956
+ else:
957
+ return
958
+
959
+ self.scaler.scale(loss).backward()
960
+ loss_mts[loss_key].update(loss.item(), batch_size)
961
+ for extra_loss_key, extra_loss in extra_losses.items():
962
+ if extra_loss_key not in extra_loss_mts:
963
+ extra_loss_mts[extra_loss_key] = AverageMeter(
964
+ extra_loss_key, self.device, ":.2e"
965
+ )
966
+ extra_loss_mts[extra_loss_key].update(extra_loss.item(), batch_size)
967
+
968
+ def _log_meters_and_save_best_ckpts(self, phases: List[str]):
969
+ logging.info("Synchronizing meters")
970
+ out_dict = {}
971
+ checkpoint_save_keys = []
972
+ for key, meter in self._get_meters(phases).items():
973
+ meter_output = meter.compute_synced()
974
+ is_better_check = getattr(meter, "is_better", None)
975
+
976
+ for meter_subkey, meter_value in meter_output.items():
977
+ out_dict[os.path.join("Meters_train", key, meter_subkey)] = meter_value
978
+
979
+ if is_better_check is None:
980
+ continue
981
+
982
+ tracked_meter_key = os.path.join(key, meter_subkey)
983
+ if tracked_meter_key not in self.best_meter_values or is_better_check(
984
+ meter_value,
985
+ self.best_meter_values[tracked_meter_key],
986
+ ):
987
+ self.best_meter_values[tracked_meter_key] = meter_value
988
+
989
+ if (
990
+ self.checkpoint_conf.save_best_meters is not None
991
+ and key in self.checkpoint_conf.save_best_meters
992
+ ):
993
+ checkpoint_save_keys.append(tracked_meter_key.replace("/", "_"))
994
+
995
+ if len(checkpoint_save_keys) > 0:
996
+ self.save_checkpoint(self.epoch + 1, checkpoint_save_keys)
997
+
998
+ return out_dict
999
+
1000
+ def _log_timers(self, phase):
1001
+ time_remaining = 0
1002
+ epochs_remaining = self.max_epochs - self.epoch - 1
1003
+ val_epochs_remaining = sum(
1004
+ n % self.val_epoch_freq == 0 for n in range(self.epoch, self.max_epochs)
1005
+ )
1006
+
1007
+ # Adding the guaranteed val run at the end if val_epoch_freq doesn't coincide with
1008
+ # the end epoch.
1009
+ if (self.max_epochs - 1) % self.val_epoch_freq != 0:
1010
+ val_epochs_remaining += 1
1011
+
1012
+ # Remove the current val run from estimate
1013
+ if phase == Phase.VAL:
1014
+ val_epochs_remaining -= 1
1015
+
1016
+ time_remaining += (
1017
+ epochs_remaining * self.est_epoch_time[Phase.TRAIN]
1018
+ + val_epochs_remaining * self.est_epoch_time[Phase.VAL]
1019
+ )
1020
+
1021
+ self.logger.log(
1022
+ os.path.join("Step_Stats", phase, self.time_elapsed_meter.name),
1023
+ self.time_elapsed_meter.val,
1024
+ self.steps[phase],
1025
+ )
1026
+
1027
+ logging.info(f"Estimated time remaining: {human_readable_time(time_remaining)}")
1028
+
1029
+ def _reset_meters(self, phases: str) -> None:
1030
+ for meter in self._get_meters(phases).values():
1031
+ meter.reset()
1032
+
1033
+ def _check_val_key_match(self, val_keys, phase):
1034
+ if val_keys is not None:
1035
+ # Check if there are any duplicates
1036
+ assert len(val_keys) == len(set(val_keys)), (
1037
+ f"Duplicate keys in val datasets, keys: {val_keys}"
1038
+ )
1039
+
1040
+ # Check that the keys match the meter keys
1041
+ if self.meters_conf is not None and phase in self.meters_conf:
1042
+ assert set(val_keys) == set(self.meters_conf[phase].keys()), (
1043
+ f"Keys in val datasets do not match the keys in meters."
1044
+ f"\nMissing in meters: {set(val_keys) - set(self.meters_conf[phase].keys())}"
1045
+ f"\nMissing in val datasets: {set(self.meters_conf[phase].keys()) - set(val_keys)}"
1046
+ )
1047
+
1048
+ if self.loss_conf is not None:
1049
+ loss_keys = set(self.loss_conf.keys()) - set(["all"])
1050
+ if "default" not in loss_keys:
1051
+ for k in val_keys:
1052
+ assert k in loss_keys, (
1053
+ f"Error: key {k} is not defined in the losses, and no default is set"
1054
+ )
1055
+
1056
+ def _setup_components(self):
1057
+ # Get the keys for all the val datasets, if any
1058
+ val_phase = Phase.VAL
1059
+ val_keys = None
1060
+ if self.data_conf.get(val_phase, None) is not None:
1061
+ val_keys = collect_dict_keys(self.data_conf[val_phase])
1062
+ # Additional checks on the sanity of the config for val datasets
1063
+ self._check_val_key_match(val_keys, phase=val_phase)
1064
+
1065
+ logging.info("Setting up components: Model, loss, optim, meters etc.")
1066
+ self.epoch = 0
1067
+ self.steps = {Phase.TRAIN: 0, Phase.VAL: 0}
1068
+
1069
+ self.logger = Logger(self.logging_conf)
1070
+
1071
+ self.model = instantiate(self.model_conf, _convert_="all")
1072
+ print_model_summary(self.model)
1073
+
1074
+ self.loss = None
1075
+ if self.loss_conf:
1076
+ self.loss = {
1077
+ key: el # wrap_base_loss(el)
1078
+ for (key, el) in instantiate(self.loss_conf, _convert_="all").items()
1079
+ }
1080
+ self.loss = nn.ModuleDict(self.loss)
1081
+
1082
+ self.meters = {}
1083
+ self.best_meter_values = {}
1084
+ if self.meters_conf:
1085
+ self.meters = instantiate(self.meters_conf, _convert_="all")
1086
+
1087
+ self.scaler = torch.amp.GradScaler(
1088
+ self.device,
1089
+ enabled=self.optim_conf.amp.enabled if self.optim_conf else False,
1090
+ )
1091
+
1092
+ self.gradient_clipper = (
1093
+ instantiate(self.optim_conf.gradient_clip) if self.optim_conf else None
1094
+ )
1095
+ self.gradient_logger = (
1096
+ instantiate(self.optim_conf.gradient_logger) if self.optim_conf else None
1097
+ )
1098
+
1099
+ logging.info("Finished setting up components: Model, loss, optim, meters etc.")
1100
+
1101
+ def _construct_optimizers(self):
1102
+ self.optim = construct_optimizer(
1103
+ self.model,
1104
+ self.optim_conf.optimizer,
1105
+ self.optim_conf.options,
1106
+ self.optim_conf.param_group_modifiers,
1107
+ )
1108
+
1109
+ def _log_loss_detailed_and_return_core_loss(self, loss, loss_str, step):
1110
+ core_loss = loss.pop(CORE_LOSS_KEY)
1111
+ if step % self.logging_conf.log_scalar_frequency == 0:
1112
+ for k in loss:
1113
+ log_str = os.path.join(loss_str, k)
1114
+ self.logger.log(log_str, loss[k], step)
1115
+ return core_loss
1116
+
1117
+
1118
+ def print_model_summary(model: torch.nn.Module, log_dir: str = ""):
1119
+ """
1120
+ Prints the model and the number of parameters in the model.
1121
+ # Multiple packages provide this info in a nice table format
1122
+ # However, they need us to provide an `input` (as they also write down the output sizes)
1123
+ # Our models are complex, and a single input is restrictive.
1124
+ # https://github.com/sksq96/pytorch-summary
1125
+ # https://github.com/nmhkahn/torchsummaryX
1126
+ """
1127
+ if get_rank() != 0:
1128
+ return
1129
+ param_kwargs = {}
1130
+ trainable_parameters = sum(
1131
+ p.numel() for p in model.parameters(**param_kwargs) if p.requires_grad
1132
+ )
1133
+ total_parameters = sum(p.numel() for p in model.parameters(**param_kwargs))
1134
+ non_trainable_parameters = total_parameters - trainable_parameters
1135
+ logging.info("==" * 10)
1136
+ logging.info(f"Summary for model {type(model)}")
1137
+ logging.info(f"Model is {model}")
1138
+ logging.info(f"\tTotal parameters {get_human_readable_count(total_parameters)}")
1139
+ logging.info(
1140
+ f"\tTrainable parameters {get_human_readable_count(trainable_parameters)}"
1141
+ )
1142
+ logging.info(
1143
+ f"\tNon-Trainable parameters {get_human_readable_count(non_trainable_parameters)}"
1144
+ )
1145
+ logging.info("==" * 10)
1146
+
1147
+ if log_dir:
1148
+ output_fpath = os.path.join(log_dir, "model.txt")
1149
+ with g_pathmgr.open(output_fpath, "w") as f:
1150
+ print(model, file=f)
1151
+
1152
+
1153
+ PARAMETER_NUM_UNITS = [" ", "K", "M", "B", "T"]
1154
+
1155
+
1156
+ def get_human_readable_count(number: int) -> str:
1157
+ """
1158
+ Abbreviates an integer number with K, M, B, T for thousands, millions,
1159
+ billions and trillions, respectively.
1160
+ Examples:
1161
+ >>> get_human_readable_count(123)
1162
+ '123 '
1163
+ >>> get_human_readable_count(1234) # (one thousand)
1164
+ '1.2 K'
1165
+ >>> get_human_readable_count(2e6) # (two million)
1166
+ '2.0 M'
1167
+ >>> get_human_readable_count(3e9) # (three billion)
1168
+ '3.0 B'
1169
+ >>> get_human_readable_count(4e14) # (four hundred trillion)
1170
+ '400 T'
1171
+ >>> get_human_readable_count(5e15) # (more than trillion)
1172
+ '5,000 T'
1173
+ Args:
1174
+ number: a positive integer number
1175
+ Return:
1176
+ A string formatted according to the pattern described above.
1177
+ """
1178
+ assert number >= 0
1179
+ labels = PARAMETER_NUM_UNITS
1180
+ num_digits = int(np.floor(np.log10(number)) + 1 if number > 0 else 1)
1181
+ num_groups = int(np.ceil(num_digits / 3))
1182
+ num_groups = min(num_groups, len(labels)) # don't abbreviate beyond trillions
1183
+ shift = -3 * (num_groups - 1)
1184
+ number = number * (10**shift)
1185
+ index = num_groups - 1
1186
+ if index < 1 or number >= 100:
1187
+ return f"{int(number):,d} {labels[index]}"
1188
+ else:
1189
+ return f"{number:,.1f} {labels[index]}"
OVOW/third_party/sam3/sam3/train/transforms/__init__.py ADDED
@@ -0,0 +1,3 @@
 
 
 
 
1
+ # Copyright (c) Meta Platforms, Inc. and affiliates. All Rights Reserved
2
+
3
+ # pyre-unsafe
OVOW/third_party/sam3/sam3/train/transforms/basic.py ADDED
@@ -0,0 +1,456 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ # Copyright (c) Meta Platforms, Inc. and affiliates. All Rights Reserved
2
+
3
+ # pyre-unsafe
4
+
5
+ """
6
+ Transforms and data augmentation for both image + bbox.
7
+ """
8
+
9
+ import math
10
+ import random
11
+ from typing import Iterable
12
+
13
+ import PIL
14
+ import torch
15
+ import torchvision.transforms as T
16
+ import torchvision.transforms.functional as F
17
+ from sam3.model.box_ops import box_xyxy_to_cxcywh
18
+ from sam3.model.data_misc import interpolate
19
+
20
+
21
+ def crop(image, target, region):
22
+ cropped_image = F.crop(image, *region)
23
+
24
+ target = target.copy()
25
+ i, j, h, w = region
26
+
27
+ # should we do something wrt the original size?
28
+ target["size"] = torch.tensor([h, w])
29
+
30
+ fields = ["labels", "area", "iscrowd", "positive_map"]
31
+
32
+ if "boxes" in target:
33
+ boxes = target["boxes"]
34
+ max_size = torch.as_tensor([w, h], dtype=torch.float32)
35
+ cropped_boxes = boxes - torch.as_tensor([j, i, j, i], dtype=torch.float32)
36
+ cropped_boxes = torch.min(cropped_boxes.reshape(-1, 2, 2), max_size)
37
+ cropped_boxes = cropped_boxes.clamp(min=0)
38
+ area = (cropped_boxes[:, 1, :] - cropped_boxes[:, 0, :]).prod(dim=1)
39
+ target["boxes"] = cropped_boxes.reshape(-1, 4)
40
+ target["area"] = area
41
+ fields.append("boxes")
42
+
43
+ if "input_boxes" in target:
44
+ boxes = target["input_boxes"]
45
+ max_size = torch.as_tensor([w, h], dtype=torch.float32)
46
+ cropped_boxes = boxes - torch.as_tensor([j, i, j, i], dtype=torch.float32)
47
+ cropped_boxes = torch.min(cropped_boxes.reshape(-1, 2, 2), max_size)
48
+ cropped_boxes = cropped_boxes.clamp(min=0)
49
+ target["input_boxes"] = cropped_boxes.reshape(-1, 4)
50
+
51
+ if "masks" in target:
52
+ # FIXME should we update the area here if there are no boxes?
53
+ target["masks"] = target["masks"][:, i : i + h, j : j + w]
54
+ fields.append("masks")
55
+
56
+ # remove elements for which the boxes or masks that have zero area
57
+ if "boxes" in target or "masks" in target:
58
+ # favor boxes selection when defining which elements to keep
59
+ # this is compatible with previous implementation
60
+ if "boxes" in target:
61
+ cropped_boxes = target["boxes"].reshape(-1, 2, 2)
62
+ keep = torch.all(cropped_boxes[:, 1, :] > cropped_boxes[:, 0, :], dim=1)
63
+ else:
64
+ keep = target["masks"].flatten(1).any(1)
65
+
66
+ for field in fields:
67
+ if field in target:
68
+ target[field] = target[field][keep]
69
+
70
+ return cropped_image, target
71
+
72
+
73
+ def hflip(image, target):
74
+ flipped_image = F.hflip(image)
75
+
76
+ w, h = image.size
77
+
78
+ target = target.copy()
79
+ if "boxes" in target:
80
+ boxes = target["boxes"]
81
+ boxes = boxes[:, [2, 1, 0, 3]] * torch.as_tensor(
82
+ [-1, 1, -1, 1]
83
+ ) + torch.as_tensor([w, 0, w, 0])
84
+ target["boxes"] = boxes
85
+
86
+ if "input_boxes" in target:
87
+ boxes = target["input_boxes"]
88
+ boxes = boxes[:, [2, 1, 0, 3]] * torch.as_tensor(
89
+ [-1, 1, -1, 1]
90
+ ) + torch.as_tensor([w, 0, w, 0])
91
+ target["input_boxes"] = boxes
92
+
93
+ if "masks" in target:
94
+ target["masks"] = target["masks"].flip(-1)
95
+
96
+ if "text_input" in target:
97
+ text_input = (
98
+ target["text_input"]
99
+ .replace("left", "[TMP]")
100
+ .replace("right", "left")
101
+ .replace("[TMP]", "right")
102
+ )
103
+ target["text_input"] = text_input
104
+
105
+ return flipped_image, target
106
+
107
+
108
+ def resize(image, target, size, max_size=None, square=False):
109
+ # size can be min_size (scalar) or (w, h) tuple
110
+
111
+ def get_size_with_aspect_ratio(image_size, size, max_size=None):
112
+ w, h = image_size
113
+ if max_size is not None:
114
+ min_original_size = float(min((w, h)))
115
+ max_original_size = float(max((w, h)))
116
+ if max_original_size / min_original_size * size > max_size:
117
+ size = int(round(max_size * min_original_size / max_original_size))
118
+
119
+ if (w <= h and w == size) or (h <= w and h == size):
120
+ return (h, w)
121
+
122
+ if w < h:
123
+ ow = size
124
+ oh = int(size * h / w)
125
+ else:
126
+ oh = size
127
+ ow = int(size * w / h)
128
+
129
+ return (oh, ow)
130
+
131
+ def get_size(image_size, size, max_size=None):
132
+ if isinstance(size, (list, tuple)):
133
+ return size[::-1]
134
+ else:
135
+ return get_size_with_aspect_ratio(image_size, size, max_size)
136
+
137
+ if square:
138
+ size = size, size
139
+ else:
140
+ size = get_size(image.size, size, max_size)
141
+ rescaled_image = F.resize(image, size)
142
+
143
+ if target is None:
144
+ return rescaled_image, None
145
+
146
+ ratios = tuple(
147
+ float(s) / float(s_orig) for s, s_orig in zip(rescaled_image.size, image.size)
148
+ )
149
+ ratio_width, ratio_height = ratios
150
+
151
+ target = target.copy()
152
+ if "boxes" in target:
153
+ boxes = target["boxes"]
154
+ scaled_boxes = boxes * torch.as_tensor(
155
+ [ratio_width, ratio_height, ratio_width, ratio_height], dtype=torch.float32
156
+ )
157
+ target["boxes"] = scaled_boxes
158
+ if "input_boxes" in target:
159
+ boxes = target["input_boxes"]
160
+ scaled_boxes = boxes * torch.as_tensor(
161
+ [ratio_width, ratio_height, ratio_width, ratio_height], dtype=torch.float32
162
+ )
163
+ target["input_boxes"] = scaled_boxes
164
+
165
+ if "area" in target:
166
+ area = target["area"]
167
+ scaled_area = area * (ratio_width * ratio_height)
168
+ target["area"] = scaled_area
169
+
170
+ h, w = size
171
+ target["size"] = torch.tensor([h, w])
172
+
173
+ if "masks" in target:
174
+ target["masks"] = (
175
+ interpolate(target["masks"][:, None].float(), size, mode="nearest")[:, 0]
176
+ > 0.5
177
+ )
178
+
179
+ return rescaled_image, target
180
+
181
+
182
+ def pad(image, target, padding):
183
+ if len(padding) == 2:
184
+ # assumes that we only pad on the bottom right corners
185
+ padded_image = F.pad(image, (0, 0, padding[0], padding[1]))
186
+ else:
187
+ # left, top, right, bottom
188
+ padded_image = F.pad(image, (padding[0], padding[1], padding[2], padding[3]))
189
+ if target is None:
190
+ return padded_image, None
191
+ target = target.copy()
192
+
193
+ w, h = padded_image.size
194
+
195
+ # should we do something wrt the original size?
196
+ target["size"] = torch.tensor([h, w])
197
+ if "boxes" in target and len(padding) == 4:
198
+ boxes = target["boxes"]
199
+ boxes = boxes + torch.as_tensor(
200
+ [padding[0], padding[1], padding[0], padding[1]], dtype=torch.float32
201
+ )
202
+ target["boxes"] = boxes
203
+
204
+ if "input_boxes" in target and len(padding) == 4:
205
+ boxes = target["input_boxes"]
206
+ boxes = boxes + torch.as_tensor(
207
+ [padding[0], padding[1], padding[0], padding[1]], dtype=torch.float32
208
+ )
209
+ target["input_boxes"] = boxes
210
+
211
+ if "masks" in target:
212
+ if len(padding) == 2:
213
+ target["masks"] = torch.nn.functional.pad(
214
+ target["masks"], (0, padding[0], 0, padding[1])
215
+ )
216
+ else:
217
+ target["masks"] = torch.nn.functional.pad(
218
+ target["masks"], (padding[0], padding[2], padding[1], padding[3])
219
+ )
220
+ return padded_image, target
221
+
222
+
223
+ class RandomCrop:
224
+ def __init__(self, size):
225
+ self.size = size
226
+
227
+ def __call__(self, img, target):
228
+ region = T.RandomCrop.get_params(img, self.size)
229
+ return crop(img, target, region)
230
+
231
+
232
+ class RandomSizeCrop:
233
+ def __init__(self, min_size: int, max_size: int, respect_boxes: bool = False):
234
+ self.min_size = min_size
235
+ self.max_size = max_size
236
+ self.respect_boxes = respect_boxes # if True we can't crop a box out
237
+
238
+ def __call__(self, img: PIL.Image.Image, target: dict):
239
+ init_boxes = len(target["boxes"])
240
+ init_boxes_tensor = target["boxes"].clone()
241
+ if self.respect_boxes and init_boxes > 0:
242
+ minW, minH, maxW, maxH = (
243
+ min(img.width, self.min_size),
244
+ min(img.width, self.min_size),
245
+ min(img.width, self.max_size),
246
+ min(img.height, self.max_size),
247
+ )
248
+ minX, minY = (
249
+ target["boxes"][:, 0].max().item() + 10.0,
250
+ target["boxes"][:, 1].max().item() + 10.0,
251
+ )
252
+ minX = min(img.width, minX)
253
+ minY = min(img.height, minY)
254
+ maxX, maxY = (
255
+ target["boxes"][:, 2].min().item() - 10,
256
+ target["boxes"][:, 3].min().item() - 10,
257
+ )
258
+ maxX = max(0.0, maxX)
259
+ maxY = max(0.0, maxY)
260
+ minW = max(minW, minX - maxX)
261
+ minH = max(minH, minY - maxY)
262
+ w = random.uniform(minW, max(minW, maxW))
263
+ h = random.uniform(minH, max(minH, maxH))
264
+ if minX > maxX:
265
+ # i = random.uniform(max(0, minX - w + 1), max(maxX, max(0, minX - w + 1)))
266
+ i = random.uniform(max(0, minX - w), max(maxX, max(0, minX - w)))
267
+ else:
268
+ i = random.uniform(
269
+ max(0, minX - w + 1), max(maxX - 1, max(0, minX - w + 1))
270
+ )
271
+ if minY > maxY:
272
+ # j = random.uniform(max(0, minY - h + 1), max(maxY, max(0, minY - h + 1)))
273
+ j = random.uniform(max(0, minY - h), max(maxY, max(0, minY - h)))
274
+ else:
275
+ j = random.uniform(
276
+ max(0, minY - h + 1), max(maxY - 1, max(0, minY - h + 1))
277
+ )
278
+ result_img, result_target = crop(img, target, [j, i, h, w])
279
+ assert len(result_target["boxes"]) == init_boxes, (
280
+ f"img_w={img.width}\timg_h={img.height}\tminX={minX}\tminY={minY}\tmaxX={maxX}\tmaxY={maxY}\tminW={minW}\tminH={minH}\tmaxW={maxW}\tmaxH={maxH}\tw={w}\th={h}\ti={i}\tj={j}\tinit_boxes={init_boxes_tensor}\tresults={result_target['boxes']}"
281
+ )
282
+
283
+ return result_img, result_target
284
+ else:
285
+ w = random.randint(self.min_size, min(img.width, self.max_size))
286
+ h = random.randint(self.min_size, min(img.height, self.max_size))
287
+ region = T.RandomCrop.get_params(img, (h, w))
288
+ result_img, result_target = crop(img, target, region)
289
+ return result_img, result_target
290
+
291
+
292
+ class CenterCrop:
293
+ def __init__(self, size):
294
+ self.size = size
295
+
296
+ def __call__(self, img, target):
297
+ image_width, image_height = img.size
298
+ crop_height, crop_width = self.size
299
+ crop_top = int(round((image_height - crop_height) / 2.0))
300
+ crop_left = int(round((image_width - crop_width) / 2.0))
301
+ return crop(img, target, (crop_top, crop_left, crop_height, crop_width))
302
+
303
+
304
+ class RandomHorizontalFlip:
305
+ def __init__(self, p=0.5):
306
+ self.p = p
307
+
308
+ def __call__(self, img, target):
309
+ if random.random() < self.p:
310
+ return hflip(img, target)
311
+ return img, target
312
+
313
+
314
+ class RandomResize:
315
+ def __init__(self, sizes, max_size=None, square=False):
316
+ if isinstance(sizes, int):
317
+ sizes = (sizes,)
318
+ assert isinstance(sizes, Iterable)
319
+ self.sizes = list(sizes)
320
+ self.max_size = max_size
321
+ self.square = square
322
+
323
+ def __call__(self, img, target=None):
324
+ size = random.choice(self.sizes)
325
+ return resize(img, target, size, self.max_size, square=self.square)
326
+
327
+
328
+ class RandomPad:
329
+ def __init__(self, max_pad):
330
+ self.max_pad = max_pad
331
+
332
+ def __call__(self, img, target):
333
+ pad_x = random.randint(0, self.max_pad)
334
+ pad_y = random.randint(0, self.max_pad)
335
+ return pad(img, target, (pad_x, pad_y))
336
+
337
+
338
+ class PadToSize:
339
+ def __init__(self, size):
340
+ self.size = size
341
+
342
+ def __call__(self, img, target):
343
+ w, h = img.size
344
+ pad_x = self.size - w
345
+ pad_y = self.size - h
346
+ assert pad_x >= 0 and pad_y >= 0
347
+ pad_left = random.randint(0, pad_x)
348
+ pad_right = pad_x - pad_left
349
+ pad_top = random.randint(0, pad_y)
350
+ pad_bottom = pad_y - pad_top
351
+ return pad(img, target, (pad_left, pad_top, pad_right, pad_bottom))
352
+
353
+
354
+ class Identity:
355
+ def __call__(self, img, target):
356
+ return img, target
357
+
358
+
359
+ class RandomSelect:
360
+ """
361
+ Randomly selects between transforms1 and transforms2,
362
+ with probability p for transforms1 and (1 - p) for transforms2
363
+ """
364
+
365
+ def __init__(self, transforms1=None, transforms2=None, p=0.5):
366
+ self.transforms1 = transforms1 or Identity()
367
+ self.transforms2 = transforms2 or Identity()
368
+ self.p = p
369
+
370
+ def __call__(self, img, target):
371
+ if random.random() < self.p:
372
+ return self.transforms1(img, target)
373
+ return self.transforms2(img, target)
374
+
375
+
376
+ class ToTensor:
377
+ def __call__(self, img, target):
378
+ return F.to_tensor(img), target
379
+
380
+
381
+ class RandomErasing:
382
+ def __init__(self, *args, **kwargs):
383
+ self.eraser = T.RandomErasing(*args, **kwargs)
384
+
385
+ def __call__(self, img, target):
386
+ return self.eraser(img), target
387
+
388
+
389
+ class Normalize:
390
+ def __init__(self, mean, std):
391
+ self.mean = mean
392
+ self.std = std
393
+
394
+ def __call__(self, image, target=None):
395
+ image = F.normalize(image, mean=self.mean, std=self.std)
396
+ if target is None:
397
+ return image, None
398
+ target = target.copy()
399
+ h, w = image.shape[-2:]
400
+ if "boxes" in target:
401
+ boxes = target["boxes"]
402
+ boxes = box_xyxy_to_cxcywh(boxes)
403
+ boxes = boxes / torch.tensor([w, h, w, h], dtype=torch.float32)
404
+ target["boxes"] = boxes
405
+ if "input_boxes" in target:
406
+ boxes = target["input_boxes"]
407
+ boxes = box_xyxy_to_cxcywh(boxes)
408
+ boxes = boxes / torch.tensor([w, h, w, h], dtype=torch.float32)
409
+ target["input_boxes"] = boxes
410
+ return image, target
411
+
412
+
413
+ class RemoveDifficult:
414
+ def __init__(self, enabled=False):
415
+ self.remove_difficult = enabled
416
+
417
+ def __call__(self, image, target=None):
418
+ if target is None:
419
+ return image, None
420
+ target = target.copy()
421
+ keep = ~target["iscrowd"].to(torch.bool) | (not self.remove_difficult)
422
+ if "boxes" in target:
423
+ target["boxes"] = target["boxes"][keep]
424
+ target["labels"] = target["labels"][keep]
425
+ target["iscrowd"] = target["iscrowd"][keep]
426
+ return image, target
427
+
428
+
429
+ class Compose:
430
+ def __init__(self, transforms):
431
+ self.transforms = transforms
432
+
433
+ def __call__(self, image, target):
434
+ for t in self.transforms:
435
+ image, target = t(image, target)
436
+ return image, target
437
+
438
+ def __repr__(self):
439
+ format_string = self.__class__.__name__ + "("
440
+ for t in self.transforms:
441
+ format_string += "\n"
442
+ format_string += " {0}".format(t)
443
+ format_string += "\n)"
444
+ return format_string
445
+
446
+
447
+ def get_random_resize_scales(size, min_size, rounded):
448
+ stride = 128 if rounded else 32
449
+ min_size = int(stride * math.ceil(min_size / stride))
450
+ scales = list(range(min_size, size + 1, stride))
451
+ return scales
452
+
453
+
454
+ def get_random_resize_max_size(size, ratio=5 / 3):
455
+ max_size = round(ratio * size)
456
+ return max_size
OVOW/third_party/sam3/sam3/train/transforms/basic_for_api.py ADDED
@@ -0,0 +1,1395 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ # Copyright (c) Meta Platforms, Inc. and affiliates. All Rights Reserved
2
+
3
+ # pyre-unsafe
4
+
5
+ """
6
+ Transforms and data augmentation for both image + bbox.
7
+ """
8
+
9
+ import logging
10
+ import numbers
11
+ import random
12
+ from collections.abc import Sequence
13
+ from typing import Iterable
14
+
15
+ import torch
16
+ import torchvision.transforms as T
17
+ import torchvision.transforms.functional as F
18
+ import torchvision.transforms.v2.functional as Fv2
19
+ from PIL import Image as PILImage
20
+ from sam3.model.box_ops import box_xyxy_to_cxcywh, masks_to_boxes
21
+ from sam3.train.data.sam3_image_dataset import Datapoint
22
+ from torchvision.transforms import InterpolationMode
23
+
24
+
25
+ def crop(
26
+ datapoint,
27
+ index,
28
+ region,
29
+ v2=False,
30
+ check_validity=True,
31
+ check_input_validity=True,
32
+ recompute_box_from_mask=False,
33
+ ):
34
+ if v2:
35
+ rtop, rleft, rheight, rwidth = (int(round(r)) for r in region)
36
+ datapoint.images[index].data = Fv2.crop(
37
+ datapoint.images[index].data,
38
+ top=rtop,
39
+ left=rleft,
40
+ height=rheight,
41
+ width=rwidth,
42
+ )
43
+ else:
44
+ datapoint.images[index].data = F.crop(datapoint.images[index].data, *region)
45
+
46
+ i, j, h, w = region
47
+
48
+ # should we do something wrt the original size?
49
+ datapoint.images[index].size = (h, w)
50
+
51
+ for obj in datapoint.images[index].objects:
52
+ # crop the mask
53
+ if obj.segment is not None:
54
+ obj.segment = F.crop(obj.segment, int(i), int(j), int(h), int(w))
55
+
56
+ # crop the bounding box
57
+ if recompute_box_from_mask and obj.segment is not None:
58
+ # here the boxes are still in XYXY format with absolute coordinates (they are
59
+ # converted to CxCyWH with relative coordinates in basic_for_api.NormalizeAPI)
60
+ obj.bbox, obj.area = get_bbox_xyxy_abs_coords_from_mask(obj.segment)
61
+ else:
62
+ if recompute_box_from_mask and obj.segment is None and obj.area > 0:
63
+ logging.warning(
64
+ "Cannot recompute bounding box from mask since `obj.segment` is None. "
65
+ "Falling back to directly cropping from the input bounding box."
66
+ )
67
+ boxes = obj.bbox.view(1, 4)
68
+ max_size = torch.as_tensor([w, h], dtype=torch.float32)
69
+ cropped_boxes = boxes - torch.as_tensor([j, i, j, i], dtype=torch.float32)
70
+ cropped_boxes = torch.min(cropped_boxes.reshape(-1, 2, 2), max_size)
71
+ cropped_boxes = cropped_boxes.clamp(min=0)
72
+ obj.area = (cropped_boxes[:, 1, :] - cropped_boxes[:, 0, :]).prod(dim=1)
73
+ obj.bbox = cropped_boxes.reshape(-1, 4)
74
+
75
+ for query in datapoint.find_queries:
76
+ if query.semantic_target is not None:
77
+ query.semantic_target = F.crop(
78
+ query.semantic_target, int(i), int(j), int(h), int(w)
79
+ )
80
+ if query.image_id == index and query.input_bbox is not None:
81
+ boxes = query.input_bbox
82
+ max_size = torch.as_tensor([w, h], dtype=torch.float32)
83
+ cropped_boxes = boxes - torch.as_tensor([j, i, j, i], dtype=torch.float32)
84
+ cropped_boxes = torch.min(cropped_boxes.reshape(-1, 2, 2), max_size)
85
+ cropped_boxes = cropped_boxes.clamp(min=0)
86
+
87
+ # cur_area = (cropped_boxes[:, 1, :] - cropped_boxes[:, 0, :]).prod(dim=1)
88
+ # if check_input_validity:
89
+ # assert (
90
+ # (cur_area > 0).all().item()
91
+ # ), "Some input box got cropped out by the crop transform"
92
+
93
+ query.input_bbox = cropped_boxes.reshape(-1, 4)
94
+ if query.image_id == index and query.input_points is not None:
95
+ print(
96
+ "Warning! Point cropping with this function may lead to unexpected results"
97
+ )
98
+ points = query.input_points
99
+ # Unlike right-lower box edges, which are exclusive, the
100
+ # point must be in [0, length-1], hence the -1
101
+ max_size = torch.as_tensor([w, h], dtype=torch.float32) - 1
102
+ cropped_points = points - torch.as_tensor([j, i, 0], dtype=torch.float32)
103
+ cropped_points[:, :, :2] = torch.min(cropped_points[:, :, :2], max_size)
104
+ cropped_points[:, :, :2] = cropped_points[:, :, :2].clamp(min=0)
105
+ query.input_points = cropped_points
106
+
107
+ if check_validity:
108
+ # Check that all boxes are still valid
109
+ for obj in datapoint.images[index].objects:
110
+ assert obj.area > 0, "Box {} has no area".format(obj.bbox)
111
+
112
+ return datapoint
113
+
114
+
115
+ def hflip(datapoint, index):
116
+ datapoint.images[index].data = F.hflip(datapoint.images[index].data)
117
+
118
+ w, h = datapoint.images[index].data.size
119
+ for obj in datapoint.images[index].objects:
120
+ boxes = obj.bbox.view(1, 4)
121
+ boxes = boxes[:, [2, 1, 0, 3]] * torch.as_tensor(
122
+ [-1, 1, -1, 1]
123
+ ) + torch.as_tensor([w, 0, w, 0])
124
+ obj.bbox = boxes
125
+ if obj.segment is not None:
126
+ obj.segment = F.hflip(obj.segment)
127
+
128
+ for query in datapoint.find_queries:
129
+ if query.semantic_target is not None:
130
+ query.semantic_target = F.hflip(query.semantic_target)
131
+ if query.image_id == index and query.input_bbox is not None:
132
+ boxes = query.input_bbox
133
+ boxes = boxes[:, [2, 1, 0, 3]] * torch.as_tensor(
134
+ [-1, 1, -1, 1]
135
+ ) + torch.as_tensor([w, 0, w, 0])
136
+ query.input_bbox = boxes
137
+ if query.image_id == index and query.input_points is not None:
138
+ points = query.input_points
139
+ points = points * torch.as_tensor([-1, 1, 1]) + torch.as_tensor([w, 0, 0])
140
+ query.input_points = points
141
+ return datapoint
142
+
143
+
144
+ def get_size_with_aspect_ratio(image_size, size, max_size=None):
145
+ w, h = image_size
146
+ if max_size is not None:
147
+ min_original_size = float(min((w, h)))
148
+ max_original_size = float(max((w, h)))
149
+ if max_original_size / min_original_size * size > max_size:
150
+ size = max_size * min_original_size / max_original_size
151
+
152
+ if (w <= h and w == size) or (h <= w and h == size):
153
+ return (h, w)
154
+
155
+ if w < h:
156
+ ow = int(round(size))
157
+ oh = int(round(size * h / w))
158
+ else:
159
+ oh = int(round(size))
160
+ ow = int(round(size * w / h))
161
+
162
+ return (oh, ow)
163
+
164
+
165
+ def resize(datapoint, index, size, max_size=None, square=False, v2=False):
166
+ # size can be min_size (scalar) or (w, h) tuple
167
+
168
+ def get_size(image_size, size, max_size=None):
169
+ if isinstance(size, (list, tuple)):
170
+ return size[::-1]
171
+ else:
172
+ return get_size_with_aspect_ratio(image_size, size, max_size)
173
+
174
+ if square:
175
+ size = size, size
176
+ else:
177
+ cur_size = (
178
+ datapoint.images[index].data.size()[-2:][::-1]
179
+ if v2
180
+ else datapoint.images[index].data.size
181
+ )
182
+ size = get_size(cur_size, size, max_size)
183
+
184
+ old_size = (
185
+ datapoint.images[index].data.size()[-2:][::-1]
186
+ if v2
187
+ else datapoint.images[index].data.size
188
+ )
189
+ if v2:
190
+ datapoint.images[index].data = Fv2.resize(
191
+ datapoint.images[index].data, size, antialias=True
192
+ )
193
+ else:
194
+ datapoint.images[index].data = F.resize(datapoint.images[index].data, size)
195
+
196
+ new_size = (
197
+ datapoint.images[index].data.size()[-2:][::-1]
198
+ if v2
199
+ else datapoint.images[index].data.size
200
+ )
201
+ ratios = tuple(float(s) / float(s_orig) for s, s_orig in zip(new_size, old_size))
202
+ ratio_width, ratio_height = ratios
203
+
204
+ for obj in datapoint.images[index].objects:
205
+ boxes = obj.bbox.view(1, 4)
206
+ scaled_boxes = boxes * torch.as_tensor(
207
+ [ratio_width, ratio_height, ratio_width, ratio_height], dtype=torch.float32
208
+ )
209
+ obj.bbox = scaled_boxes
210
+ obj.area *= ratio_width * ratio_height
211
+ if obj.segment is not None:
212
+ obj.segment = F.resize(obj.segment[None, None], size).squeeze()
213
+
214
+ for query in datapoint.find_queries:
215
+ if query.semantic_target is not None:
216
+ query.semantic_target = F.resize(
217
+ query.semantic_target[None, None], size
218
+ ).squeeze()
219
+ if query.image_id == index and query.input_bbox is not None:
220
+ boxes = query.input_bbox
221
+ scaled_boxes = boxes * torch.as_tensor(
222
+ [ratio_width, ratio_height, ratio_width, ratio_height],
223
+ dtype=torch.float32,
224
+ )
225
+ query.input_bbox = scaled_boxes
226
+ if query.image_id == index and query.input_points is not None:
227
+ points = query.input_points
228
+ scaled_points = points * torch.as_tensor(
229
+ [ratio_width, ratio_height, 1],
230
+ dtype=torch.float32,
231
+ )
232
+ query.input_points = scaled_points
233
+
234
+ h, w = size
235
+ datapoint.images[index].size = (h, w)
236
+ return datapoint
237
+
238
+
239
+ def pad(datapoint, index, padding, v2=False):
240
+ old_h, old_w = datapoint.images[index].size
241
+ h, w = old_h, old_w
242
+ if len(padding) == 2:
243
+ # assumes that we only pad on the bottom right corners
244
+ if v2:
245
+ datapoint.images[index].data = Fv2.pad(
246
+ datapoint.images[index].data, (0, 0, padding[0], padding[1])
247
+ )
248
+ else:
249
+ datapoint.images[index].data = F.pad(
250
+ datapoint.images[index].data, (0, 0, padding[0], padding[1])
251
+ )
252
+ h += padding[1]
253
+ w += padding[0]
254
+ else:
255
+ if v2:
256
+ # left, top, right, bottom
257
+ datapoint.images[index].data = Fv2.pad(
258
+ datapoint.images[index].data,
259
+ (padding[0], padding[1], padding[2], padding[3]),
260
+ )
261
+ else:
262
+ # left, top, right, bottom
263
+ datapoint.images[index].data = F.pad(
264
+ datapoint.images[index].data,
265
+ (padding[0], padding[1], padding[2], padding[3]),
266
+ )
267
+ h += padding[1] + padding[3]
268
+ w += padding[0] + padding[2]
269
+
270
+ datapoint.images[index].size = (h, w)
271
+
272
+ for obj in datapoint.images[index].objects:
273
+ if len(padding) != 2:
274
+ obj.bbox += torch.as_tensor(
275
+ [padding[0], padding[1], padding[0], padding[1]], dtype=torch.float32
276
+ )
277
+ if obj.segment is not None:
278
+ if v2:
279
+ if len(padding) == 2:
280
+ obj.segment = Fv2.pad(
281
+ obj.segment[None], (0, 0, padding[0], padding[1])
282
+ ).squeeze(0)
283
+ else:
284
+ obj.segment = Fv2.pad(obj.segment[None], tuple(padding)).squeeze(0)
285
+ else:
286
+ if len(padding) == 2:
287
+ obj.segment = F.pad(obj.segment, (0, 0, padding[0], padding[1]))
288
+ else:
289
+ obj.segment = F.pad(obj.segment, tuple(padding))
290
+
291
+ for query in datapoint.find_queries:
292
+ if query.semantic_target is not None:
293
+ if v2:
294
+ if len(padding) == 2:
295
+ query.semantic_target = Fv2.pad(
296
+ query.semantic_target[None, None],
297
+ (0, 0, padding[0], padding[1]),
298
+ ).squeeze()
299
+ else:
300
+ query.semantic_target = Fv2.pad(
301
+ query.semantic_target[None, None], tuple(padding)
302
+ ).squeeze()
303
+ else:
304
+ if len(padding) == 2:
305
+ query.semantic_target = F.pad(
306
+ query.semantic_target[None, None],
307
+ (0, 0, padding[0], padding[1]),
308
+ ).squeeze()
309
+ else:
310
+ query.semantic_target = F.pad(
311
+ query.semantic_target[None, None], tuple(padding)
312
+ ).squeeze()
313
+ if query.image_id == index and query.input_bbox is not None:
314
+ if len(padding) != 2:
315
+ query.input_bbox += torch.as_tensor(
316
+ [padding[0], padding[1], padding[0], padding[1]],
317
+ dtype=torch.float32,
318
+ )
319
+ if query.image_id == index and query.input_points is not None:
320
+ if len(padding) != 2:
321
+ query.input_points += torch.as_tensor(
322
+ [padding[0], padding[1], 0], dtype=torch.float32
323
+ )
324
+
325
+ return datapoint
326
+
327
+
328
+ class RandomSizeCropAPI:
329
+ def __init__(
330
+ self,
331
+ min_size: int,
332
+ max_size: int,
333
+ respect_boxes: bool,
334
+ consistent_transform: bool,
335
+ respect_input_boxes: bool = True,
336
+ v2: bool = False,
337
+ recompute_box_from_mask: bool = False,
338
+ ):
339
+ self.min_size = min_size
340
+ self.max_size = max_size
341
+ self.respect_boxes = respect_boxes # if True we can't crop a box out
342
+ self.respect_input_boxes = respect_input_boxes
343
+ self.consistent_transform = consistent_transform
344
+ self.v2 = v2
345
+ self.recompute_box_from_mask = recompute_box_from_mask
346
+
347
+ def _sample_no_respect_boxes(self, img):
348
+ w = random.randint(self.min_size, min(img.width, self.max_size))
349
+ h = random.randint(self.min_size, min(img.height, self.max_size))
350
+ return T.RandomCrop.get_params(img, (h, w))
351
+
352
+ def _sample_respect_boxes(self, img, boxes, points, min_box_size=10.0):
353
+ """
354
+ Assure that no box or point is dropped via cropping, though portions
355
+ of boxes may be removed.
356
+ """
357
+ if len(boxes) == 0 and len(points) == 0:
358
+ return self._sample_no_respect_boxes(img)
359
+
360
+ if self.v2:
361
+ img_height, img_width = img.size()[-2:]
362
+ else:
363
+ img_width, img_height = img.size
364
+
365
+ minW, minH, maxW, maxH = (
366
+ min(img_width, self.min_size),
367
+ min(img_height, self.min_size),
368
+ min(img_width, self.max_size),
369
+ min(img_height, self.max_size),
370
+ )
371
+
372
+ # The crop box must extend one pixel beyond points to the bottom/right
373
+ # to assure the exclusive box contains the points.
374
+ minX = (
375
+ torch.cat([boxes[:, 0] + min_box_size, points[:, 0] + 1], dim=0)
376
+ .max()
377
+ .item()
378
+ )
379
+ minY = (
380
+ torch.cat([boxes[:, 1] + min_box_size, points[:, 1] + 1], dim=0)
381
+ .max()
382
+ .item()
383
+ )
384
+ minX = min(img_width, minX)
385
+ minY = min(img_height, minY)
386
+ maxX = torch.cat([boxes[:, 2] - min_box_size, points[:, 0]], dim=0).min().item()
387
+ maxY = torch.cat([boxes[:, 3] - min_box_size, points[:, 1]], dim=0).min().item()
388
+ maxX = max(0.0, maxX)
389
+ maxY = max(0.0, maxY)
390
+ minW = max(minW, minX - maxX)
391
+ minH = max(minH, minY - maxY)
392
+ w = random.uniform(minW, max(minW, maxW))
393
+ h = random.uniform(minH, max(minH, maxH))
394
+ if minX > maxX:
395
+ # i = random.uniform(max(0, minX - w + 1), max(maxX, max(0, minX - w + 1)))
396
+ i = random.uniform(max(0, minX - w), max(maxX, max(0, minX - w)))
397
+ else:
398
+ i = random.uniform(
399
+ max(0, minX - w + 1), max(maxX - 1, max(0, minX - w + 1))
400
+ )
401
+ if minY > maxY:
402
+ # j = random.uniform(max(0, minY - h + 1), max(maxY, max(0, minY - h + 1)))
403
+ j = random.uniform(max(0, minY - h), max(maxY, max(0, minY - h)))
404
+ else:
405
+ j = random.uniform(
406
+ max(0, minY - h + 1), max(maxY - 1, max(0, minY - h + 1))
407
+ )
408
+
409
+ return [j, i, h, w]
410
+
411
+ def __call__(self, datapoint, **kwargs):
412
+ if self.respect_boxes or self.respect_input_boxes:
413
+ if self.consistent_transform:
414
+ # Check that all the images are the same size
415
+ w, h = datapoint.images[0].data.size
416
+ for img in datapoint.images:
417
+ assert img.data.size == (w, h)
418
+
419
+ all_boxes = []
420
+ # Getting all boxes in all the images
421
+ if self.respect_boxes:
422
+ all_boxes += [
423
+ obj.bbox.view(-1, 4)
424
+ for img in datapoint.images
425
+ for obj in img.objects
426
+ ]
427
+ # Get all the boxes in the find queries
428
+ if self.respect_input_boxes:
429
+ all_boxes += [
430
+ q.input_bbox.view(-1, 4)
431
+ for q in datapoint.find_queries
432
+ if q.input_bbox is not None
433
+ ]
434
+ if all_boxes:
435
+ all_boxes = torch.cat(all_boxes, 0)
436
+ else:
437
+ all_boxes = torch.empty(0, 4)
438
+
439
+ all_points = [
440
+ q.input_points.view(-1, 3)[:, :2]
441
+ for q in datapoint.find_queries
442
+ if q.input_points is not None
443
+ ]
444
+ if all_points:
445
+ all_points = torch.cat(all_points, 0)
446
+ else:
447
+ all_points = torch.empty(0, 2)
448
+
449
+ crop_param = self._sample_respect_boxes(
450
+ datapoint.images[0].data, all_boxes, all_points
451
+ )
452
+ for i in range(len(datapoint.images)):
453
+ datapoint = crop(
454
+ datapoint,
455
+ i,
456
+ crop_param,
457
+ v2=self.v2,
458
+ check_validity=self.respect_boxes,
459
+ check_input_validity=self.respect_input_boxes,
460
+ recompute_box_from_mask=self.recompute_box_from_mask,
461
+ )
462
+ return datapoint
463
+ else:
464
+ for i in range(len(datapoint.images)):
465
+ all_boxes = []
466
+ # Get all boxes in the current image
467
+ if self.respect_boxes:
468
+ all_boxes += [
469
+ obj.bbox.view(-1, 4) for obj in datapoint.images[i].objects
470
+ ]
471
+ # Get all the boxes in the find queries that correspond to this image
472
+ if self.respect_input_boxes:
473
+ all_boxes += [
474
+ q.input_bbox.view(-1, 4)
475
+ for q in datapoint.find_queries
476
+ if q.image_id == i and q.input_bbox is not None
477
+ ]
478
+ if all_boxes:
479
+ all_boxes = torch.cat(all_boxes, 0)
480
+ else:
481
+ all_boxes = torch.empty(0, 4)
482
+
483
+ all_points = [
484
+ q.input_points.view(-1, 3)[:, :2]
485
+ for q in datapoint.find_queries
486
+ if q.input_points is not None
487
+ ]
488
+ if all_points:
489
+ all_points = torch.cat(all_points, 0)
490
+ else:
491
+ all_points = torch.empty(0, 2)
492
+
493
+ crop_param = self._sample_respect_boxes(
494
+ datapoint.images[i].data, all_boxes, all_points
495
+ )
496
+ datapoint = crop(
497
+ datapoint,
498
+ i,
499
+ crop_param,
500
+ v2=self.v2,
501
+ check_validity=self.respect_boxes,
502
+ check_input_validity=self.respect_input_boxes,
503
+ recompute_box_from_mask=self.recompute_box_from_mask,
504
+ )
505
+ return datapoint
506
+ else:
507
+ if self.consistent_transform:
508
+ # Check that all the images are the same size
509
+ w, h = datapoint.images[0].data.size
510
+ for img in datapoint.images:
511
+ assert img.data.size == (w, h)
512
+
513
+ crop_param = self._sample_no_respect_boxes(datapoint.images[0].data)
514
+ for i in range(len(datapoint.images)):
515
+ datapoint = crop(
516
+ datapoint,
517
+ i,
518
+ crop_param,
519
+ v2=self.v2,
520
+ check_validity=self.respect_boxes,
521
+ check_input_validity=self.respect_input_boxes,
522
+ recompute_box_from_mask=self.recompute_box_from_mask,
523
+ )
524
+ return datapoint
525
+ else:
526
+ for i in range(len(datapoint.images)):
527
+ crop_param = self._sample_no_respect_boxes(datapoint.images[i].data)
528
+ datapoint = crop(
529
+ datapoint,
530
+ i,
531
+ crop_param,
532
+ v2=self.v2,
533
+ check_validity=self.respect_boxes,
534
+ check_input_validity=self.respect_input_boxes,
535
+ recompute_box_from_mask=self.recompute_box_from_mask,
536
+ )
537
+ return datapoint
538
+
539
+
540
+ class CenterCropAPI:
541
+ def __init__(self, size, consistent_transform, recompute_box_from_mask=False):
542
+ self.size = size
543
+ self.consistent_transform = consistent_transform
544
+ self.recompute_box_from_mask = recompute_box_from_mask
545
+
546
+ def _sample_crop(self, image_width, image_height):
547
+ crop_height, crop_width = self.size
548
+ crop_top = int(round((image_height - crop_height) / 2.0))
549
+ crop_left = int(round((image_width - crop_width) / 2.0))
550
+ return crop_top, crop_left, crop_height, crop_width
551
+
552
+ def __call__(self, datapoint, **kwargs):
553
+ if self.consistent_transform:
554
+ # Check that all the images are the same size
555
+ w, h = datapoint.images[0].data.size
556
+ for img in datapoint.images:
557
+ assert img.size == (w, h)
558
+
559
+ crop_top, crop_left, crop_height, crop_width = self._sample_crop(w, h)
560
+ for i in range(len(datapoint.images)):
561
+ datapoint = crop(
562
+ datapoint,
563
+ i,
564
+ (crop_top, crop_left, crop_height, crop_width),
565
+ recompute_box_from_mask=self.recompute_box_from_mask,
566
+ )
567
+ return datapoint
568
+
569
+ for i in range(len(datapoint.images)):
570
+ w, h = datapoint.images[i].data.size
571
+ crop_top, crop_left, crop_height, crop_width = self._sample_crop(w, h)
572
+ datapoint = crop(
573
+ datapoint,
574
+ i,
575
+ (crop_top, crop_left, crop_height, crop_width),
576
+ recompute_box_from_mask=self.recompute_box_from_mask,
577
+ )
578
+
579
+ return datapoint
580
+
581
+
582
+ class RandomHorizontalFlip:
583
+ def __init__(self, consistent_transform, p=0.5):
584
+ self.p = p
585
+ self.consistent_transform = consistent_transform
586
+
587
+ def __call__(self, datapoint, **kwargs):
588
+ if self.consistent_transform:
589
+ if random.random() < self.p:
590
+ for i in range(len(datapoint.images)):
591
+ datapoint = hflip(datapoint, i)
592
+ return datapoint
593
+ for i in range(len(datapoint.images)):
594
+ if random.random() < self.p:
595
+ datapoint = hflip(datapoint, i)
596
+ return datapoint
597
+
598
+
599
+ class RandomResizeAPI:
600
+ def __init__(
601
+ self, sizes, consistent_transform, max_size=None, square=False, v2=False
602
+ ):
603
+ if isinstance(sizes, int):
604
+ sizes = (sizes,)
605
+ assert isinstance(sizes, Iterable)
606
+ self.sizes = list(sizes)
607
+ self.max_size = max_size
608
+ self.square = square
609
+ self.consistent_transform = consistent_transform
610
+ self.v2 = v2
611
+
612
+ def __call__(self, datapoint, **kwargs):
613
+ if self.consistent_transform:
614
+ size = random.choice(self.sizes)
615
+ for i in range(len(datapoint.images)):
616
+ datapoint = resize(
617
+ datapoint, i, size, self.max_size, square=self.square, v2=self.v2
618
+ )
619
+ return datapoint
620
+ for i in range(len(datapoint.images)):
621
+ size = random.choice(self.sizes)
622
+ datapoint = resize(
623
+ datapoint, i, size, self.max_size, square=self.square, v2=self.v2
624
+ )
625
+ return datapoint
626
+
627
+
628
+ class ScheduledRandomResizeAPI(RandomResizeAPI):
629
+ def __init__(self, size_scheduler, consistent_transform, square=False):
630
+ self.size_scheduler = size_scheduler
631
+ # Just a meaningful init value for super
632
+ params = self.size_scheduler(epoch_num=0)
633
+ sizes, max_size = params["sizes"], params["max_size"]
634
+ super().__init__(sizes, consistent_transform, max_size=max_size, square=square)
635
+
636
+ def __call__(self, datapoint, **kwargs):
637
+ assert "epoch" in kwargs, "Param scheduler needs to know the current epoch"
638
+ params = self.size_scheduler(kwargs["epoch"])
639
+ sizes, max_size = params["sizes"], params["max_size"]
640
+ self.sizes = sizes
641
+ self.max_size = max_size
642
+ datapoint = super(ScheduledRandomResizeAPI, self).__call__(datapoint, **kwargs)
643
+ return datapoint
644
+
645
+
646
+ class RandomPadAPI:
647
+ def __init__(self, max_pad, consistent_transform):
648
+ self.max_pad = max_pad
649
+ self.consistent_transform = consistent_transform
650
+
651
+ def _sample_pad(self):
652
+ pad_x = random.randint(0, self.max_pad)
653
+ pad_y = random.randint(0, self.max_pad)
654
+ return pad_x, pad_y
655
+
656
+ def __call__(self, datapoint, **kwargs):
657
+ if self.consistent_transform:
658
+ pad_x, pad_y = self._sample_pad()
659
+ for i in range(len(datapoint.images)):
660
+ datapoint = pad(datapoint, i, (pad_x, pad_y))
661
+ return datapoint
662
+
663
+ for i in range(len(datapoint.images)):
664
+ pad_x, pad_y = self._sample_pad()
665
+ datapoint = pad(datapoint, i, (pad_x, pad_y))
666
+ return datapoint
667
+
668
+
669
+ class PadToSizeAPI:
670
+ def __init__(self, size, consistent_transform, bottom_right=False, v2=False):
671
+ self.size = size
672
+ self.consistent_transform = consistent_transform
673
+ self.v2 = v2
674
+ self.bottom_right = bottom_right
675
+
676
+ def _sample_pad(self, w, h):
677
+ pad_x = self.size - w
678
+ pad_y = self.size - h
679
+ assert pad_x >= 0 and pad_y >= 0
680
+ pad_left = random.randint(0, pad_x)
681
+ pad_right = pad_x - pad_left
682
+ pad_top = random.randint(0, pad_y)
683
+ pad_bottom = pad_y - pad_top
684
+ return pad_left, pad_top, pad_right, pad_bottom
685
+
686
+ def __call__(self, datapoint, **kwargs):
687
+ if self.consistent_transform:
688
+ # Check that all the images are the same size
689
+ w, h = datapoint.images[0].data.size
690
+ for img in datapoint.images:
691
+ assert img.size == (w, h)
692
+ if self.bottom_right:
693
+ pad_right = self.size - w
694
+ pad_bottom = self.size - h
695
+ padding = (pad_right, pad_bottom)
696
+ else:
697
+ padding = self._sample_pad(w, h)
698
+ for i in range(len(datapoint.images)):
699
+ datapoint = pad(datapoint, i, padding, v2=self.v2)
700
+ return datapoint
701
+
702
+ for i, img in enumerate(datapoint.images):
703
+ w, h = img.data.size
704
+ if self.bottom_right:
705
+ pad_right = self.size - w
706
+ pad_bottom = self.size - h
707
+ padding = (pad_right, pad_bottom)
708
+ else:
709
+ padding = self._sample_pad(w, h)
710
+ datapoint = pad(datapoint, i, padding, v2=self.v2)
711
+ return datapoint
712
+
713
+
714
+ class RandomMosaicVideoAPI:
715
+ def __init__(self, prob=0.15, grid_h=2, grid_w=2, use_random_hflip=False):
716
+ self.prob = prob
717
+ self.grid_h = grid_h
718
+ self.grid_w = grid_w
719
+ self.use_random_hflip = use_random_hflip
720
+
721
+ def __call__(self, datapoint, **kwargs):
722
+ if random.random() > self.prob:
723
+ return datapoint
724
+
725
+ # select a random location to place the target mask in the mosaic
726
+ target_grid_y = random.randint(0, self.grid_h - 1)
727
+ target_grid_x = random.randint(0, self.grid_w - 1)
728
+ # whether to flip each grid in the mosaic horizontally
729
+ if self.use_random_hflip:
730
+ should_hflip = torch.rand(self.grid_h, self.grid_w) < 0.5
731
+ else:
732
+ should_hflip = torch.zeros(self.grid_h, self.grid_w, dtype=torch.bool)
733
+ for i in range(len(datapoint.images)):
734
+ datapoint = random_mosaic_frame(
735
+ datapoint,
736
+ i,
737
+ grid_h=self.grid_h,
738
+ grid_w=self.grid_w,
739
+ target_grid_y=target_grid_y,
740
+ target_grid_x=target_grid_x,
741
+ should_hflip=should_hflip,
742
+ )
743
+
744
+ return datapoint
745
+
746
+
747
+ def random_mosaic_frame(
748
+ datapoint,
749
+ index,
750
+ grid_h,
751
+ grid_w,
752
+ target_grid_y,
753
+ target_grid_x,
754
+ should_hflip,
755
+ ):
756
+ # Step 1: downsize the images and paste them into a mosaic
757
+ image_data = datapoint.images[index].data
758
+ is_pil = isinstance(image_data, PILImage.Image)
759
+ if is_pil:
760
+ H_im = image_data.height
761
+ W_im = image_data.width
762
+ image_data_output = PILImage.new("RGB", (W_im, H_im))
763
+ else:
764
+ H_im = image_data.size(-2)
765
+ W_im = image_data.size(-1)
766
+ image_data_output = torch.zeros_like(image_data)
767
+
768
+ downsize_cache = {}
769
+ for grid_y in range(grid_h):
770
+ for grid_x in range(grid_w):
771
+ y_offset_b = grid_y * H_im // grid_h
772
+ x_offset_b = grid_x * W_im // grid_w
773
+ y_offset_e = (grid_y + 1) * H_im // grid_h
774
+ x_offset_e = (grid_x + 1) * W_im // grid_w
775
+ H_im_downsize = y_offset_e - y_offset_b
776
+ W_im_downsize = x_offset_e - x_offset_b
777
+
778
+ if (H_im_downsize, W_im_downsize) in downsize_cache:
779
+ image_data_downsize = downsize_cache[(H_im_downsize, W_im_downsize)]
780
+ else:
781
+ image_data_downsize = F.resize(
782
+ image_data,
783
+ size=(H_im_downsize, W_im_downsize),
784
+ interpolation=InterpolationMode.BILINEAR,
785
+ antialias=True, # antialiasing for downsizing
786
+ )
787
+ downsize_cache[(H_im_downsize, W_im_downsize)] = image_data_downsize
788
+ if should_hflip[grid_y, grid_x].item():
789
+ image_data_downsize = F.hflip(image_data_downsize)
790
+
791
+ if is_pil:
792
+ image_data_output.paste(image_data_downsize, (x_offset_b, y_offset_b))
793
+ else:
794
+ image_data_output[:, y_offset_b:y_offset_e, x_offset_b:x_offset_e] = (
795
+ image_data_downsize
796
+ )
797
+
798
+ datapoint.images[index].data = image_data_output
799
+
800
+ # Step 2: downsize the masks and paste them into the target grid of the mosaic
801
+ # (note that we don't scale input/target boxes since they are not used in TA)
802
+ for obj in datapoint.images[index].objects:
803
+ if obj.segment is None:
804
+ continue
805
+ assert obj.segment.shape == (H_im, W_im) and obj.segment.dtype == torch.uint8
806
+ segment_output = torch.zeros_like(obj.segment)
807
+
808
+ target_y_offset_b = target_grid_y * H_im // grid_h
809
+ target_x_offset_b = target_grid_x * W_im // grid_w
810
+ target_y_offset_e = (target_grid_y + 1) * H_im // grid_h
811
+ target_x_offset_e = (target_grid_x + 1) * W_im // grid_w
812
+ target_H_im_downsize = target_y_offset_e - target_y_offset_b
813
+ target_W_im_downsize = target_x_offset_e - target_x_offset_b
814
+
815
+ segment_downsize = F.resize(
816
+ obj.segment[None, None],
817
+ size=(target_H_im_downsize, target_W_im_downsize),
818
+ interpolation=InterpolationMode.BILINEAR,
819
+ antialias=True, # antialiasing for downsizing
820
+ )[0, 0]
821
+ if should_hflip[target_grid_y, target_grid_x].item():
822
+ segment_downsize = F.hflip(segment_downsize[None, None])[0, 0]
823
+
824
+ segment_output[
825
+ target_y_offset_b:target_y_offset_e, target_x_offset_b:target_x_offset_e
826
+ ] = segment_downsize
827
+ obj.segment = segment_output
828
+
829
+ return datapoint
830
+
831
+
832
+ class ScheduledPadToSizeAPI(PadToSizeAPI):
833
+ def __init__(self, size_scheduler, consistent_transform):
834
+ self.size_scheduler = size_scheduler
835
+ size = self.size_scheduler(epoch_num=0)["sizes"]
836
+ super().__init__(size, consistent_transform)
837
+
838
+ def __call__(self, datapoint, **kwargs):
839
+ assert "epoch" in kwargs, "Param scheduler needs to know the current epoch"
840
+ params = self.size_scheduler(kwargs["epoch"])
841
+ self.size = params["resolution"]
842
+ return super(ScheduledPadToSizeAPI, self).__call__(datapoint, **kwargs)
843
+
844
+
845
+ class IdentityAPI:
846
+ def __call__(self, datapoint, **kwargs):
847
+ return datapoint
848
+
849
+
850
+ class RandomSelectAPI:
851
+ """
852
+ Randomly selects between transforms1 and transforms2,
853
+ with probability p for transforms1 and (1 - p) for transforms2
854
+ """
855
+
856
+ def __init__(self, transforms1=None, transforms2=None, p=0.5):
857
+ self.transforms1 = transforms1 or IdentityAPI()
858
+ self.transforms2 = transforms2 or IdentityAPI()
859
+ self.p = p
860
+
861
+ def __call__(self, datapoint, **kwargs):
862
+ if random.random() < self.p:
863
+ return self.transforms1(datapoint, **kwargs)
864
+ return self.transforms2(datapoint, **kwargs)
865
+
866
+
867
+ class ToTensorAPI:
868
+ def __init__(self, v2=False):
869
+ self.v2 = v2
870
+
871
+ def __call__(self, datapoint: Datapoint, **kwargs):
872
+ for img in datapoint.images:
873
+ if self.v2:
874
+ img.data = Fv2.to_image_tensor(img.data)
875
+ # img.data = Fv2.to_dtype(img.data, torch.uint8, scale=True)
876
+ # img.data = Fv2.convert_image_dtype(img.data, torch.uint8)
877
+ else:
878
+ img.data = F.to_tensor(img.data)
879
+ return datapoint
880
+
881
+
882
+ class NormalizeAPI:
883
+ def __init__(self, mean, std, v2=False):
884
+ self.mean = mean
885
+ self.std = std
886
+ self.v2 = v2
887
+
888
+ def __call__(self, datapoint: Datapoint, **kwargs):
889
+ for img in datapoint.images:
890
+ if self.v2:
891
+ img.data = Fv2.convert_image_dtype(img.data, torch.float32)
892
+ img.data = Fv2.normalize(img.data, mean=self.mean, std=self.std)
893
+ else:
894
+ img.data = F.normalize(img.data, mean=self.mean, std=self.std)
895
+ for obj in img.objects:
896
+ boxes = obj.bbox
897
+ cur_h, cur_w = img.data.shape[-2:]
898
+ boxes = box_xyxy_to_cxcywh(boxes)
899
+ boxes = boxes / torch.tensor(
900
+ [cur_w, cur_h, cur_w, cur_h], dtype=torch.float32
901
+ )
902
+ obj.bbox = boxes
903
+
904
+ for query in datapoint.find_queries:
905
+ if query.input_bbox is not None:
906
+ boxes = query.input_bbox
907
+ cur_h, cur_w = datapoint.images[query.image_id].data.shape[-2:]
908
+ boxes = box_xyxy_to_cxcywh(boxes)
909
+ boxes = boxes / torch.tensor(
910
+ [cur_w, cur_h, cur_w, cur_h], dtype=torch.float32
911
+ )
912
+ query.input_bbox = boxes
913
+ if query.input_points is not None:
914
+ points = query.input_points
915
+ cur_h, cur_w = datapoint.images[query.image_id].data.shape[-2:]
916
+ points = points / torch.tensor([cur_w, cur_h, 1.0], dtype=torch.float32)
917
+ query.input_points = points
918
+
919
+ return datapoint
920
+
921
+
922
+ class ComposeAPI:
923
+ def __init__(self, transforms):
924
+ self.transforms = transforms
925
+
926
+ def __call__(self, datapoint, **kwargs):
927
+ for t in self.transforms:
928
+ datapoint = t(datapoint, **kwargs)
929
+ return datapoint
930
+
931
+ def __repr__(self):
932
+ format_string = self.__class__.__name__ + "("
933
+ for t in self.transforms:
934
+ format_string += "\n"
935
+ format_string += " {0}".format(t)
936
+ format_string += "\n)"
937
+ return format_string
938
+
939
+
940
+ class RandomGrayscale:
941
+ def __init__(self, consistent_transform, p=0.5):
942
+ self.p = p
943
+ self.consistent_transform = consistent_transform
944
+ self.Grayscale = T.Grayscale(num_output_channels=3)
945
+
946
+ def __call__(self, datapoint: Datapoint, **kwargs):
947
+ if self.consistent_transform:
948
+ if random.random() < self.p:
949
+ for img in datapoint.images:
950
+ img.data = self.Grayscale(img.data)
951
+ return datapoint
952
+ for img in datapoint.images:
953
+ if random.random() < self.p:
954
+ img.data = self.Grayscale(img.data)
955
+ return datapoint
956
+
957
+
958
+ class ColorJitter:
959
+ def __init__(self, consistent_transform, brightness, contrast, saturation, hue):
960
+ self.consistent_transform = consistent_transform
961
+ self.brightness = (
962
+ brightness
963
+ if isinstance(brightness, list)
964
+ else [max(0, 1 - brightness), 1 + brightness]
965
+ )
966
+ self.contrast = (
967
+ contrast
968
+ if isinstance(contrast, list)
969
+ else [max(0, 1 - contrast), 1 + contrast]
970
+ )
971
+ self.saturation = (
972
+ saturation
973
+ if isinstance(saturation, list)
974
+ else [max(0, 1 - saturation), 1 + saturation]
975
+ )
976
+ self.hue = hue if isinstance(hue, list) or hue is None else ([-hue, hue])
977
+
978
+ def __call__(self, datapoint: Datapoint, **kwargs):
979
+ if self.consistent_transform:
980
+ # Create a color jitter transformation params
981
+ (
982
+ fn_idx,
983
+ brightness_factor,
984
+ contrast_factor,
985
+ saturation_factor,
986
+ hue_factor,
987
+ ) = T.ColorJitter.get_params(
988
+ self.brightness, self.contrast, self.saturation, self.hue
989
+ )
990
+ for img in datapoint.images:
991
+ if not self.consistent_transform:
992
+ (
993
+ fn_idx,
994
+ brightness_factor,
995
+ contrast_factor,
996
+ saturation_factor,
997
+ hue_factor,
998
+ ) = T.ColorJitter.get_params(
999
+ self.brightness, self.contrast, self.saturation, self.hue
1000
+ )
1001
+ for fn_id in fn_idx:
1002
+ if fn_id == 0 and brightness_factor is not None:
1003
+ img.data = F.adjust_brightness(img.data, brightness_factor)
1004
+ elif fn_id == 1 and contrast_factor is not None:
1005
+ img.data = F.adjust_contrast(img.data, contrast_factor)
1006
+ elif fn_id == 2 and saturation_factor is not None:
1007
+ img.data = F.adjust_saturation(img.data, saturation_factor)
1008
+ elif fn_id == 3 and hue_factor is not None:
1009
+ img.data = F.adjust_hue(img.data, hue_factor)
1010
+ return datapoint
1011
+
1012
+
1013
+ class RandomAffine:
1014
+ def __init__(
1015
+ self,
1016
+ degrees,
1017
+ consistent_transform,
1018
+ scale=None,
1019
+ translate=None,
1020
+ shear=None,
1021
+ image_mean=(123, 116, 103),
1022
+ log_warning=True,
1023
+ num_tentatives=1,
1024
+ image_interpolation="bicubic",
1025
+ ):
1026
+ """
1027
+ The mask is required for this transform.
1028
+ if consistent_transform if True, then the same random affine is applied to all frames and masks.
1029
+ """
1030
+ self.degrees = degrees if isinstance(degrees, list) else ([-degrees, degrees])
1031
+ self.scale = scale
1032
+ self.shear = (
1033
+ shear if isinstance(shear, list) else ([-shear, shear] if shear else None)
1034
+ )
1035
+ self.translate = translate
1036
+ self.fill_img = image_mean
1037
+ self.consistent_transform = consistent_transform
1038
+ self.log_warning = log_warning
1039
+ self.num_tentatives = num_tentatives
1040
+
1041
+ if image_interpolation == "bicubic":
1042
+ self.image_interpolation = InterpolationMode.BICUBIC
1043
+ elif image_interpolation == "bilinear":
1044
+ self.image_interpolation = InterpolationMode.BILINEAR
1045
+ else:
1046
+ raise NotImplementedError
1047
+
1048
+ def __call__(self, datapoint: Datapoint, **kwargs):
1049
+ for _tentative in range(self.num_tentatives):
1050
+ res = self.transform_datapoint(datapoint)
1051
+ if res is not None:
1052
+ return res
1053
+
1054
+ if self.log_warning:
1055
+ logging.warning(
1056
+ f"Skip RandomAffine for zero-area mask in first frame after {self.num_tentatives} tentatives"
1057
+ )
1058
+ return datapoint
1059
+
1060
+ def transform_datapoint(self, datapoint: Datapoint):
1061
+ _, height, width = F.get_dimensions(datapoint.images[0].data)
1062
+ img_size = [width, height]
1063
+
1064
+ if self.consistent_transform:
1065
+ # Create a random affine transformation
1066
+ affine_params = T.RandomAffine.get_params(
1067
+ degrees=self.degrees,
1068
+ translate=self.translate,
1069
+ scale_ranges=self.scale,
1070
+ shears=self.shear,
1071
+ img_size=img_size,
1072
+ )
1073
+
1074
+ for img_idx, img in enumerate(datapoint.images):
1075
+ this_masks = [
1076
+ obj.segment.unsqueeze(0) if obj.segment is not None else None
1077
+ for obj in img.objects
1078
+ ]
1079
+ if not self.consistent_transform:
1080
+ # if not consistent we create a new affine params for every frame&mask pair Create a random affine transformation
1081
+ affine_params = T.RandomAffine.get_params(
1082
+ degrees=self.degrees,
1083
+ translate=self.translate,
1084
+ scale_ranges=self.scale,
1085
+ shears=self.shear,
1086
+ img_size=img_size,
1087
+ )
1088
+
1089
+ transformed_bboxes, transformed_masks = [], []
1090
+ for i in range(len(img.objects)):
1091
+ if this_masks[i] is None:
1092
+ transformed_masks.append(None)
1093
+ # Dummy bbox for a dummy target
1094
+ transformed_bboxes.append(torch.tensor([[0, 0, 0, 0]]))
1095
+ else:
1096
+ transformed_mask = F.affine(
1097
+ this_masks[i],
1098
+ *affine_params,
1099
+ interpolation=InterpolationMode.NEAREST,
1100
+ fill=0.0,
1101
+ )
1102
+ if img_idx == 0 and transformed_mask.max() == 0:
1103
+ # We are dealing with a video and the object is not visible in the first frame
1104
+ # Return the datapoint without transformation
1105
+ return None
1106
+ transformed_bbox = masks_to_boxes(transformed_mask)
1107
+ transformed_bboxes.append(transformed_bbox)
1108
+ transformed_masks.append(transformed_mask.squeeze())
1109
+
1110
+ for i in range(len(img.objects)):
1111
+ img.objects[i].bbox = transformed_bboxes[i]
1112
+ img.objects[i].segment = transformed_masks[i]
1113
+
1114
+ img.data = F.affine(
1115
+ img.data,
1116
+ *affine_params,
1117
+ interpolation=self.image_interpolation,
1118
+ fill=self.fill_img,
1119
+ )
1120
+ return datapoint
1121
+
1122
+
1123
+ class RandomResizedCrop:
1124
+ def __init__(
1125
+ self,
1126
+ consistent_transform,
1127
+ size,
1128
+ scale=None,
1129
+ ratio=None,
1130
+ log_warning=True,
1131
+ num_tentatives=4,
1132
+ keep_aspect_ratio=False,
1133
+ ):
1134
+ """
1135
+ The mask is required for this transform.
1136
+ if consistent_transform if True, then the same random resized crop is applied to all frames and masks.
1137
+ """
1138
+ if isinstance(size, numbers.Number):
1139
+ self.size = (int(size), int(size))
1140
+ elif isinstance(size, Sequence) and len(size) == 1:
1141
+ self.size = (size[0], size[0])
1142
+ elif len(size) != 2:
1143
+ raise ValueError("Please provide only two dimensions (h, w) for size.")
1144
+ else:
1145
+ self.size = size
1146
+
1147
+ self.scale = scale if scale is not None else (0.08, 1.0)
1148
+ self.ratio = ratio if ratio is not None else (3.0 / 4.0, 4.0 / 3.0)
1149
+ self.consistent_transform = consistent_transform
1150
+ self.log_warning = log_warning
1151
+ self.num_tentatives = num_tentatives
1152
+ self.keep_aspect_ratio = keep_aspect_ratio
1153
+
1154
+ def __call__(self, datapoint: Datapoint, **kwargs):
1155
+ for _tentative in range(self.num_tentatives):
1156
+ res = self.transform_datapoint(datapoint)
1157
+ if res is not None:
1158
+ return res
1159
+
1160
+ if self.log_warning:
1161
+ logging.warning(
1162
+ f"Skip RandomResizeCrop for zero-area mask in first frame after {self.num_tentatives} tentatives"
1163
+ )
1164
+ return datapoint
1165
+
1166
+ def transform_datapoint(self, datapoint: Datapoint):
1167
+ if self.keep_aspect_ratio:
1168
+ original_size = datapoint.images[0].size
1169
+ original_ratio = original_size[1] / original_size[0]
1170
+ ratio = [r * original_ratio for r in self.ratio]
1171
+ else:
1172
+ ratio = self.ratio
1173
+
1174
+ if self.consistent_transform:
1175
+ # Create a random crop transformation
1176
+ crop_params = T.RandomResizedCrop.get_params(
1177
+ img=datapoint.images[0].data,
1178
+ scale=self.scale,
1179
+ ratio=ratio,
1180
+ )
1181
+
1182
+ for img_idx, img in enumerate(datapoint.images):
1183
+ if not self.consistent_transform:
1184
+ # Create a random crop transformation
1185
+ crop_params = T.RandomResizedCrop.get_params(
1186
+ img=img.data,
1187
+ scale=self.scale,
1188
+ ratio=ratio,
1189
+ )
1190
+
1191
+ this_masks = [
1192
+ obj.segment.unsqueeze(0) if obj.segment is not None else None
1193
+ for obj in img.objects
1194
+ ]
1195
+
1196
+ transformed_bboxes, transformed_masks = [], []
1197
+ for i in range(len(img.objects)):
1198
+ if this_masks[i] is None:
1199
+ transformed_masks.append(None)
1200
+ # Dummy bbox for a dummy target
1201
+ transformed_bboxes.append(torch.tensor([[0, 0, 0, 0]]))
1202
+ else:
1203
+ transformed_mask = F.resized_crop(
1204
+ this_masks[i],
1205
+ *crop_params,
1206
+ size=self.size,
1207
+ interpolation=InterpolationMode.NEAREST,
1208
+ )
1209
+ if img_idx == 0 and transformed_mask.max() == 0:
1210
+ # We are dealing with a video and the object is not visible in the first frame
1211
+ # Return the datapoint without transformation
1212
+ return None
1213
+ transformed_masks.append(transformed_mask.squeeze())
1214
+ transformed_bbox = masks_to_boxes(transformed_mask)
1215
+ transformed_bboxes.append(transformed_bbox)
1216
+
1217
+ # Set the new boxes and masks if all transformed masks and boxes are good.
1218
+ for i in range(len(img.objects)):
1219
+ img.objects[i].bbox = transformed_bboxes[i]
1220
+ img.objects[i].segment = transformed_masks[i]
1221
+
1222
+ img.data = F.resized_crop(
1223
+ img.data,
1224
+ *crop_params,
1225
+ size=self.size,
1226
+ interpolation=InterpolationMode.BILINEAR,
1227
+ )
1228
+ return datapoint
1229
+
1230
+
1231
+ class ResizeToMaxIfAbove:
1232
+ # Resize datapoint image if one of its sides is larger that max_size
1233
+ def __init__(
1234
+ self,
1235
+ max_size=None,
1236
+ ):
1237
+ self.max_size = max_size
1238
+
1239
+ def __call__(self, datapoint: Datapoint, **kwargs):
1240
+ _, height, width = F.get_dimensions(datapoint.images[0].data)
1241
+
1242
+ if height <= self.max_size and width <= self.max_size:
1243
+ # The original frames are small enough
1244
+ return datapoint
1245
+ elif height >= width:
1246
+ new_height = self.max_size
1247
+ new_width = int(round(self.max_size * width / height))
1248
+ else:
1249
+ new_height = int(round(self.max_size * height / width))
1250
+ new_width = self.max_size
1251
+
1252
+ size = new_height, new_width
1253
+
1254
+ for index in range(len(datapoint.images)):
1255
+ datapoint.images[index].data = F.resize(datapoint.images[index].data, size)
1256
+
1257
+ for obj in datapoint.images[index].objects:
1258
+ obj.segment = F.resize(
1259
+ obj.segment[None, None],
1260
+ size,
1261
+ interpolation=InterpolationMode.NEAREST,
1262
+ ).squeeze()
1263
+
1264
+ h, w = size
1265
+ datapoint.images[index].size = (h, w)
1266
+ return datapoint
1267
+
1268
+
1269
+ def get_bbox_xyxy_abs_coords_from_mask(mask):
1270
+ """Get the bounding box (XYXY format w/ absolute coordinates) of a binary mask."""
1271
+ assert mask.dim() == 2
1272
+ rows = torch.any(mask, dim=1)
1273
+ cols = torch.any(mask, dim=0)
1274
+ row_inds = rows.nonzero().view(-1)
1275
+ col_inds = cols.nonzero().view(-1)
1276
+ if row_inds.numel() == 0:
1277
+ # mask is empty
1278
+ bbox = torch.zeros(1, 4, dtype=torch.float32)
1279
+ bbox_area = 0.0
1280
+ else:
1281
+ ymin, ymax = row_inds.min(), row_inds.max()
1282
+ xmin, xmax = col_inds.min(), col_inds.max()
1283
+ bbox = torch.tensor([xmin, ymin, xmax, ymax], dtype=torch.float32).view(1, 4)
1284
+ bbox_area = float((ymax - ymin) * (xmax - xmin))
1285
+ return bbox, bbox_area
1286
+
1287
+
1288
+ class MotionBlur:
1289
+ def __init__(self, kernel_size=5, consistent_transform=True, p=0.5):
1290
+ assert kernel_size % 2 == 1, "Kernel size must be odd."
1291
+ self.kernel_size = kernel_size
1292
+ self.consistent_transform = consistent_transform
1293
+ self.p = p
1294
+
1295
+ def __call__(self, datapoint: Datapoint, **kwargs):
1296
+ if random.random() >= self.p:
1297
+ return datapoint
1298
+ if self.consistent_transform:
1299
+ # Generate a single motion blur kernel for all images
1300
+ kernel = self._generate_motion_blur_kernel()
1301
+ for img in datapoint.images:
1302
+ if not self.consistent_transform:
1303
+ # Generate a new motion blur kernel for each image
1304
+ kernel = self._generate_motion_blur_kernel()
1305
+ img.data = self._apply_motion_blur(img.data, kernel)
1306
+
1307
+ return datapoint
1308
+
1309
+ def _generate_motion_blur_kernel(self):
1310
+ kernel = torch.zeros((self.kernel_size, self.kernel_size))
1311
+ direction = random.choice(["horizontal", "vertical", "diagonal"])
1312
+ if direction == "horizontal":
1313
+ kernel[self.kernel_size // 2, :] = 1.0
1314
+ elif direction == "vertical":
1315
+ kernel[:, self.kernel_size // 2] = 1.0
1316
+ elif direction == "diagonal":
1317
+ for i in range(self.kernel_size):
1318
+ kernel[i, i] = 1.0
1319
+ kernel /= kernel.sum()
1320
+ return kernel
1321
+
1322
+ def _apply_motion_blur(self, image, kernel):
1323
+ if isinstance(image, PILImage.Image):
1324
+ image = F.to_tensor(image)
1325
+ channels = image.shape[0]
1326
+ kernel = kernel.to(image.device).unsqueeze(0).unsqueeze(0)
1327
+ blurred_image = torch.nn.functional.conv2d(
1328
+ image.unsqueeze(0),
1329
+ kernel.repeat(channels, 1, 1, 1),
1330
+ padding=self.kernel_size // 2,
1331
+ groups=channels,
1332
+ )
1333
+ return F.to_pil_image(blurred_image.squeeze(0))
1334
+
1335
+
1336
+ class LargeScaleJitter:
1337
+ def __init__(
1338
+ self,
1339
+ scale_range=(0.1, 2.0),
1340
+ aspect_ratio_range=(0.75, 1.33),
1341
+ crop_size=(640, 640),
1342
+ consistent_transform=True,
1343
+ p=0.5,
1344
+ ):
1345
+ """
1346
+ Args:rack
1347
+ scale_range (tuple): Range of scaling factors (min_scale, max_scale).
1348
+ aspect_ratio_range (tuple): Range of aspect ratios (min_aspect_ratio, max_aspect_ratio).
1349
+ crop_size (tuple): Target size of the cropped region (width, height).
1350
+ consistent_transform (bool): Whether to apply the same transformation across all frames.
1351
+ p (float): Probability of applying the transformation.
1352
+ """
1353
+ self.scale_range = scale_range
1354
+ self.aspect_ratio_range = aspect_ratio_range
1355
+ self.crop_size = crop_size
1356
+ self.consistent_transform = consistent_transform
1357
+ self.p = p
1358
+
1359
+ def __call__(self, datapoint: Datapoint, **kwargs):
1360
+ if random.random() >= self.p:
1361
+ return datapoint
1362
+
1363
+ # Sample a single scale factor and aspect ratio for all frames
1364
+ log_ratio = torch.log(torch.tensor(self.aspect_ratio_range))
1365
+ scale_factor = torch.empty(1).uniform_(*self.scale_range).item()
1366
+ aspect_ratio = torch.exp(
1367
+ torch.empty(1).uniform_(log_ratio[0], log_ratio[1])
1368
+ ).item()
1369
+
1370
+ for idx, img in enumerate(datapoint.images):
1371
+ if not self.consistent_transform:
1372
+ # Sample a new scale factor and aspect ratio for each frame
1373
+ log_ratio = torch.log(torch.tensor(self.aspect_ratio_range))
1374
+ scale_factor = torch.empty(1).uniform_(*self.scale_range).item()
1375
+ aspect_ratio = torch.exp(
1376
+ torch.empty(1).uniform_(log_ratio[0], log_ratio[1])
1377
+ ).item()
1378
+
1379
+ # Compute the dimensions of the jittered crop
1380
+ original_width, original_height = img.data.size
1381
+ target_area = original_width * original_height * scale_factor
1382
+ crop_width = int(round((target_area * aspect_ratio) ** 0.5))
1383
+ crop_height = int(round((target_area / aspect_ratio) ** 0.5))
1384
+
1385
+ # Randomly select the top-left corner of the crop
1386
+ crop_x = random.randint(0, max(0, original_width - crop_width))
1387
+ crop_y = random.randint(0, max(0, original_height - crop_height))
1388
+
1389
+ # Extract the cropped region
1390
+ datapoint = crop(datapoint, idx, (crop_x, crop_y, crop_width, crop_height))
1391
+
1392
+ # Resize the cropped region to the target crop size
1393
+ datapoint = resize(datapoint, idx, self.crop_size)
1394
+
1395
+ return datapoint
OVOW/third_party/sam3/sam3/train/transforms/filter_query_transforms.py ADDED
@@ -0,0 +1,607 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ # Copyright (c) Meta Platforms, Inc. and affiliates. All Rights Reserved
2
+
3
+ # pyre-unsafe
4
+
5
+ import logging
6
+ import random
7
+ from collections import defaultdict
8
+ from typing import List, Optional, Union
9
+
10
+ import torch
11
+ from sam3.train.data.sam3_image_dataset import Datapoint, FindQuery, Object
12
+
13
+
14
+ class FilterDataPointQueries:
15
+ find_ids_to_filter: set = None
16
+ get_ids_to_filter: set = None
17
+ obj_ids_to_filter: set = None # stored as pairs (img_id, obj_id)
18
+
19
+ def identify_queries_to_filter(self, datapoint: Datapoint) -> None:
20
+ """
21
+ Compute set of query ids to keep, for both find and get queries
22
+ """
23
+ raise NotImplementedError
24
+
25
+ def _do_filter_query(self, query: Union[FindQuery], query_id: int):
26
+ assert self.find_ids_to_filter is not None
27
+
28
+ return query_id in self.find_ids_to_filter
29
+
30
+
31
+ class FilterQueryWithText(FilterDataPointQueries):
32
+ """
33
+ Filter all datapoints which have query text in a specified list of exluded terms
34
+ """
35
+
36
+ def __init__(
37
+ self, exclude_find_keys: List[str] = None, exclude_get_keys: List[str] = None
38
+ ):
39
+ self.find_filter_keys = exclude_find_keys if exclude_find_keys else []
40
+ self.get_filter_keys = exclude_get_keys if exclude_get_keys else []
41
+
42
+ def identify_queries_to_filter(self, datapoint):
43
+ self.obj_ids_to_filter = set()
44
+ del_find_ids = []
45
+ del_get_ids = []
46
+ for i, f_q in enumerate(datapoint.find_queries):
47
+ if f_q.query_text in self.find_filter_keys:
48
+ del_find_ids.append(i)
49
+
50
+ self.find_ids_to_filter = set(del_find_ids)
51
+
52
+
53
+ class KeepMaxNumFindQueries(FilterDataPointQueries):
54
+ def __init__(
55
+ self, max_num_find_queries: int, retain_positive_queries: bool = False
56
+ ):
57
+ self.max_num_find_queries = max_num_find_queries
58
+ self.retain_positive_queries = retain_positive_queries
59
+
60
+ def identify_queries_to_filter(self, datapoint: Datapoint) -> None:
61
+ self.obj_ids_to_filter = set()
62
+ num_find_queries = len(datapoint.find_queries)
63
+ if num_find_queries <= self.max_num_find_queries:
64
+ self.find_ids_to_filter = set() # keep all find queries
65
+ return
66
+
67
+ if not self.retain_positive_queries:
68
+ all_find_query_ids = list(range(num_find_queries))
69
+ num_queries_to_filter = max(0, num_find_queries - self.max_num_find_queries)
70
+ query_ids_to_filter = random.sample(
71
+ all_find_query_ids, k=num_queries_to_filter
72
+ )
73
+ else:
74
+ # keep up to max_num_find_queries postive find queries and fill
75
+ # the remaining slots (if any) with negative find queries
76
+ pos_find_ids, neg_find_ids = [], []
77
+ for i, f_q in enumerate(datapoint.find_queries):
78
+ # Negative finds return an empty list of object_ids_output
79
+ if len(f_q.object_ids_output) == 0:
80
+ neg_find_ids.append(i)
81
+ else:
82
+ pos_find_ids.append(i)
83
+
84
+ if len(pos_find_ids) >= self.max_num_find_queries:
85
+ # we have more positive find queries than `max_num_find_queries`,
86
+ # so we subsample postive find queries and remove all negative find queries
87
+ num_queries_to_filter = len(pos_find_ids) - self.max_num_find_queries
88
+ query_ids_to_filter = random.sample(
89
+ pos_find_ids, k=num_queries_to_filter
90
+ )
91
+ query_ids_to_filter.extend(neg_find_ids)
92
+ else:
93
+ # we have fewer positive find queries than `max_num_find_queries`
94
+ # so we need to fill the remaining with negative find queries
95
+ num_queries_to_filter = num_find_queries - self.max_num_find_queries
96
+ query_ids_to_filter = random.sample(
97
+ neg_find_ids, k=num_queries_to_filter
98
+ )
99
+
100
+ assert len(query_ids_to_filter) == num_find_queries - self.max_num_find_queries
101
+ self.find_ids_to_filter = set(query_ids_to_filter)
102
+
103
+
104
+ class KeepMaxNumFindQueriesVideo(FilterDataPointQueries):
105
+ def __init__(
106
+ self,
107
+ video_mosaic_max_num_find_queries_per_frame: int,
108
+ retain_positive_queries: bool = False,
109
+ ):
110
+ self.video_mosaic_max_num_find_queries_per_frame = (
111
+ video_mosaic_max_num_find_queries_per_frame
112
+ )
113
+ self.retain_positive_queries = retain_positive_queries
114
+
115
+ def identify_queries_to_filter(self, datapoint: Datapoint) -> None:
116
+ self.obj_ids_to_filter = set()
117
+ num_find_queries = len(datapoint.find_queries)
118
+
119
+ findQueries_to_imageIds = defaultdict(list)
120
+ max_queries_per_frame = True
121
+ for i, f_q in enumerate(datapoint.find_queries):
122
+ findQueries_to_imageIds[f_q.image_id].append(i)
123
+ if (
124
+ len(findQueries_to_imageIds[f_q.image_id])
125
+ > self.video_mosaic_max_num_find_queries_per_frame
126
+ ):
127
+ max_queries_per_frame = False
128
+
129
+ if max_queries_per_frame:
130
+ self.find_ids_to_filter = set()
131
+ return
132
+
133
+ num_frames = len(findQueries_to_imageIds)
134
+ findQueries_0 = findQueries_to_imageIds[0]
135
+ num_find_queries_0 = len(findQueries_0)
136
+ max_num_find_queries_per_frame = (
137
+ self.video_mosaic_max_num_find_queries_per_frame
138
+ )
139
+ if not self.retain_positive_queries:
140
+ find_query_ids_0 = list(range(num_find_queries_0))
141
+ num_queries_to_filter = max(
142
+ 0, num_find_queries_0 - max_num_find_queries_per_frame
143
+ )
144
+ query_ids_to_filter_0 = random.sample(
145
+ find_query_ids_0, k=num_queries_to_filter
146
+ )
147
+ else:
148
+ # keep up to max_num_find_queries postive find queries and fill
149
+ # the remaining slots (if any) with negative find queries
150
+ pos_find_ids_0, neg_find_ids_0 = [], []
151
+ for i, f_q_id in enumerate(findQueries_0):
152
+ f_q = datapoint.find_queries[f_q_id]
153
+ # Negative finds return an empty list of object_ids_output
154
+ if len(f_q.object_ids_output) == 0:
155
+ neg_find_ids_0.append(i)
156
+ else:
157
+ pos_find_ids_0.append(i)
158
+
159
+ if len(pos_find_ids_0) >= max_num_find_queries_per_frame:
160
+ # we have more positive find queries than `max_num_find_queries`,
161
+ # so we subsample postive find queries and remove all negative find queries
162
+ num_queries_to_filter = (
163
+ len(pos_find_ids_0) - max_num_find_queries_per_frame
164
+ )
165
+ query_ids_to_filter_0 = random.sample(
166
+ pos_find_ids_0, k=num_queries_to_filter
167
+ )
168
+ query_ids_to_filter_0.extend(neg_find_ids_0)
169
+ else:
170
+ # we have fewer positive find queries than `max_num_find_queries`
171
+ # so we need to fill the remaining with negative find queries
172
+ num_queries_to_filter = (
173
+ num_find_queries_0 - max_num_find_queries_per_frame
174
+ )
175
+ query_ids_to_filter_0 = random.sample(
176
+ neg_find_ids_0, k=num_queries_to_filter
177
+ )
178
+
179
+ # get based on frame 0 all find queries from all the frames with the same indices as in frame 0
180
+ query_ids_to_filter = []
181
+ for i in range(num_frames):
182
+ findQueries_i = findQueries_to_imageIds[i]
183
+ query_ids_to_filter.extend(
184
+ [findQueries_i[j] for j in query_ids_to_filter_0]
185
+ )
186
+
187
+ assert (
188
+ len(query_ids_to_filter)
189
+ == num_find_queries
190
+ - self.video_mosaic_max_num_find_queries_per_frame * num_frames
191
+ )
192
+ self.find_ids_to_filter = set(query_ids_to_filter)
193
+
194
+
195
+ class KeepSemanticFindQueriesOnly(FilterDataPointQueries):
196
+ def identify_queries_to_filter(self, datapoint: Datapoint) -> None:
197
+ self.obj_ids_to_filter = set()
198
+ self.find_ids_to_filter = {
199
+ i for i, q in enumerate(datapoint.find_queries) if q.input_bbox is not None
200
+ } # filter (remove) geometric find queries (whose input_bbox is not None)
201
+
202
+ # Keep all get queries which don't depend on filtered finds
203
+
204
+
205
+ class KeepUnaryFindQueriesOnly(FilterDataPointQueries):
206
+ def identify_queries_to_filter(self, datapoint: Datapoint) -> None:
207
+ self.obj_ids_to_filter = set()
208
+ self.find_ids_to_filter = set()
209
+
210
+ # Keep all get queries which don't depend on filtered finds
211
+
212
+
213
+ class FilterZeroBoxQueries(FilterDataPointQueries):
214
+ """
215
+ Filters all find queries which predict a box with zero area
216
+ """
217
+
218
+ @staticmethod
219
+ def _is_zero_area_object(obj: Object):
220
+ # Check if height or width of bounding box is zero
221
+ bbox = obj.bbox # Assume in XYXY format
222
+ height = bbox[..., 3].item() - bbox[..., 1].item()
223
+ width = bbox[..., 2].item() - bbox[..., 0].item()
224
+
225
+ return height == 0 or width == 0
226
+
227
+ def identify_queries_to_filter(self, datapoint):
228
+ self.obj_ids_to_filter = set()
229
+
230
+ # Find objects with zero area
231
+ # Assume only one image per datapoint
232
+ image_objects = datapoint.images[0].objects
233
+ exclude_objects = {
234
+ obj_id
235
+ for obj_id, obj in enumerate(image_objects)
236
+ if self._is_zero_area_object(obj)
237
+ }
238
+
239
+ # If a query predicts an object with zero area, drop the whole find query
240
+ del_find_ids = []
241
+ for i, f_q in enumerate(datapoint.find_queries):
242
+ f_q_objects = set(f_q.object_ids_output)
243
+ if len(exclude_objects.intersection(f_q_objects)) > 0:
244
+ del_find_ids.append(i)
245
+
246
+ self.find_ids_to_filter = set(del_find_ids)
247
+
248
+
249
+ class FilterFindQueriesWithTooManyOut(FilterDataPointQueries):
250
+ """
251
+ Filters all find queries which have more than a specified number of objects in the output
252
+ """
253
+
254
+ def __init__(self, max_num_objects: int):
255
+ self.max_num_objects = max_num_objects
256
+
257
+ def identify_queries_to_filter(self, datapoint):
258
+ self.obj_ids_to_filter = set()
259
+
260
+ # If a query predicts more than max_num_objects, drop the whole find query
261
+ del_find_ids = []
262
+ for i, f_q in enumerate(datapoint.find_queries):
263
+ if len(f_q.object_ids_output) > self.max_num_objects:
264
+ del_find_ids.append(i)
265
+
266
+ self.find_ids_to_filter = set(del_find_ids)
267
+
268
+
269
+ class FilterEmptyTargets(FilterDataPointQueries):
270
+ """
271
+ Filters all targets which have zero area
272
+ """
273
+
274
+ def identify_queries_to_filter(self, datapoint):
275
+ self.obj_ids_to_filter = set()
276
+
277
+ for img_id in range(len(datapoint.images)):
278
+ for obj_id, obj in enumerate(datapoint.images[img_id].objects):
279
+ if obj.area < 1e-6:
280
+ self.obj_ids_to_filter.add((img_id, obj_id))
281
+ self.find_ids_to_filter = set()
282
+
283
+
284
+ class FilterNonExhaustiveFindQueries(FilterDataPointQueries):
285
+ """
286
+ Filters all find queries which are non-exhaustive
287
+ """
288
+
289
+ def __init__(self, exhaustivity_type: str):
290
+ """
291
+ Args:
292
+ exhaustivity_type: Can be "pixel" or "instance":
293
+ -pixel: filter queries where the union of all segments covers every pixel belonging to target class
294
+ -instance: filter queries where there are non-separable or non annotated instances
295
+ Note that instance exhaustivity implies pixel exhaustivity
296
+ """
297
+ assert exhaustivity_type in ["pixel", "instance"]
298
+ self.exhaustivity_type = exhaustivity_type
299
+
300
+ def identify_queries_to_filter(self, datapoint):
301
+ self.obj_ids_to_filter = set()
302
+
303
+ # If a query predicts more than max_num_objects, drop the whole find query
304
+ del_find_ids = []
305
+ for i, f_q in enumerate(datapoint.find_queries):
306
+ if self.exhaustivity_type == "instance":
307
+ if not f_q.is_exhaustive:
308
+ del_find_ids.append(i)
309
+ elif self.exhaustivity_type == "pixel":
310
+ if f_q.is_pixel_exhaustive is not None and not f_q.is_pixel_exhaustive:
311
+ del_find_ids.append(i)
312
+ else:
313
+ raise RuntimeError(
314
+ f"Unknown exhaustivity type {self.exhaustivity_type}"
315
+ )
316
+
317
+ self.find_ids_to_filter = set(del_find_ids)
318
+
319
+
320
+ class FilterInvalidGeometricQueries(FilterDataPointQueries):
321
+ """
322
+ Filters geometric queries whose output got deleted (eg due to cropping)
323
+ """
324
+
325
+ def identify_queries_to_filter(self, datapoint):
326
+ self.obj_ids_to_filter = set()
327
+
328
+ # If a query predicts more than max_num_objects, drop the whole find query
329
+ del_find_ids = []
330
+ for i, f_q in enumerate(datapoint.find_queries):
331
+ if f_q.input_bbox is not None and f_q.query_text == "geometric":
332
+ if len(f_q.object_ids_output) == 0:
333
+ del_find_ids.append(i)
334
+ self.find_ids_to_filter = set(del_find_ids)
335
+
336
+
337
+ class FlexibleFilterFindGetQueries:
338
+ def __init__(
339
+ self, query_filter: FilterDataPointQueries, enabled: bool = True
340
+ ) -> None:
341
+ self.query_filter = query_filter
342
+ self.enabled = enabled
343
+
344
+ def __call__(self, datapoint, **kwargs):
345
+ if not self.enabled:
346
+ return datapoint
347
+
348
+ # Identify all queries to filter
349
+ self.query_filter.identify_queries_to_filter(datapoint=datapoint)
350
+
351
+ del_find_ids = []
352
+ del_get_ids = []
353
+ for i, f_q in enumerate(datapoint.find_queries):
354
+ if self.query_filter._do_filter_query(f_q, i):
355
+ datapoint.find_queries[i] = None
356
+ del_find_ids.append(i)
357
+
358
+ new_find_queries = []
359
+ new_get_queries = []
360
+
361
+ find_old_to_new_map = {}
362
+ get_old_to_new_map = {}
363
+
364
+ find_counter = 0
365
+ get_counter = 0
366
+
367
+ for i, f_q in enumerate(datapoint.find_queries):
368
+ if f_q is not None:
369
+ find_old_to_new_map[i] = find_counter
370
+ find_counter += 1
371
+ new_find_queries.append(f_q)
372
+
373
+ start_with_zero_check = False
374
+ for n_f_q in new_find_queries:
375
+ if n_f_q.query_processing_order == 0:
376
+ start_with_zero_check = True
377
+ break
378
+
379
+ if len(new_find_queries) == 0:
380
+ start_with_zero_check = True
381
+
382
+ assert start_with_zero_check, (
383
+ "Invalid Find queries, they need to start at query_processing_order = 0"
384
+ )
385
+
386
+ datapoint.find_queries = new_find_queries
387
+
388
+ if len(datapoint.find_queries) == 0:
389
+ print("Warning: No find queries left in datapoint, this is not allowed")
390
+ print("Filtering function:", self.query_filter)
391
+ print("Datapoint:", datapoint)
392
+ raise ValueError
393
+
394
+ # The deletion may have removed intermediate steps, so we need to remap to make them contiguous again
395
+ all_stages = sorted(
396
+ list(set(q.query_processing_order for q in datapoint.find_queries))
397
+ )
398
+ stage_map = {qpo: i for i, qpo in enumerate(all_stages)}
399
+ for i in range(len(datapoint.find_queries)):
400
+ qpo = datapoint.find_queries[i].query_processing_order
401
+ datapoint.find_queries[i].query_processing_order = stage_map[qpo]
402
+
403
+ # Final step, clear up objects that are not used anymore
404
+ for img_id in range(len(datapoint.images)):
405
+ all_objects_ids = set(
406
+ i
407
+ for find in datapoint.find_queries
408
+ for i in find.object_ids_output
409
+ if find.image_id == img_id
410
+ )
411
+ unused_ids = (
412
+ set(range(len(datapoint.images[img_id].objects))) - all_objects_ids
413
+ )
414
+ for tgt_img_id, tgt_obj_id in self.query_filter.obj_ids_to_filter:
415
+ if tgt_img_id == img_id:
416
+ unused_ids.add(tgt_obj_id)
417
+
418
+ if len(unused_ids) > 0:
419
+ old_objects = datapoint.images[img_id].objects
420
+ object_old_to_new_map = {}
421
+ new_objects = []
422
+ for i, o in enumerate(old_objects):
423
+ if i not in unused_ids:
424
+ object_old_to_new_map[i] = len(new_objects)
425
+ new_objects.append(o)
426
+
427
+ datapoint.images[img_id].objects = new_objects
428
+
429
+ # Remap the outputs of the find queries
430
+ affected_find_queries_ids = set()
431
+ object_old_to_new_map_per_query = {}
432
+ for fid, find in enumerate(datapoint.find_queries):
433
+ if find.image_id == img_id:
434
+ old_object_ids_output = find.object_ids_output
435
+ object_old_to_new_map_per_query[fid] = {}
436
+ find.object_ids_output = []
437
+ for oid, old_obj_id in enumerate(old_object_ids_output):
438
+ if old_obj_id not in unused_ids:
439
+ new_obj_id = object_old_to_new_map[old_obj_id]
440
+ find.object_ids_output.append(new_obj_id)
441
+ object_old_to_new_map_per_query[fid][oid] = (
442
+ len(find.object_ids_output) - 1
443
+ )
444
+ affected_find_queries_ids.add(fid)
445
+
446
+ # finally remove unused images
447
+ all_imgs_to_keep = set()
448
+ for f_q in datapoint.find_queries:
449
+ all_imgs_to_keep.add(f_q.image_id)
450
+
451
+ old_img_id_to_new_img_id = {}
452
+ new_images = []
453
+ for img_id, img in enumerate(datapoint.images):
454
+ if img_id in all_imgs_to_keep:
455
+ old_img_id_to_new_img_id[img_id] = len(new_images)
456
+ new_images.append(img)
457
+ datapoint.images = new_images
458
+
459
+ for f_q in datapoint.find_queries:
460
+ f_q.image_id = old_img_id_to_new_img_id[f_q.image_id]
461
+
462
+ return datapoint
463
+
464
+
465
+ class AddPrefixSuffixToFindText:
466
+ """
467
+ Add prefix or suffix strings to find query text on the fly.
468
+
469
+ If `condition_on_text` is True, the prefix or suffix strings are only added
470
+ to those find query text in `condition_text_list` (case-insensitive).
471
+ """
472
+
473
+ def __init__(
474
+ self,
475
+ prefix: Optional[str] = None,
476
+ suffix: Optional[str] = None,
477
+ condition_on_text: bool = False,
478
+ condition_text_list: Optional[List[str]] = None,
479
+ enabled: bool = True,
480
+ ) -> None:
481
+ self.prefix = prefix
482
+ self.suffix = suffix
483
+ self.condition_on_text = condition_on_text
484
+ if self.condition_on_text:
485
+ assert condition_text_list is not None
486
+ self.condition_text_set = {s.lower().strip() for s in condition_text_list}
487
+ self.enabled = enabled
488
+ if self.enabled:
489
+ logging.info(
490
+ f"AddPrefixSuffixToFindText: prefix={prefix}, suffix={suffix}, "
491
+ f"condition_on_text={condition_on_text}, condition_text_list={condition_text_list}"
492
+ )
493
+
494
+ def __call__(self, datapoint, **kwargs):
495
+ if not self.enabled:
496
+ return datapoint
497
+
498
+ for find in datapoint.find_queries:
499
+ if find.query_text == "geometric":
500
+ # skip geometric find queries
501
+ continue
502
+ if (
503
+ self.condition_on_text
504
+ and find.query_text.lower().strip() not in self.condition_text_set
505
+ ):
506
+ # if condition_on_text is True, skip those queries not in condition_text_set
507
+ continue
508
+
509
+ # add prefix and/or suffix strings to the find query text
510
+ if self.prefix is not None:
511
+ find.query_text = self.prefix + find.query_text
512
+ if self.suffix is not None:
513
+ find.query_text = find.query_text + self.suffix
514
+
515
+ return datapoint
516
+
517
+
518
+ class FilterCrowds(FilterDataPointQueries):
519
+ def identify_queries_to_filter(self, datapoint: Datapoint) -> None:
520
+ """
521
+ Compute set of query ids to keep, for both find and get queries
522
+ """
523
+ self.obj_ids_to_filter = set()
524
+ self.find_ids_to_filter = set()
525
+ # self.get_ids_to_filter = set()
526
+ for img_id, img in enumerate(datapoint.images):
527
+ for obj_id, obj in enumerate(img.objects):
528
+ if obj.is_crowd:
529
+ self.obj_ids_to_filter.add((img_id, obj_id))
530
+
531
+
532
+ class TextQueryToVisual:
533
+ """
534
+ Transform a test query to a visual query (with some proba), using any of the output targets as the prompt
535
+ """
536
+
537
+ def __init__(self, probability, keep_text_queries=False) -> None:
538
+ self.probability = probability
539
+ assert 0 <= probability <= 1
540
+ self.keep_text_queries = keep_text_queries
541
+
542
+ def __call__(self, datapoint: Datapoint, **kwargs):
543
+ for find in datapoint.find_queries:
544
+ if find.input_bbox is not None or find.input_points is not None:
545
+ # skip geometric find queries
546
+ continue
547
+
548
+ if len(find.object_ids_output) == 0:
549
+ # Can't create a visual query, skip
550
+ continue
551
+
552
+ if find.query_processing_order > 0:
553
+ # Second stage query, can't use
554
+ continue
555
+
556
+ if random.random() > self.probability:
557
+ continue
558
+
559
+ selected_vq_id = random.choice(find.object_ids_output)
560
+ img_id = find.image_id
561
+
562
+ find.input_bbox = datapoint.images[img_id].objects[selected_vq_id].bbox
563
+ find.input_bbox_label = torch.ones(1, dtype=torch.bool)
564
+ if not self.keep_text_queries:
565
+ find.query_text = "visual"
566
+
567
+ return datapoint
568
+
569
+
570
+ class RemoveInputBoxes:
571
+ """
572
+ Remove input boxes from find queries
573
+ """
574
+
575
+ def __init__(self) -> None:
576
+ pass
577
+
578
+ def __call__(self, datapoint: Datapoint, **kwargs):
579
+ for find in datapoint.find_queries:
580
+ if find.input_bbox is None:
581
+ continue
582
+
583
+ if find.query_text == "geometric":
584
+ print("Warning: removing input box from geometric find query")
585
+
586
+ find.input_bbox = None
587
+ return datapoint
588
+
589
+
590
+ class OverwriteTextQuery:
591
+ """
592
+ With some probability, overwrite the text query with a custom text
593
+ """
594
+
595
+ def __init__(self, target_text, probability=1.0) -> None:
596
+ self.probability = probability
597
+ self.target_text = target_text
598
+ assert 0 <= probability <= 1
599
+
600
+ def __call__(self, datapoint: Datapoint, **kwargs):
601
+ for find in datapoint.find_queries:
602
+ if random.random() > self.probability:
603
+ continue
604
+
605
+ find.query_text = self.target_text
606
+
607
+ return datapoint
OVOW/third_party/sam3/sam3/train/transforms/point_sampling.py ADDED
@@ -0,0 +1,346 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
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 torch
8
+ from PIL import Image as PILImage
9
+ from pycocotools import mask as mask_util
10
+ from sam3.train.data.sam3_image_dataset import Datapoint
11
+ from torchvision.ops import masks_to_boxes
12
+
13
+
14
+ def sample_points_from_rle(rle, n_points, mode, box=None, normalize=True):
15
+ """
16
+ Sample random points from a mask provided in COCO RLE format. 'mode'
17
+ 'mode' is in ["centered", "random_mask", "random_box"]
18
+ "centered": points are sampled farthest from the mask edges and each other
19
+ "random_mask": points are sampled uniformly from the mask
20
+ "random_box": points are sampled uniformly from the annotation's box
21
+ 'box' must be provided if 'mode' is "random_box".
22
+ If 'normalize' is true, points are in [0,1], relative to mask h,w.
23
+ """
24
+ mask = np.ascontiguousarray(mask_util.decode(rle))
25
+ points = sample_points_from_mask(mask, n_points, mode, box)
26
+
27
+ if normalize:
28
+ h, w = mask.shape
29
+ norm = np.array([w, h, 1.0])[None, :]
30
+ points = points / norm
31
+
32
+ return points
33
+
34
+
35
+ def sample_points_from_mask(mask, n_points, mode, box=None):
36
+ if mode == "centered":
37
+ points = center_positive_sample(mask, n_points)
38
+ elif mode == "random_mask":
39
+ points = uniform_positive_sample(mask, n_points)
40
+ elif mode == "random_box":
41
+ assert box is not None, "'random_box' mode requires a provided box."
42
+ points = uniform_sample_from_box(mask, box, n_points)
43
+ else:
44
+ raise ValueError(f"Unknown point sampling mode {mode}.")
45
+ return points
46
+
47
+
48
+ def uniform_positive_sample(mask, n_points):
49
+ """
50
+ Samples positive points uniformly from the mask. Only integer pixel
51
+ values are sampled.
52
+ """
53
+ # Sampling directly from the uncompressed RLE would be faster but is
54
+ # likely unnecessary.
55
+ mask_points = np.stack(np.nonzero(mask), axis=0).transpose(1, 0)
56
+ assert len(mask_points) > 0, "Can't sample positive points from an empty mask."
57
+ selected_idxs = np.random.randint(low=0, high=len(mask_points), size=n_points)
58
+ selected_points = mask_points[selected_idxs]
59
+
60
+ selected_points = selected_points[:, ::-1] # (y, x) -> (x, y)
61
+ labels = np.ones((len(selected_points), 1))
62
+ selected_points = np.concatenate([selected_points, labels], axis=1)
63
+
64
+ return selected_points
65
+
66
+
67
+ def center_positive_sample(mask, n_points):
68
+ """
69
+ Samples points farthest from mask edges (by distance transform)
70
+ and subsequent points also farthest from each other. Each new point
71
+ sampled is treated as an edge for future points. Edges of the image are
72
+ treated as edges of the mask.
73
+ """
74
+
75
+ # Pad mask by one pixel on each end to assure distance transform
76
+ # avoids edges
77
+ padded_mask = np.pad(mask, 1)
78
+
79
+ points = []
80
+ for _ in range(n_points):
81
+ assert np.max(mask) > 0, "Can't sample positive points from an empty mask."
82
+ dist = cv2.distanceTransform(padded_mask, cv2.DIST_L2, 0)
83
+ point = np.unravel_index(dist.argmax(), dist.shape)
84
+ # Mark selected point as background so next point avoids it
85
+ padded_mask[point[0], point[1]] = 0
86
+ points.append(point[::-1]) # (y, x) -> (x, y)
87
+
88
+ points = np.stack(points, axis=0)
89
+ points = points - 1 # Subtract left/top padding of 1
90
+ labels = np.ones((len(points), 1))
91
+ points = np.concatenate([points, labels], axis=1)
92
+
93
+ return points
94
+
95
+
96
+ def uniform_sample_from_box(mask, box, n_points):
97
+ """
98
+ Sample points uniformly from the provided box. The points' labels
99
+ are determined by the provided mask. Does not guarantee a positive
100
+ point is sampled. The box is assumed unnormalized in XYXY format.
101
+ Points are sampled at integer values.
102
+ """
103
+
104
+ # Since lower/right edges are exclusive, ceil can be applied to all edges
105
+ int_box = np.ceil(box)
106
+
107
+ x = np.random.randint(low=int_box[0], high=int_box[2], size=n_points)
108
+ y = np.random.randint(low=int_box[1], high=int_box[3], size=n_points)
109
+ labels = mask[y, x]
110
+ points = np.stack([x, y, labels], axis=1)
111
+
112
+ return points
113
+
114
+
115
+ def rescale_box_xyxy(box, factor, imsize=None):
116
+ """
117
+ Rescale a box providing in unnormalized XYXY format, fixing the center.
118
+ If imsize is provided, clamp to the image.
119
+ """
120
+ cx, cy = (box[0] + box[2]) / 2, (box[1] + box[3]) / 2
121
+ w, h = box[2] - box[0], box[3] - box[1]
122
+
123
+ new_w, new_h = factor * w, factor * h
124
+
125
+ new_x0, new_y0 = cx - new_w / 2, cy - new_h / 2
126
+ new_x1, new_y1 = cx + new_w / 2, cy + new_h / 2
127
+
128
+ if imsize is not None:
129
+ new_x0 = max(min(new_x0, imsize[1]), 0)
130
+ new_x1 = max(min(new_x1, imsize[1]), 0)
131
+ new_y0 = max(min(new_y0, imsize[0]), 0)
132
+ new_y1 = max(min(new_y1, imsize[0]), 0)
133
+
134
+ return [new_x0, new_y0, new_x1, new_y1]
135
+
136
+
137
+ def noise_box(box, im_size, box_noise_std, box_noise_max, min_box_area):
138
+ if box_noise_std <= 0.0:
139
+ return box
140
+ noise = box_noise_std * torch.randn(size=(4,))
141
+ w, h = box[2] - box[0], box[3] - box[1]
142
+ scale_factor = torch.tensor([w, h, w, h])
143
+ noise = noise * scale_factor
144
+ if box_noise_max is not None:
145
+ noise = torch.clamp(noise, -box_noise_max, box_noise_max)
146
+ input_box = box + noise
147
+ # Clamp to maximum image size
148
+ img_clamp = torch.tensor([im_size[1], im_size[0], im_size[1], im_size[0]])
149
+ input_box = torch.maximum(input_box, torch.zeros_like(input_box))
150
+ input_box = torch.minimum(input_box, img_clamp)
151
+ if (input_box[2] - input_box[0]) * (input_box[3] - input_box[1]) <= min_box_area:
152
+ return box
153
+
154
+ return input_box
155
+
156
+
157
+ class RandomGeometricInputsAPI:
158
+ """
159
+ For geometric queries, replaces the input box or points with a random
160
+ one sampled from the GT mask. Segments must be provided for objects
161
+ that are targets of geometric queries, and must be binary masks. Existing
162
+ point and box queries in the datapoint will be ignored and completely replaced.
163
+ Will sample points and boxes in XYXY format in absolute pixel space.
164
+
165
+ Geometry queries are currently determined by taking any query whose
166
+ query text is a set value.
167
+
168
+ Args:
169
+ num_points (int or (int, int)): how many points to sample. If a tuple,
170
+ sample a random number of points uniformly over the inclusive range.
171
+ box_chance (float): fraction of time a box is sampled. A box will replace
172
+ one sampled point.
173
+ box_noise_std (float): if greater than 0, add noise to the sampled boxes
174
+ with this std. Noise is relative to the length of the box side.
175
+ box_noise_max (int): if not none, truncate any box noise larger than this
176
+ in terms of absolute pixels.
177
+ resample_box_from_mask (bool): if True, any sampled box will be determined
178
+ by finding the extrema of the provided mask. If False, the bbox provided
179
+ in the target object will be used.
180
+ point_sample_mode (str): In ["centered", "random_mask", "random_box"],
181
+ controlling how points are sampled:
182
+ "centered": points are sampled farthest from the mask edges and each other
183
+ "random_mask": points are sampled uniformly from the mask
184
+ "random_box": points are sampled uniformly from the annotation's box
185
+ Note that "centered" may be too slow for on-line generation.
186
+ geometric_query_str (str): what string in query_text indicates a
187
+ geometry query.
188
+ minimum_box_area (float): sampled boxes with area this size or smaller after
189
+ noising will use the original box instead. It is the input's responsibility
190
+ to avoid original boxes that violate necessary area bounds.
191
+ concat_points (bool): if True, any sampled points will be added to existing
192
+ ones instead of replacing them.
193
+
194
+ """
195
+
196
+ def __init__(
197
+ self,
198
+ num_points,
199
+ box_chance,
200
+ box_noise_std=0.0,
201
+ box_noise_max=None,
202
+ minimum_box_area=0.0,
203
+ resample_box_from_mask=False,
204
+ point_sample_mode="random_mask",
205
+ sample_box_scale_factor=1.0,
206
+ geometric_query_str="geometric",
207
+ concat_points=False,
208
+ ):
209
+ self.num_points = num_points
210
+ if not isinstance(self.num_points, int):
211
+ # Convert from inclusive range to exclusive range expected by torch
212
+ self.num_points[1] += 1
213
+ self.num_points = tuple(self.num_points)
214
+ self.box_chance = box_chance
215
+ self.box_noise_std = box_noise_std
216
+ self.box_noise_max = box_noise_max
217
+ self.minimum_box_area = minimum_box_area
218
+ self.resample_box_from_mask = resample_box_from_mask
219
+ self.point_sample_mode = point_sample_mode
220
+ assert point_sample_mode in [
221
+ "centered",
222
+ "random_mask",
223
+ "random_box",
224
+ ], "Unknown point sample mode."
225
+ self.geometric_query_str = geometric_query_str
226
+ self.concat_points = concat_points
227
+ self.sample_box_scale_factor = sample_box_scale_factor
228
+
229
+ def _sample_num_points_and_if_box(self):
230
+ if isinstance(self.num_points, tuple):
231
+ n_points = torch.randint(
232
+ low=self.num_points[0], high=self.num_points[1], size=(1,)
233
+ ).item()
234
+ else:
235
+ n_points = self.num_points
236
+ if self.box_chance > 0.0:
237
+ use_box = torch.rand(size=(1,)).item() < self.box_chance
238
+ n_points -= int(use_box) # box stands in for one point
239
+ else:
240
+ use_box = False
241
+ return n_points, use_box
242
+
243
+ def _get_original_box(self, target_object):
244
+ if not self.resample_box_from_mask:
245
+ return target_object.bbox
246
+ mask = target_object.segment
247
+ return masks_to_boxes(mask[None, :, :])[0]
248
+
249
+ def _get_target_object(self, datapoint, query):
250
+ img = datapoint.images[query.image_id]
251
+ targets = query.object_ids_output
252
+ assert len(targets) == 1, (
253
+ "Geometric queries only support a single target object."
254
+ )
255
+ target_idx = targets[0]
256
+ return img.objects[target_idx]
257
+
258
+ def __call__(self, datapoint, **kwargs):
259
+ for query in datapoint.find_queries:
260
+ if query.query_text != self.geometric_query_str:
261
+ continue
262
+
263
+ target_object = self._get_target_object(datapoint, query)
264
+ n_points, use_box = self._sample_num_points_and_if_box()
265
+ box = self._get_original_box(target_object)
266
+
267
+ mask = target_object.segment
268
+ if n_points > 0:
269
+ # FIXME: The conversion to numpy and back to reuse code
270
+ # is awkward, but this is all in the dataloader worker anyway
271
+ # on CPU and so I don't think it should matter.
272
+ if self.sample_box_scale_factor != 1.0:
273
+ sample_box = rescale_box_xyxy(
274
+ box.numpy(), self.sample_box_scale_factor, mask.shape
275
+ )
276
+ else:
277
+ sample_box = box.numpy()
278
+ input_points = sample_points_from_mask(
279
+ mask.numpy(),
280
+ n_points,
281
+ self.point_sample_mode,
282
+ sample_box,
283
+ )
284
+ input_points = torch.as_tensor(input_points)
285
+ input_points = input_points[None, :, :]
286
+ if self.concat_points and query.input_points is not None:
287
+ input_points = torch.cat([query.input_points, input_points], dim=1)
288
+ else:
289
+ input_points = query.input_points if self.concat_points else None
290
+
291
+ if use_box:
292
+ w, h = datapoint.images[query.image_id].size
293
+ input_box = noise_box(
294
+ box,
295
+ (h, w),
296
+ box_noise_std=self.box_noise_std,
297
+ box_noise_max=self.box_noise_max,
298
+ min_box_area=self.minimum_box_area,
299
+ )
300
+ input_box = input_box[None, :]
301
+ else:
302
+ input_box = query.input_bbox if self.concat_points else None
303
+
304
+ query.input_points = input_points
305
+ query.input_bbox = input_box
306
+
307
+ return datapoint
308
+
309
+
310
+ class RandomizeInputBbox:
311
+ """
312
+ Simplified version of the geometric transform that only deals with input boxes
313
+ """
314
+
315
+ def __init__(
316
+ self,
317
+ box_noise_std=0.0,
318
+ box_noise_max=None,
319
+ minimum_box_area=0.0,
320
+ ):
321
+ self.box_noise_std = box_noise_std
322
+ self.box_noise_max = box_noise_max
323
+ self.minimum_box_area = minimum_box_area
324
+
325
+ def __call__(self, datapoint: Datapoint, **kwargs):
326
+ for query in datapoint.find_queries:
327
+ if query.input_bbox is None:
328
+ continue
329
+
330
+ img = datapoint.images[query.image_id].data
331
+ if isinstance(img, PILImage.Image):
332
+ w, h = img.size
333
+ else:
334
+ assert isinstance(img, torch.Tensor)
335
+ h, w = img.shape[-2:]
336
+
337
+ for box_id in range(query.input_bbox.shape[0]):
338
+ query.input_bbox[box_id, :] = noise_box(
339
+ query.input_bbox[box_id, :].view(4),
340
+ (h, w),
341
+ box_noise_std=self.box_noise_std,
342
+ box_noise_max=self.box_noise_max,
343
+ min_box_area=self.minimum_box_area,
344
+ ).view(1, 4)
345
+
346
+ return datapoint
OVOW/third_party/sam3/sam3/train/transforms/segmentation.py ADDED
@@ -0,0 +1,156 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ # Copyright (c) Meta Platforms, Inc. and affiliates. All Rights Reserved
2
+
3
+ # pyre-unsafe
4
+
5
+ import numpy as np
6
+ import pycocotools.mask as mask_utils
7
+ import torch
8
+ import torchvision.transforms.functional as F
9
+ from PIL import Image as PILImage
10
+ from sam3.model.box_ops import masks_to_boxes
11
+ from sam3.train.data.sam3_image_dataset import Datapoint
12
+
13
+
14
+ class InstanceToSemantic(object):
15
+ """Convert instance segmentation to semantic segmentation."""
16
+
17
+ def __init__(self, delete_instance=True, use_rle=False):
18
+ self.delete_instance = delete_instance
19
+ self.use_rle = use_rle
20
+
21
+ def __call__(self, datapoint: Datapoint, **kwargs):
22
+ for fquery in datapoint.find_queries:
23
+ h, w = datapoint.images[fquery.image_id].size
24
+
25
+ if self.use_rle:
26
+ all_segs = [
27
+ datapoint.images[fquery.image_id].objects[obj_id].segment
28
+ for obj_id in fquery.object_ids_output
29
+ ]
30
+ if len(all_segs) > 0:
31
+ # we need to double check that all rles are the correct size
32
+ # Otherwise cocotools will fail silently to an empty [0,0] mask
33
+ for seg in all_segs:
34
+ assert seg["size"] == all_segs[0]["size"], (
35
+ "Instance segments have inconsistent sizes. "
36
+ f"Found sizes {seg['size']} and {all_segs[0]['size']}"
37
+ )
38
+ fquery.semantic_target = mask_utils.merge(all_segs)
39
+ else:
40
+ # There is no good way to create an empty RLE of the correct size
41
+ # We resort to converting an empty box to RLE
42
+ fquery.semantic_target = mask_utils.frPyObjects(
43
+ np.array([[0, 0, 0, 0]], dtype=np.float64), h, w
44
+ )[0]
45
+
46
+ else:
47
+ # `semantic_target` is uint8 and remains uint8 throughout the transforms
48
+ # (it contains binary 0 and 1 values just like `segment` for each object)
49
+ fquery.semantic_target = torch.zeros((h, w), dtype=torch.uint8)
50
+ for obj_id in fquery.object_ids_output:
51
+ segment = datapoint.images[fquery.image_id].objects[obj_id].segment
52
+ if segment is not None:
53
+ assert (
54
+ isinstance(segment, torch.Tensor)
55
+ and segment.dtype == torch.uint8
56
+ )
57
+ fquery.semantic_target |= segment
58
+
59
+ if self.delete_instance:
60
+ for img in datapoint.images:
61
+ for obj in img.objects:
62
+ del obj.segment
63
+ obj.segment = None
64
+
65
+ return datapoint
66
+
67
+
68
+ class RecomputeBoxesFromMasks:
69
+ """Recompute bounding boxes from masks."""
70
+
71
+ def __call__(self, datapoint: Datapoint, **kwargs):
72
+ for img in datapoint.images:
73
+ for obj in img.objects:
74
+ # Note: if the mask is empty, the bounding box will be undefined
75
+ # The empty targets should be subsequently filtered
76
+ obj.bbox = masks_to_boxes(obj.segment)
77
+ obj.area = obj.segment.sum().item()
78
+
79
+ return datapoint
80
+
81
+
82
+ class DecodeRle:
83
+ """This transform decodes RLEs into binary segments.
84
+ Implementing it as a transforms allows lazy loading. Some transforms (eg query filters)
85
+ may be deleting masks, so decoding them from the beginning is wasteful.
86
+
87
+ This transforms needs to be called before any kind of geometric manipulation
88
+ """
89
+
90
+ def __call__(self, datapoint: Datapoint, **kwargs):
91
+ imgId2size = {}
92
+ warning_shown = False
93
+ for imgId, img in enumerate(datapoint.images):
94
+ if isinstance(img.data, PILImage.Image):
95
+ img_w, img_h = img.data.size
96
+ elif isinstance(img.data, torch.Tensor):
97
+ img_w, img_h = img.data.shape[-2:]
98
+ else:
99
+ raise RuntimeError(f"Unexpected image type {type(img.data)}")
100
+
101
+ imgId2size[imgId] = (img_h, img_w)
102
+
103
+ for obj in img.objects:
104
+ if obj.segment is not None and not isinstance(
105
+ obj.segment, torch.Tensor
106
+ ):
107
+ if mask_utils.area(obj.segment) == 0:
108
+ print("Warning, empty mask found, approximating from box")
109
+ obj.segment = torch.zeros(img_h, img_w, dtype=torch.uint8)
110
+ x1, y1, x2, y2 = obj.bbox.int().tolist()
111
+ obj.segment[y1 : max(y2, y1 + 1), x1 : max(x1 + 1, x2)] = 1
112
+ else:
113
+ obj.segment = mask_utils.decode(obj.segment)
114
+ # segment is uint8 and remains uint8 throughout the transforms
115
+ obj.segment = torch.tensor(obj.segment).to(torch.uint8)
116
+
117
+ if list(obj.segment.shape) != [img_h, img_w]:
118
+ # Should not happen often, but adding for security
119
+ if not warning_shown:
120
+ print(
121
+ f"Warning expected instance segmentation size to be {[img_h, img_w]} but found {list(obj.segment.shape)}"
122
+ )
123
+ # Printing only once per datapoint to avoid spam
124
+ warning_shown = True
125
+
126
+ obj.segment = F.resize(
127
+ obj.segment[None], (img_h, img_w)
128
+ ).squeeze(0)
129
+
130
+ assert list(obj.segment.shape) == [img_h, img_w]
131
+
132
+ warning_shown = False
133
+ for query in datapoint.find_queries:
134
+ if query.semantic_target is not None and not isinstance(
135
+ query.semantic_target, torch.Tensor
136
+ ):
137
+ query.semantic_target = mask_utils.decode(query.semantic_target)
138
+ # segment is uint8 and remains uint8 throughout the transforms
139
+ query.semantic_target = torch.tensor(query.semantic_target).to(
140
+ torch.uint8
141
+ )
142
+ if tuple(query.semantic_target.shape) != imgId2size[query.image_id]:
143
+ if not warning_shown:
144
+ print(
145
+ f"Warning expected semantic segmentation size to be {imgId2size[query.image_id]} but found {tuple(query.semantic_target.shape)}"
146
+ )
147
+ # Printing only once per datapoint to avoid spam
148
+ warning_shown = True
149
+
150
+ query.semantic_target = F.resize(
151
+ query.semantic_target[None], imgId2size[query.image_id]
152
+ ).squeeze(0)
153
+
154
+ assert tuple(query.semantic_target.shape) == imgId2size[query.image_id]
155
+
156
+ return datapoint
OVOW/third_party/sam3/sam3/train/utils/__init__.py ADDED
@@ -0,0 +1,3 @@
 
 
 
 
1
+ # Copyright (c) Meta Platforms, Inc. and affiliates. All Rights Reserved
2
+
3
+ # pyre-unsafe
OVOW/third_party/sam3/sam3/train/utils/checkpoint_utils.py ADDED
@@ -0,0 +1,360 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ # Copyright (c) Meta Platforms, Inc. and affiliates. All Rights Reserved
2
+
3
+ # pyre-unsafe
4
+
5
+
6
+ import contextlib
7
+ import fnmatch
8
+ import logging
9
+ from typing import (
10
+ Any,
11
+ Callable,
12
+ Dict,
13
+ List,
14
+ Mapping,
15
+ Optional,
16
+ Sequence,
17
+ Set,
18
+ Tuple,
19
+ Union,
20
+ )
21
+
22
+ import numpy as np
23
+ import torch
24
+ import torch.nn as nn
25
+ from iopath.common.file_io import g_pathmgr
26
+ from torch.jit._script import RecursiveScriptModule
27
+
28
+
29
+ def unix_pattern_to_parameter_names(
30
+ constraints: List[str], all_parameter_names: Sequence[str]
31
+ ) -> Union[None, Set[str]]:
32
+ """
33
+ Go through the list of parameter names and select those that match
34
+ any of the provided constraints
35
+ """
36
+ parameter_names = []
37
+ for param_name in constraints:
38
+ matching_parameters = set(fnmatch.filter(all_parameter_names, param_name))
39
+ assert len(matching_parameters) > 0, (
40
+ f"param_names {param_name} don't match any param in the given names."
41
+ )
42
+ parameter_names.append(matching_parameters)
43
+ return set.union(*parameter_names)
44
+
45
+
46
+ def filter_params_matching_unix_pattern(
47
+ patterns: List[str], state_dict: Dict[str, torch.Tensor]
48
+ ) -> Dict[str, torch.Tensor]:
49
+ """
50
+ Remove from the state dictionary the parameters matching the provided unix patterns
51
+
52
+ Args:
53
+ patterns: the list of unix patterns to exclude
54
+ state_dict: the dictionary to filter
55
+
56
+ Returns:
57
+ A new state dictionary
58
+ """
59
+ if len(patterns) == 0:
60
+ return {}
61
+
62
+ all_keys = list(state_dict.keys())
63
+ included_keys = unix_pattern_to_parameter_names(patterns, all_keys)
64
+ return {k: state_dict[k] for k in included_keys}
65
+
66
+
67
+ def exclude_params_matching_unix_pattern(
68
+ patterns: List[str], state_dict: Dict[str, torch.Tensor]
69
+ ) -> Dict[str, torch.Tensor]:
70
+ """
71
+ Remove from the state dictionary the parameters matching the provided unix patterns
72
+
73
+ Args:
74
+ patterns: the list of unix patterns to exclude
75
+ state_dict: the dictionary to filter
76
+
77
+ Returns:
78
+ A new state dictionary
79
+ """
80
+ if len(patterns) == 0:
81
+ return state_dict
82
+
83
+ all_keys = list(state_dict.keys())
84
+ excluded_keys = unix_pattern_to_parameter_names(patterns, all_keys)
85
+ return {k: v for k, v in state_dict.items() if k not in excluded_keys}
86
+
87
+
88
+ def _get_state_dict_summary(state_dict: Dict[str, torch.Tensor]):
89
+ keys = []
90
+ trace = []
91
+ for k, v in state_dict.items():
92
+ keys.append(k)
93
+ trace.append(v.sum().item())
94
+ trace = np.array(trace)[np.argsort(keys)]
95
+ return trace
96
+
97
+
98
+ def assert_skipped_parameters_are_frozen(model: nn.Module, patterns: List[str]):
99
+ """
100
+ Verifies that all the parameters matching the provided patterns
101
+ are frozen - this acts as a safeguard when ignoring parameter
102
+ when saving checkpoints - if the parameters are in fact trainable
103
+ """
104
+ if not patterns:
105
+ return
106
+
107
+ frozen_state_dict = filter_params_matching_unix_pattern(
108
+ patterns=patterns, state_dict=model.state_dict()
109
+ )
110
+ non_frozen_keys = {
111
+ n
112
+ for n, p in model.named_parameters()
113
+ if n in frozen_state_dict and p.requires_grad
114
+ }
115
+ if non_frozen_keys:
116
+ raise ValueError(
117
+ f"Parameters excluded with `skip_saving_parameters` should be frozen: {non_frozen_keys}"
118
+ )
119
+
120
+
121
+ @contextlib.contextmanager
122
+ def with_check_parameter_frozen(
123
+ model: nn.Module, patterns: List[str], disabled: bool = True
124
+ ):
125
+ """
126
+ Context manager that inspects a model surrounding a piece of code
127
+ and verifies if the model has been updated by this piece of code
128
+
129
+ The function will raise an exception if the model has been updated
130
+ on at least one of the parameter that matches one of the pattern
131
+
132
+ Args:
133
+ model: the model that might have been updated
134
+ patterns: for the parameters we want to observe
135
+ allowed:
136
+ """
137
+ if not patterns or disabled:
138
+ yield
139
+ return
140
+
141
+ frozen_state_dict = filter_params_matching_unix_pattern(
142
+ patterns=patterns, state_dict=model.state_dict()
143
+ )
144
+ summary_before = _get_state_dict_summary(frozen_state_dict)
145
+
146
+ yield
147
+
148
+ frozen_state_dict = filter_params_matching_unix_pattern(
149
+ patterns=patterns, state_dict=model.state_dict()
150
+ )
151
+ summary_after = _get_state_dict_summary(frozen_state_dict)
152
+
153
+ if not np.allclose(summary_before, summary_after, atol=1e-6):
154
+ raise ValueError(
155
+ f"""
156
+ The `model_weight_initializer` has initialized parameters frozen with `skip_saving_parameters`.
157
+ You can resolve this error by either initializing those parameters from within the model definition
158
+ or using the flag `trainer.checkpoint.initialize_after_preemption` to True.
159
+ """
160
+ )
161
+
162
+
163
+ class CkptExcludeKernel:
164
+ """
165
+ Removes the keys from the given model state_dict that match the key_pattern.
166
+
167
+ Args:
168
+ key_pattern: Patterns used to select the keys in the state_dict
169
+ that are eligible for this kernel.
170
+ """
171
+
172
+ def __init__(self, key_pattern: List[str]):
173
+ self.key_pattern = key_pattern
174
+
175
+ def __call__(self, state_dict: Dict):
176
+ """
177
+ Args:
178
+ state_dict: A dictionary representing the given checkpoint's state dict.
179
+ """
180
+ if len(self.key_pattern) == 0:
181
+ return state_dict
182
+ exclude_keys = unix_pattern_to_parameter_names(
183
+ self.key_pattern, state_dict.keys()
184
+ )
185
+ return {k: v for k, v in state_dict.items() if k not in exclude_keys}
186
+
187
+
188
+ def load_checkpoint(
189
+ path_list: List[str],
190
+ pick_recursive_keys: Optional[List[str]] = None,
191
+ map_location: str = "cpu",
192
+ ) -> Any:
193
+ """
194
+ Loads a checkpoint from the specified path.
195
+
196
+ Args:
197
+ path_list: A list of paths which contain the checkpoint. Each element
198
+ is tried (in order) until a file that exists is found. That file is then
199
+ used to read the checkpoint.
200
+ pick_recursive_keys: Picks sub dicts from the loaded checkpoint if not None.
201
+ For pick_recursive_keys = ["a", "b"], will return checkpoint_dict["a"]["b"]
202
+ map_location (str): a function, torch.device, string or a dict specifying how to
203
+ remap storage locations
204
+
205
+ Returns: Model with the matchin pre-trained weights loaded.
206
+ """
207
+ path_exists = False
208
+ for path in path_list:
209
+ if g_pathmgr.exists(path):
210
+ path_exists = True
211
+ break
212
+
213
+ if not path_exists:
214
+ raise ValueError(f"No path exists in {path_list}")
215
+
216
+ with g_pathmgr.open(path, "rb") as f:
217
+ checkpoint = torch.load(f, map_location=map_location)
218
+
219
+ logging.info(f"Loaded checkpoint from {path}")
220
+ if pick_recursive_keys is not None:
221
+ for key in pick_recursive_keys:
222
+ checkpoint = checkpoint[key]
223
+ return checkpoint
224
+
225
+
226
+ def get_state_dict(checkpoint, ckpt_state_dict_keys):
227
+ if isinstance(checkpoint, RecursiveScriptModule):
228
+ # This is a torchscript JIT model
229
+ return checkpoint.state_dict()
230
+ pre_train_dict = checkpoint
231
+ for i, key in enumerate(ckpt_state_dict_keys):
232
+ if (isinstance(pre_train_dict, Mapping) and key not in pre_train_dict) or (
233
+ isinstance(pre_train_dict, Sequence) and key >= len(pre_train_dict)
234
+ ):
235
+ key_str = (
236
+ '["' + '"]["'.join(list(map(ckpt_state_dict_keys[:i], str))) + '"]'
237
+ )
238
+ raise KeyError(
239
+ f"'{key}' not found in checkpoint{key_str} "
240
+ f"with keys: {pre_train_dict.keys()}"
241
+ )
242
+ pre_train_dict = pre_train_dict[key]
243
+ return pre_train_dict
244
+
245
+
246
+ def load_checkpoint_and_apply_kernels(
247
+ checkpoint_path: str,
248
+ checkpoint_kernels: List[Callable] = None,
249
+ ckpt_state_dict_keys: Tuple[str] = ("state_dict",),
250
+ map_location: str = "cpu",
251
+ ) -> nn.Module:
252
+ """
253
+ Performs checkpoint loading with a variety of pre-processing kernel applied in
254
+ sequence.
255
+
256
+ Args:
257
+ checkpoint_path (str): Path to the checkpoint.
258
+ checkpoint_kernels List(Callable): A list of checkpoint processing kernels
259
+ to apply in the specified order. Supported kernels include `CkptIncludeKernel`,
260
+ `CkptExcludeKernel`, etc. These kernels are applied in the
261
+ given order.
262
+ ckpt_state_dict_keys (str): Keys containing the model state dict.
263
+ map_location (str): a function, torch.device, string or a dict specifying how to
264
+ remap storage locations
265
+
266
+ Returns: Model with the matchin pre-trained weights loaded.
267
+ """
268
+ assert g_pathmgr.exists(checkpoint_path), "Checkpoint '{}' not found".format(
269
+ checkpoint_path
270
+ )
271
+
272
+ # Load the checkpoint on CPU to avoid GPU mem spike.
273
+ with g_pathmgr.open(checkpoint_path, "rb") as f:
274
+ checkpoint = torch.load(f, map_location=map_location)
275
+
276
+ pre_train_dict = get_state_dict(checkpoint, ckpt_state_dict_keys)
277
+
278
+ # Not logging into info etc since it's a huge log
279
+ logging.debug(
280
+ "Loaded Checkpoint State Dict pre-kernel application: %s"
281
+ % str(", ".join(list(pre_train_dict.keys())))
282
+ )
283
+ # Apply kernels
284
+ if checkpoint_kernels is not None:
285
+ for f in checkpoint_kernels:
286
+ pre_train_dict = f(state_dict=pre_train_dict)
287
+
288
+ logging.debug(
289
+ "Loaded Checkpoint State Dict Post-kernel application %s"
290
+ % str(", ".join(list(pre_train_dict.keys())))
291
+ )
292
+
293
+ return pre_train_dict
294
+
295
+
296
+ def check_load_state_dict_errors(
297
+ missing_keys,
298
+ unexpected_keys,
299
+ strict: bool,
300
+ ignore_missing_keys: List[str] = None,
301
+ ignore_unexpected_keys: List[str] = None,
302
+ ):
303
+ if ignore_missing_keys is not None and len(ignore_missing_keys) > 0:
304
+ ignored_keys = unix_pattern_to_parameter_names(
305
+ ignore_missing_keys, missing_keys
306
+ )
307
+ missing_keys = [key for key in missing_keys if key not in ignored_keys]
308
+
309
+ if ignore_unexpected_keys is not None and len(ignore_unexpected_keys) > 0:
310
+ ignored_unexpected_keys = unix_pattern_to_parameter_names(
311
+ ignore_unexpected_keys, unexpected_keys
312
+ )
313
+ unexpected_keys = [
314
+ key for key in unexpected_keys if key not in ignored_unexpected_keys
315
+ ]
316
+
317
+ err = "State key mismatch."
318
+ if unexpected_keys:
319
+ err += f" Unexpected keys: {unexpected_keys}."
320
+ if missing_keys:
321
+ err += f" Missing keys: {missing_keys}."
322
+
323
+ if unexpected_keys or missing_keys:
324
+ logging.warning(err)
325
+ if unexpected_keys or strict:
326
+ raise KeyError(err)
327
+
328
+
329
+ def load_state_dict_into_model(
330
+ state_dict: Dict,
331
+ model: nn.Module,
332
+ strict: bool = True,
333
+ ignore_missing_keys: List[str] = None,
334
+ ignore_unexpected_keys: List[str] = None,
335
+ checkpoint_kernels: List[Callable] = None,
336
+ ):
337
+ """
338
+ Loads a state dict into the given model.
339
+
340
+ Args:
341
+ state_dict: A dictionary containing the model's
342
+ state dict, or a subset if strict is False
343
+ model: Model to load the checkpoint weights into
344
+ strict: raise if the state_dict has missing state keys
345
+ ignore_missing_keys: unix pattern of keys to ignore
346
+ """
347
+ # Apply kernels
348
+ if checkpoint_kernels is not None:
349
+ for f in checkpoint_kernels:
350
+ state_dict = f(state_dict=state_dict)
351
+ missing_keys, unexpected_keys = model.load_state_dict(state_dict, strict=False)
352
+
353
+ check_load_state_dict_errors(
354
+ missing_keys,
355
+ unexpected_keys,
356
+ strict=strict,
357
+ ignore_missing_keys=ignore_missing_keys,
358
+ ignore_unexpected_keys=ignore_unexpected_keys,
359
+ )
360
+ return model
OVOW/third_party/sam3/sam3/train/utils/distributed.py ADDED
@@ -0,0 +1,587 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ # Copyright (c) Meta Platforms, Inc. and affiliates. All Rights Reserved
2
+
3
+ # pyre-unsafe
4
+
5
+ # Copyright (c) Meta Platforms, Inc. and affiliates.
6
+ # All rights reserved.
7
+
8
+ # This source code is licensed under the license found in the
9
+ # LICENSE file in the root directory of this source tree.
10
+
11
+ import datetime
12
+ import functools
13
+ import io
14
+ import logging
15
+ import os
16
+ import random
17
+ import tempfile
18
+ import time
19
+ from typing import Any, Callable, List, Tuple
20
+
21
+ import torch
22
+ import torch.autograd as autograd
23
+ import torch.distributed as dist
24
+
25
+
26
+ # Default to GPU 0
27
+ _cuda_device_index: int = 0
28
+
29
+ # Setting _cuda_device_index to -1 internally implies that we should use CPU
30
+ _CPU_DEVICE_INDEX = -1
31
+ _PRIMARY_RANK = 0
32
+
33
+
34
+ @functools.lru_cache()
35
+ def _get_global_gloo_group():
36
+ """
37
+ Return a process group based on gloo backend, containing all the ranks
38
+ The result is cached.
39
+ """
40
+
41
+ if dist.get_backend() == "nccl":
42
+ # Increase timeout from 1800 sec to 43200 sec (12 hr) to avoid some processes
43
+ # being much slower than others causing a timeout (which can happen in relation
44
+ # or LVIS class mAP evaluation).
45
+ timeout = 43200
46
+ return dist.new_group(
47
+ backend="gloo",
48
+ timeout=datetime.timedelta(seconds=timeout),
49
+ )
50
+
51
+ return dist.group.WORLD
52
+
53
+
54
+ def is_main_process():
55
+ """Return true if the current process is the main one"""
56
+ return get_rank() == 0
57
+
58
+
59
+ def all_gather_via_filesys(data, filesys_save_dir=None, gather_to_rank_0_only=False):
60
+ """
61
+ Run all_gather on arbitrary picklable data (not necessarily tensors), similar to
62
+ `all_gather` above, but using filesystem instead of collective ops.
63
+
64
+ If gather_to_rank_0_only is True, only rank 0 will load the gathered object list
65
+ (and other ranks will have an empty list).
66
+ """
67
+ world_size = get_world_size()
68
+ if world_size == 1:
69
+ return [data]
70
+
71
+ print("gathering via files")
72
+ cpu_group = _get_global_gloo_group()
73
+
74
+ # if unspecified, we will save to the current python file dir
75
+ if filesys_save_dir is not None:
76
+ save_dir = filesys_save_dir
77
+ elif "EXP_DIR" in os.environ:
78
+ save_dir = os.environ["EXP_DIR"]
79
+ else:
80
+ # try the same directory where the code is stored
81
+ save_dir = filesys_save_dir or os.path.dirname(__file__)
82
+ save_dir = os.path.join(save_dir, "all_gather_via_filesys")
83
+ if is_main_process():
84
+ os.makedirs(save_dir, exist_ok=True)
85
+
86
+ # use a timestamp and salt to distinguish different all_gather
87
+ timestamp = int(time.time()) if is_main_process() else 0
88
+ salt = random.randint(0, 2**31 - 1) if is_main_process() else 0
89
+ # broadcast the timestamp and salt across ranks
90
+ # (all-reduce will do the broadcasting since only rank 0 is non-zero)
91
+ timestamp_and_salt = torch.tensor([timestamp, salt], dtype=torch.long)
92
+ dist.all_reduce(timestamp_and_salt, group=cpu_group)
93
+ timestamp, salt = timestamp_and_salt.tolist()
94
+
95
+ # save the data to a file on the disk
96
+ rank_save = get_rank()
97
+ save_data_filename = f"data_to_gather_{timestamp}_{salt}_{rank_save}.pkl"
98
+ save_data_path = os.path.join(save_dir, save_data_filename)
99
+ assert not os.path.exists(save_data_path), f"{save_data_path} already exists"
100
+ torch.save(data, save_data_path)
101
+ dist.barrier(group=cpu_group)
102
+
103
+ # read the data from the files
104
+ data_list = []
105
+ if rank_save == 0 or not gather_to_rank_0_only:
106
+ for rank_load in range(world_size):
107
+ load_data_filename = f"data_to_gather_{timestamp}_{salt}_{rank_load}.pkl"
108
+ load_data_path = os.path.join(save_dir, load_data_filename)
109
+ assert os.path.exists(load_data_path), f"cannot read {save_data_path}"
110
+ data_list.append(torch.load(load_data_path, weights_only=False))
111
+ dist.barrier(group=cpu_group)
112
+
113
+ # delete the saved file
114
+ os.remove(save_data_path)
115
+ return data_list
116
+
117
+
118
+ def all_gather(data, force_cpu=False, force_filesys=False, filesys_save_dir=None):
119
+ """
120
+ Run all_gather on arbitrary picklable data (not necessarily tensors)
121
+ Args:
122
+ data: any picklable object
123
+ Returns:
124
+ list[data]: list of data gathered from each rank
125
+ """
126
+
127
+ world_size = get_world_size()
128
+ if world_size == 1:
129
+ return [data]
130
+
131
+ if os.getenv("MDETR_FILESYS_REDUCE_RANK_0_ONLY") == "1":
132
+ return all_gather_via_filesys(
133
+ data, filesys_save_dir, gather_to_rank_0_only=True
134
+ )
135
+
136
+ if os.getenv("MDETR_FILESYS_REDUCE") == "1" or force_filesys:
137
+ return all_gather_via_filesys(data, filesys_save_dir)
138
+
139
+ cpu_group = None
140
+ if os.getenv("MDETR_CPU_REDUCE") == "1" or force_cpu:
141
+ cpu_group = _get_global_gloo_group()
142
+
143
+ buffer = io.BytesIO()
144
+ torch.save(data, buffer)
145
+ data_view = buffer.getbuffer()
146
+ device = "cuda" if cpu_group is None else "cpu"
147
+ tensor = torch.ByteTensor(data_view).to(device)
148
+
149
+ # obtain Tensor size of each rank
150
+ local_size = torch.tensor([tensor.numel()], device=device, dtype=torch.long)
151
+ size_list = [
152
+ torch.tensor([0], device=device, dtype=torch.long) for _ in range(world_size)
153
+ ]
154
+ if cpu_group is None:
155
+ dist.all_gather(size_list, local_size)
156
+ else:
157
+ print("gathering on cpu")
158
+ dist.all_gather(size_list, local_size, group=cpu_group)
159
+ size_list = [int(size.item()) for size in size_list]
160
+ max_size = max(size_list)
161
+ assert isinstance(local_size.item(), int)
162
+ local_size = int(local_size.item())
163
+
164
+ # receiving Tensor from all ranks
165
+ # we pad the tensor because torch all_gather does not support
166
+ # gathering tensors of different shapes
167
+ tensor_list = []
168
+ for _ in size_list:
169
+ tensor_list.append(torch.empty((max_size,), dtype=torch.uint8, device=device))
170
+ if local_size != max_size:
171
+ padding = torch.empty(
172
+ size=(max_size - local_size,), dtype=torch.uint8, device=device
173
+ )
174
+ tensor = torch.cat((tensor, padding), dim=0)
175
+ if cpu_group is None:
176
+ dist.all_gather(tensor_list, tensor)
177
+ else:
178
+ dist.all_gather(tensor_list, tensor, group=cpu_group)
179
+
180
+ data_list = []
181
+ for size, tensor in zip(size_list, tensor_list):
182
+ tensor = torch.split(tensor, [size, max_size - size], dim=0)[0]
183
+ buffer = io.BytesIO(tensor.cpu().numpy())
184
+ obj = torch.load(buffer, weights_only=False)
185
+ data_list.append(obj)
186
+
187
+ return data_list
188
+
189
+
190
+ def convert_to_distributed_tensor(tensor: torch.Tensor) -> Tuple[torch.Tensor, str]:
191
+ """
192
+ For some backends, such as NCCL, communication only works if the
193
+ tensor is on the GPU. This helper function converts to the correct
194
+ device and returns the tensor + original device.
195
+ """
196
+ orig_device = "cpu" if not tensor.is_cuda else "gpu"
197
+ if (
198
+ torch.distributed.is_available()
199
+ and torch.distributed.get_backend() == torch.distributed.Backend.NCCL
200
+ and not tensor.is_cuda
201
+ ):
202
+ tensor = tensor.cuda()
203
+ return (tensor, orig_device)
204
+
205
+
206
+ def convert_to_normal_tensor(tensor: torch.Tensor, orig_device: str) -> torch.Tensor:
207
+ """
208
+ For some backends, such as NCCL, communication only works if the
209
+ tensor is on the GPU. This converts the tensor back to original device.
210
+ """
211
+ if tensor.is_cuda and orig_device == "cpu":
212
+ tensor = tensor.cpu()
213
+ return tensor
214
+
215
+
216
+ def is_distributed_training_run() -> bool:
217
+ return (
218
+ torch.distributed.is_available()
219
+ and torch.distributed.is_initialized()
220
+ and (torch.distributed.get_world_size() > 1)
221
+ )
222
+
223
+
224
+ def is_primary() -> bool:
225
+ """
226
+ Returns True if this is rank 0 of a distributed training job OR if it is
227
+ a single trainer job. Otherwise False.
228
+ """
229
+ return get_rank() == _PRIMARY_RANK
230
+
231
+
232
+ def all_reduce_mean(tensor: torch.Tensor) -> torch.Tensor:
233
+ """
234
+ Wrapper over torch.distributed.all_reduce for performing mean reduction
235
+ of tensor over all processes.
236
+ """
237
+ return all_reduce_op(
238
+ tensor,
239
+ torch.distributed.ReduceOp.SUM,
240
+ lambda t: t / torch.distributed.get_world_size(),
241
+ )
242
+
243
+
244
+ def all_reduce_sum(tensor: torch.Tensor) -> torch.Tensor:
245
+ """
246
+ Wrapper over torch.distributed.all_reduce for performing sum
247
+ reduction of tensor over all processes in both distributed /
248
+ non-distributed scenarios.
249
+ """
250
+ return all_reduce_op(tensor, torch.distributed.ReduceOp.SUM)
251
+
252
+
253
+ def all_reduce_min(tensor: torch.Tensor) -> torch.Tensor:
254
+ """
255
+ Wrapper over torch.distributed.all_reduce for performing min
256
+ reduction of tensor over all processes in both distributed /
257
+ non-distributed scenarios.
258
+ """
259
+ return all_reduce_op(tensor, torch.distributed.ReduceOp.MIN)
260
+
261
+
262
+ def all_reduce_max(tensor: torch.Tensor) -> torch.Tensor:
263
+ """
264
+ Wrapper over torch.distributed.all_reduce for performing min
265
+ reduction of tensor over all processes in both distributed /
266
+ non-distributed scenarios.
267
+ """
268
+ return all_reduce_op(tensor, torch.distributed.ReduceOp.MAX)
269
+
270
+
271
+ def all_reduce_op(
272
+ tensor: torch.Tensor,
273
+ op: torch.distributed.ReduceOp,
274
+ after_op_func: Callable[[torch.Tensor], torch.Tensor] = None,
275
+ ) -> torch.Tensor:
276
+ """
277
+ Wrapper over torch.distributed.all_reduce for performing
278
+ reduction of tensor over all processes in both distributed /
279
+ non-distributed scenarios.
280
+ """
281
+ if is_distributed_training_run():
282
+ tensor, orig_device = convert_to_distributed_tensor(tensor)
283
+ torch.distributed.all_reduce(tensor, op)
284
+ if after_op_func is not None:
285
+ tensor = after_op_func(tensor)
286
+ tensor = convert_to_normal_tensor(tensor, orig_device)
287
+ return tensor
288
+
289
+
290
+ def gather_tensors_from_all(tensor: torch.Tensor) -> List[torch.Tensor]:
291
+ """
292
+ Wrapper over torch.distributed.all_gather for performing
293
+ 'gather' of 'tensor' over all processes in both distributed /
294
+ non-distributed scenarios.
295
+ """
296
+ if tensor.ndim == 0:
297
+ # 0 dim tensors cannot be gathered. so unsqueeze
298
+ tensor = tensor.unsqueeze(0)
299
+
300
+ if is_distributed_training_run():
301
+ tensor, orig_device = convert_to_distributed_tensor(tensor)
302
+ gathered_tensors = [
303
+ torch.zeros_like(tensor) for _ in range(torch.distributed.get_world_size())
304
+ ]
305
+ torch.distributed.all_gather(gathered_tensors, tensor)
306
+ gathered_tensors = [
307
+ convert_to_normal_tensor(_tensor, orig_device)
308
+ for _tensor in gathered_tensors
309
+ ]
310
+ else:
311
+ gathered_tensors = [tensor]
312
+
313
+ return gathered_tensors
314
+
315
+
316
+ def gather_from_all(tensor: torch.Tensor) -> torch.Tensor:
317
+ gathered_tensors = gather_tensors_from_all(tensor)
318
+ gathered_tensor = torch.cat(gathered_tensors, 0)
319
+ return gathered_tensor
320
+
321
+
322
+ def broadcast(tensor: torch.Tensor, src: int = 0) -> torch.Tensor:
323
+ """
324
+ Wrapper over torch.distributed.broadcast for broadcasting a tensor from the source
325
+ to all processes in both distributed / non-distributed scenarios.
326
+ """
327
+ if is_distributed_training_run():
328
+ tensor, orig_device = convert_to_distributed_tensor(tensor)
329
+ torch.distributed.broadcast(tensor, src)
330
+ tensor = convert_to_normal_tensor(tensor, orig_device)
331
+ return tensor
332
+
333
+
334
+ def barrier() -> None:
335
+ """
336
+ Wrapper over torch.distributed.barrier, returns without waiting
337
+ if the distributed process group is not initialized instead of throwing error.
338
+ """
339
+ if not torch.distributed.is_available() or not torch.distributed.is_initialized():
340
+ return
341
+ torch.distributed.barrier()
342
+
343
+
344
+ def get_world_size() -> int:
345
+ """
346
+ Simple wrapper for correctly getting worldsize in both distributed
347
+ / non-distributed settings
348
+ """
349
+ return (
350
+ torch.distributed.get_world_size()
351
+ if torch.distributed.is_available() and torch.distributed.is_initialized()
352
+ else 1
353
+ )
354
+
355
+
356
+ def get_rank() -> int:
357
+ """
358
+ Simple wrapper for correctly getting rank in both distributed
359
+ / non-distributed settings
360
+ """
361
+ return (
362
+ torch.distributed.get_rank()
363
+ if torch.distributed.is_available() and torch.distributed.is_initialized()
364
+ else 0
365
+ )
366
+
367
+
368
+ def get_primary_rank() -> int:
369
+ return _PRIMARY_RANK
370
+
371
+
372
+ def set_cuda_device_index(idx: int) -> None:
373
+ global _cuda_device_index
374
+ _cuda_device_index = idx
375
+ torch.cuda.set_device(_cuda_device_index)
376
+
377
+
378
+ def set_cpu_device() -> None:
379
+ global _cuda_device_index
380
+ _cuda_device_index = _CPU_DEVICE_INDEX
381
+
382
+
383
+ def get_cuda_device_index() -> int:
384
+ return _cuda_device_index
385
+
386
+
387
+ def init_distributed_data_parallel_model(
388
+ model: torch.nn.Module,
389
+ broadcast_buffers: bool = False,
390
+ find_unused_parameters: bool = True,
391
+ bucket_cap_mb: int = 25,
392
+ ) -> torch.nn.parallel.DistributedDataParallel:
393
+ global _cuda_device_index
394
+
395
+ if _cuda_device_index == _CPU_DEVICE_INDEX:
396
+ # CPU-only model, don't specify device
397
+ return torch.nn.parallel.DistributedDataParallel(
398
+ model,
399
+ broadcast_buffers=broadcast_buffers,
400
+ find_unused_parameters=find_unused_parameters,
401
+ bucket_cap_mb=bucket_cap_mb,
402
+ )
403
+ else:
404
+ # GPU model
405
+ return torch.nn.parallel.DistributedDataParallel(
406
+ model,
407
+ device_ids=[_cuda_device_index],
408
+ output_device=_cuda_device_index,
409
+ broadcast_buffers=broadcast_buffers,
410
+ find_unused_parameters=find_unused_parameters,
411
+ bucket_cap_mb=bucket_cap_mb,
412
+ )
413
+
414
+
415
+ def broadcast_object(obj: Any, src: int = _PRIMARY_RANK, use_disk: bool = True) -> Any:
416
+ """Broadcast an object from a source to all workers.
417
+
418
+ Args:
419
+ obj: Object to broadcast, must be serializable
420
+ src: Source rank for broadcast (default is primary)
421
+ use_disk: If enabled, removes redundant CPU memory copies by writing to
422
+ disk
423
+ """
424
+ # Either broadcast from primary to the fleet (default),
425
+ # or use the src setting as the original rank
426
+ if get_rank() == src:
427
+ # Emit data
428
+ buffer = io.BytesIO()
429
+ torch.save(obj, buffer)
430
+ data_view = buffer.getbuffer()
431
+ length_tensor = torch.LongTensor([len(data_view)])
432
+ length_tensor = broadcast(length_tensor, src=src)
433
+ data_tensor = torch.ByteTensor(data_view)
434
+ data_tensor = broadcast(data_tensor, src=src)
435
+ else:
436
+ # Fetch from the source
437
+ length_tensor = torch.LongTensor([0])
438
+ length_tensor = broadcast(length_tensor, src=src)
439
+ data_tensor = torch.empty([length_tensor.item()], dtype=torch.uint8)
440
+ data_tensor = broadcast(data_tensor, src=src)
441
+ if use_disk:
442
+ with tempfile.TemporaryFile("r+b") as f:
443
+ f.write(data_tensor.numpy())
444
+ # remove reference to the data tensor and hope that Python garbage
445
+ # collects it
446
+ del data_tensor
447
+ f.seek(0)
448
+ obj = torch.load(f, weights_only=False)
449
+ else:
450
+ buffer = io.BytesIO(data_tensor.numpy())
451
+ obj = torch.load(buffer, weights_only=False)
452
+ return obj
453
+
454
+
455
+ def all_gather_tensor(tensor: torch.Tensor, world_size=None):
456
+ if world_size is None:
457
+ world_size = get_world_size()
458
+ # make contiguous because NCCL won't gather the tensor otherwise
459
+ assert tensor.is_contiguous(), f"{tensor.shape} is not contiguous!"
460
+ tensor, orig_device = convert_to_distributed_tensor(tensor)
461
+ tensor_all = [torch.ones_like(tensor) for _ in range(world_size)]
462
+ dist.all_gather(tensor_all, tensor, async_op=False) # performance opt
463
+ tensor_all = [
464
+ convert_to_normal_tensor(tensor, orig_device) for tensor in tensor_all
465
+ ]
466
+ return tensor_all
467
+
468
+
469
+ def all_gather_batch(tensors: List[torch.Tensor]):
470
+ """
471
+ Performs all_gather operation on the provided tensors.
472
+ """
473
+ # Queue the gathered tensors
474
+ world_size = get_world_size()
475
+ # There is no need for reduction in the single-proc case
476
+ if world_size == 1:
477
+ return tensors
478
+ tensor_list = []
479
+ output_tensor = []
480
+ for tensor in tensors:
481
+ tensor_all = all_gather_tensor(tensor, world_size)
482
+ tensor_list.append(tensor_all)
483
+
484
+ for tensor_all in tensor_list:
485
+ output_tensor.append(torch.cat(tensor_all, dim=0))
486
+ return output_tensor
487
+
488
+
489
+ class GatherLayer(autograd.Function):
490
+ """
491
+ Gather tensors from all workers with support for backward propagation:
492
+ This implementation does not cut the gradients as torch.distributed.all_gather does.
493
+ """
494
+
495
+ @staticmethod
496
+ def forward(ctx, x):
497
+ output = [torch.zeros_like(x) for _ in range(dist.get_world_size())]
498
+ dist.all_gather(output, x)
499
+ return tuple(output)
500
+
501
+ @staticmethod
502
+ def backward(ctx, *grads):
503
+ all_gradients = torch.stack(grads)
504
+ dist.all_reduce(all_gradients)
505
+ return all_gradients[dist.get_rank()]
506
+
507
+
508
+ def all_gather_batch_with_grad(tensors):
509
+ """
510
+ Performs all_gather operation on the provided tensors.
511
+ Graph remains connected for backward grad computation.
512
+ """
513
+ # Queue the gathered tensors
514
+ world_size = get_world_size()
515
+ # There is no need for reduction in the single-proc case
516
+ if world_size == 1:
517
+ return tensors
518
+ tensor_list = []
519
+ output_tensor = []
520
+
521
+ for tensor in tensors:
522
+ tensor_all = GatherLayer.apply(tensor)
523
+ tensor_list.append(tensor_all)
524
+
525
+ for tensor_all in tensor_list:
526
+ output_tensor.append(torch.cat(tensor_all, dim=0))
527
+ return output_tensor
528
+
529
+
530
+ def unwrap_ddp_if_wrapped(model):
531
+ if isinstance(model, torch.nn.parallel.DistributedDataParallel):
532
+ return model.module
533
+ return model
534
+
535
+
536
+ def create_new_process_group(group_size):
537
+ """
538
+ Creates process groups of a gives `group_size` and returns
539
+ process group that current GPU participates in.
540
+
541
+ `group_size` must divide the total number of GPUs (world_size).
542
+
543
+ Modified from
544
+ https://github.com/NVIDIA/apex/blob/4e1ae43f7f7ac69113ef426dd15f37123f0a2ed3/apex/parallel/__init__.py#L60
545
+
546
+ Args:
547
+ group_size (int): number of GPU's to collaborate for sync bn
548
+ """
549
+
550
+ assert group_size > 0
551
+
552
+ world_size = torch.distributed.get_world_size()
553
+ if world_size <= 8:
554
+ if group_size > world_size:
555
+ logging.warning(
556
+ f"Requested group size [{group_size}] > world size [{world_size}]. "
557
+ "Assuming local debug run and capping it to world size."
558
+ )
559
+ group_size = world_size
560
+ assert world_size >= group_size
561
+ assert world_size % group_size == 0
562
+
563
+ group = None
564
+ for group_num in range(world_size // group_size):
565
+ group_ids = range(group_num * group_size, (group_num + 1) * group_size)
566
+ cur_group = torch.distributed.new_group(ranks=group_ids)
567
+ if torch.distributed.get_rank() // group_size == group_num:
568
+ group = cur_group
569
+ # can not drop out and return here, every process must go through creation of all subgroups
570
+
571
+ assert group is not None
572
+ return group
573
+
574
+
575
+ def is_dist_avail_and_initialized():
576
+ if not dist.is_available():
577
+ return False
578
+ if not dist.is_initialized():
579
+ return False
580
+ return True
581
+
582
+
583
+ def gather_to_rank_0_via_filesys(data, filesys_save_dir=None):
584
+ """
585
+ Gather any picklable data to rank 0 via filesystem, using all_gather_via_filesys.
586
+ """
587
+ return all_gather_via_filesys(data, filesys_save_dir, gather_to_rank_0_only=True)
OVOW/third_party/sam3/sam3/train/utils/logger.py ADDED
@@ -0,0 +1,241 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ # Copyright (c) Meta Platforms, Inc. and affiliates. All Rights Reserved
2
+
3
+ # pyre-unsafe
4
+
5
+ import atexit
6
+ import functools
7
+ import logging
8
+ import sys
9
+ import uuid
10
+ from typing import Any, Dict, Optional, Union
11
+
12
+ from hydra.utils import instantiate
13
+ from iopath.common.file_io import g_pathmgr
14
+ from numpy import ndarray
15
+ from sam3.train.utils.train_utils import get_machine_local_and_dist_rank, makedir
16
+ from torch import Tensor
17
+ from torch.utils.tensorboard import SummaryWriter
18
+
19
+ Scalar = Union[Tensor, ndarray, int, float]
20
+
21
+
22
+ def make_tensorboard_logger(log_dir: str, **writer_kwargs: Any):
23
+ makedir(log_dir)
24
+ summary_writer_method = SummaryWriter
25
+ return TensorBoardLogger(
26
+ path=log_dir, summary_writer_method=summary_writer_method, **writer_kwargs
27
+ )
28
+
29
+
30
+ class TensorBoardWriterWrapper:
31
+ """
32
+ A wrapper around a SummaryWriter object.
33
+ """
34
+
35
+ def __init__(
36
+ self,
37
+ path: str,
38
+ *args: Any,
39
+ filename_suffix: str = None,
40
+ summary_writer_method: Any = SummaryWriter,
41
+ **kwargs: Any,
42
+ ) -> None:
43
+ """Create a new TensorBoard logger.
44
+ On construction, the logger creates a new events file that logs
45
+ will be written to. If the environment variable `RANK` is defined,
46
+ logger will only log if RANK = 0.
47
+
48
+ NOTE: If using the logger with distributed training:
49
+ - This logger can call collective operations
50
+ - Logs will be written on rank 0 only
51
+ - Logger must be constructed synchronously *after* initializing distributed process group.
52
+
53
+ Args:
54
+ path (str): path to write logs to
55
+ *args, **kwargs: Extra arguments to pass to SummaryWriter
56
+ """
57
+ self._writer: Optional[SummaryWriter] = None
58
+ _, self._rank = get_machine_local_and_dist_rank()
59
+ self._path: str = path
60
+ if self._rank == 0:
61
+ logging.info(
62
+ f"TensorBoard SummaryWriter instantiated. Files will be stored in: {path}"
63
+ )
64
+ self._writer = summary_writer_method(
65
+ log_dir=path,
66
+ *args,
67
+ filename_suffix=filename_suffix or str(uuid.uuid4()),
68
+ **kwargs,
69
+ )
70
+ else:
71
+ logging.debug(
72
+ f"Not logging meters on this host because env RANK: {self._rank} != 0"
73
+ )
74
+ atexit.register(self.close)
75
+
76
+ @property
77
+ def writer(self) -> Optional[SummaryWriter]:
78
+ return self._writer
79
+
80
+ @property
81
+ def path(self) -> str:
82
+ return self._path
83
+
84
+ def flush(self) -> None:
85
+ """Writes pending logs to disk."""
86
+
87
+ if not self._writer:
88
+ return
89
+
90
+ self._writer.flush()
91
+
92
+ def close(self) -> None:
93
+ """Close writer, flushing pending logs to disk.
94
+ Logs cannot be written after `close` is called.
95
+ """
96
+
97
+ if not self._writer:
98
+ return
99
+
100
+ self._writer.close()
101
+ self._writer = None
102
+
103
+
104
+ class TensorBoardLogger(TensorBoardWriterWrapper):
105
+ """
106
+ A simple logger for TensorBoard.
107
+ """
108
+
109
+ def log_dict(self, payload: Dict[str, Scalar], step: int) -> None:
110
+ """Add multiple scalar values to TensorBoard.
111
+
112
+ Args:
113
+ payload (dict): dictionary of tag name and scalar value
114
+ step (int, Optional): step value to record
115
+ """
116
+ if not self._writer:
117
+ return
118
+ for k, v in payload.items():
119
+ self.log(k, v, step)
120
+
121
+ def log(self, name: str, data: Scalar, step: int) -> None:
122
+ """Add scalar data to TensorBoard.
123
+
124
+ Args:
125
+ name (string): tag name used to group scalars
126
+ data (float/int/Tensor): scalar data to log
127
+ step (int, optional): step value to record
128
+ """
129
+ if not self._writer:
130
+ return
131
+ self._writer.add_scalar(name, data, global_step=step, new_style=True)
132
+
133
+ def log_hparams(
134
+ self, hparams: Dict[str, Scalar], meters: Dict[str, Scalar]
135
+ ) -> None:
136
+ """Add hyperparameter data to TensorBoard.
137
+
138
+ Args:
139
+ hparams (dict): dictionary of hyperparameter names and corresponding values
140
+ meters (dict): dictionary of name of meter and corersponding values
141
+ """
142
+ if not self._writer:
143
+ return
144
+ self._writer.add_hparams(hparams, meters)
145
+
146
+
147
+ class Logger:
148
+ """
149
+ A logger class that can interface with multiple loggers. It now supports tensorboard only for simplicity, but you can extend it with your own logger.
150
+ """
151
+
152
+ def __init__(self, logging_conf):
153
+ # allow turning off TensorBoard with "should_log: false" in config
154
+ tb_config = logging_conf.tensorboard_writer
155
+ tb_should_log = tb_config and tb_config.pop("should_log", True)
156
+ self.tb_logger = instantiate(tb_config) if tb_should_log else None
157
+
158
+ def log_dict(self, payload: Dict[str, Scalar], step: int) -> None:
159
+ if self.tb_logger:
160
+ self.tb_logger.log_dict(payload, step)
161
+
162
+ def log(self, name: str, data: Scalar, step: int) -> None:
163
+ if self.tb_logger:
164
+ self.tb_logger.log(name, data, step)
165
+
166
+ def log_hparams(
167
+ self, hparams: Dict[str, Scalar], meters: Dict[str, Scalar]
168
+ ) -> None:
169
+ if self.tb_logger:
170
+ self.tb_logger.log_hparams(hparams, meters)
171
+
172
+
173
+ # cache the opened file object, so that different calls to `setup_logger`
174
+ # with the same file name can safely write to the same file.
175
+ @functools.lru_cache(maxsize=None)
176
+ def _cached_log_stream(filename):
177
+ # we tune the buffering value so that the logs are updated
178
+ # frequently.
179
+ log_buffer_kb = 10 * 1024 # 10KB
180
+ io = g_pathmgr.open(filename, mode="a", buffering=log_buffer_kb)
181
+ atexit.register(io.close)
182
+ return io
183
+
184
+
185
+ def setup_logging(
186
+ name,
187
+ output_dir=None,
188
+ rank=0,
189
+ log_level_primary="INFO",
190
+ log_level_secondary="ERROR",
191
+ ):
192
+ """
193
+ Setup various logging streams: stdout and file handlers.
194
+ For file handlers, we only setup for the master gpu.
195
+ """
196
+ # get the filename if we want to log to the file as well
197
+ log_filename = None
198
+ if output_dir:
199
+ makedir(output_dir)
200
+ if rank == 0:
201
+ log_filename = f"{output_dir}/log.txt"
202
+
203
+ logger = logging.getLogger(name)
204
+ logger.setLevel(log_level_primary)
205
+
206
+ # create formatter
207
+ FORMAT = "%(levelname)s %(asctime)s %(filename)s:%(lineno)4d: %(message)s"
208
+ formatter = logging.Formatter(FORMAT)
209
+
210
+ # Cleanup any existing handlers
211
+ for h in logger.handlers:
212
+ logger.removeHandler(h)
213
+ logger.root.handlers = []
214
+
215
+ # setup the console handler
216
+ console_handler = logging.StreamHandler(sys.stdout)
217
+ console_handler.setFormatter(formatter)
218
+ logger.addHandler(console_handler)
219
+ if rank == 0:
220
+ console_handler.setLevel(log_level_primary)
221
+ else:
222
+ console_handler.setLevel(log_level_secondary)
223
+
224
+ # we log to file as well if user wants
225
+ if log_filename and rank == 0:
226
+ file_handler = logging.StreamHandler(_cached_log_stream(log_filename))
227
+ file_handler.setLevel(log_level_primary)
228
+ file_handler.setFormatter(formatter)
229
+ logger.addHandler(file_handler)
230
+
231
+ logging.root = logger
232
+
233
+
234
+ def shutdown_logging():
235
+ """
236
+ After training is done, we ensure to shut down all the logger streams.
237
+ """
238
+ logging.info("Shutting down loggers...")
239
+ handlers = logging.root.handlers
240
+ for handler in handlers:
241
+ handler.close()
OVOW/third_party/sam3/sam3/train/utils/train_utils.py ADDED
@@ -0,0 +1,286 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ # Copyright (c) Meta Platforms, Inc. and affiliates. All Rights Reserved
2
+
3
+ # pyre-unsafe
4
+
5
+ import logging
6
+ import math
7
+ import os
8
+ import random
9
+ import re
10
+ from datetime import timedelta
11
+ from typing import Optional
12
+
13
+ import hydra
14
+ import numpy as np
15
+ import omegaconf
16
+ import torch
17
+ import torch.distributed as dist
18
+ from iopath.common.file_io import g_pathmgr
19
+ from omegaconf import OmegaConf
20
+
21
+
22
+ def multiply_all(*args):
23
+ return np.prod(np.array(args)).item()
24
+
25
+
26
+ def collect_dict_keys(config):
27
+ """This function recursively iterates through a dataset configuration, and collect all the dict_key that are defined"""
28
+ val_keys = []
29
+ # If the this config points to the collate function, then it has a key
30
+ if "_target_" in config and re.match(r".*collate_fn.*", config["_target_"]):
31
+ val_keys.append(config["dict_key"])
32
+ else:
33
+ # Recursively proceed
34
+ for v in config.values():
35
+ if isinstance(v, type(config)):
36
+ val_keys.extend(collect_dict_keys(v))
37
+ elif isinstance(v, omegaconf.listconfig.ListConfig):
38
+ for item in v:
39
+ if isinstance(item, type(config)):
40
+ val_keys.extend(collect_dict_keys(item))
41
+ return val_keys
42
+
43
+
44
+ class Phase:
45
+ TRAIN = "train"
46
+ VAL = "val"
47
+
48
+
49
+ def register_omegaconf_resolvers():
50
+ OmegaConf.register_new_resolver("get_method", hydra.utils.get_method)
51
+ OmegaConf.register_new_resolver("get_class", hydra.utils.get_class)
52
+ OmegaConf.register_new_resolver("add", lambda x, y: x + y)
53
+ OmegaConf.register_new_resolver("times", multiply_all)
54
+ OmegaConf.register_new_resolver("divide", lambda x, y: x / y)
55
+ OmegaConf.register_new_resolver("pow", lambda x, y: x**y)
56
+ OmegaConf.register_new_resolver("subtract", lambda x, y: x - y)
57
+ OmegaConf.register_new_resolver("range", lambda x: list(range(x)))
58
+ OmegaConf.register_new_resolver("int", lambda x: int(x))
59
+ OmegaConf.register_new_resolver("ceil_int", lambda x: int(math.ceil(x)))
60
+ OmegaConf.register_new_resolver("merge", lambda *x: OmegaConf.merge(*x))
61
+ OmegaConf.register_new_resolver("string", lambda x: str(x))
62
+
63
+
64
+ def setup_distributed_backend(backend, timeout_mins):
65
+ """
66
+ Initialize torch.distributed and set the CUDA device.
67
+ Expects environment variables to be set as per
68
+ https://pytorch.org/docs/stable/distributed.html#environment-variable-initialization
69
+ along with the environ variable "LOCAL_RANK" which is used to set the CUDA device.
70
+ """
71
+ # enable TORCH_NCCL_ASYNC_ERROR_HANDLING to ensure dist nccl ops time out after timeout_mins
72
+ # of waiting
73
+ os.environ["TORCH_NCCL_ASYNC_ERROR_HANDLING"] = "1"
74
+ logging.info(f"Setting up torch.distributed with a timeout of {timeout_mins} mins")
75
+ dist.init_process_group(backend=backend, timeout=timedelta(minutes=timeout_mins))
76
+ return dist.get_rank()
77
+
78
+
79
+ def get_machine_local_and_dist_rank():
80
+ """
81
+ Get the distributed and local rank of the current gpu.
82
+ """
83
+ local_rank = int(os.environ.get("LOCAL_RANK", None))
84
+ distributed_rank = int(os.environ.get("RANK", None))
85
+ assert local_rank is not None and distributed_rank is not None, (
86
+ "Please the set the RANK and LOCAL_RANK environment variables."
87
+ )
88
+ return local_rank, distributed_rank
89
+
90
+
91
+ def print_cfg(cfg):
92
+ """
93
+ Supports printing both Hydra DictConfig and also the AttrDict config
94
+ """
95
+ logging.info("Training with config:")
96
+ logging.info(OmegaConf.to_yaml(cfg))
97
+
98
+
99
+ def set_seeds(seed_value, max_epochs, dist_rank):
100
+ """
101
+ Set the python random, numpy and torch seed for each gpu. Also set the CUDA
102
+ seeds if the CUDA is available. This ensures deterministic nature of the training.
103
+ """
104
+ # Since in the pytorch sampler, we increment the seed by 1 for every epoch.
105
+ seed_value = (seed_value + dist_rank) * max_epochs
106
+ logging.info(f"MACHINE SEED: {seed_value}")
107
+ random.seed(seed_value)
108
+ np.random.seed(seed_value)
109
+ torch.manual_seed(seed_value)
110
+ if torch.cuda.is_available():
111
+ torch.cuda.manual_seed_all(seed_value)
112
+
113
+
114
+ def makedir(dir_path):
115
+ """
116
+ Create the directory if it does not exist.
117
+ """
118
+ is_success = False
119
+ try:
120
+ if not g_pathmgr.exists(dir_path):
121
+ g_pathmgr.mkdirs(dir_path)
122
+ is_success = True
123
+ except BaseException:
124
+ logging.info(f"Error creating directory: {dir_path}")
125
+ return is_success
126
+
127
+
128
+ def is_dist_avail_and_initialized():
129
+ if not dist.is_available():
130
+ return False
131
+ if not dist.is_initialized():
132
+ return False
133
+ return True
134
+
135
+
136
+ def get_amp_type(amp_type: Optional[str] = None):
137
+ if amp_type is None:
138
+ return None
139
+ assert amp_type in ["bfloat16", "float16"], "Invalid Amp type."
140
+ if amp_type == "bfloat16":
141
+ return torch.bfloat16
142
+ else:
143
+ return torch.float16
144
+
145
+
146
+ def log_env_variables():
147
+ env_keys = sorted(list(os.environ.keys()))
148
+ st = ""
149
+ for k in env_keys:
150
+ v = os.environ[k]
151
+ st += f"{k}={v}\n"
152
+ logging.info("Logging ENV_VARIABLES")
153
+ logging.info(st)
154
+
155
+
156
+ class AverageMeter:
157
+ """Computes and stores the average and current value"""
158
+
159
+ def __init__(self, name, device, fmt=":f"):
160
+ self.name = name
161
+ self.fmt = fmt
162
+ self.device = device
163
+ self.reset()
164
+
165
+ def reset(self):
166
+ self.val = 0
167
+ self.avg = 0
168
+ self.sum = 0
169
+ self.count = 0
170
+ self._allow_updates = True
171
+
172
+ def update(self, val, n=1):
173
+ self.val = val
174
+ self.sum += val * n
175
+ self.count += n
176
+ self.avg = self.sum / self.count
177
+
178
+ def __str__(self):
179
+ fmtstr = "{name}: {val" + self.fmt + "} ({avg" + self.fmt + "})"
180
+ return fmtstr.format(**self.__dict__)
181
+
182
+
183
+ class MemMeter:
184
+ """Computes and stores the current, avg, and max of peak Mem usage per iteration"""
185
+
186
+ def __init__(self, name, device, fmt=":f"):
187
+ self.name = name
188
+ self.fmt = fmt
189
+ self.device = device
190
+ self.reset()
191
+
192
+ def reset(self):
193
+ self.val = 0 # Per iteration max usage
194
+ self.avg = 0 # Avg per iteration max usage
195
+ self.peak = 0 # Peak usage for lifetime of program
196
+ self.sum = 0
197
+ self.count = 0
198
+ self._allow_updates = True
199
+
200
+ def update(self, n=1, reset_peak_usage=True):
201
+ self.val = torch.cuda.max_memory_allocated() // 1e9
202
+ self.sum += self.val * n
203
+ self.count += n
204
+ self.avg = self.sum / self.count
205
+ self.peak = max(self.peak, self.val)
206
+ if reset_peak_usage:
207
+ torch.cuda.reset_peak_memory_stats()
208
+
209
+ def __str__(self):
210
+ fmtstr = (
211
+ "{name}: {val"
212
+ + self.fmt
213
+ + "} ({avg"
214
+ + self.fmt
215
+ + "}/{peak"
216
+ + self.fmt
217
+ + "})"
218
+ )
219
+ return fmtstr.format(**self.__dict__)
220
+
221
+
222
+ def human_readable_time(time_seconds):
223
+ time = int(time_seconds)
224
+ minutes, seconds = divmod(time, 60)
225
+ hours, minutes = divmod(minutes, 60)
226
+ days, hours = divmod(hours, 24)
227
+ return f"{days:02}d {hours:02}h {minutes:02}m"
228
+
229
+
230
+ class DurationMeter:
231
+ def __init__(self, name, device, fmt=":f"):
232
+ self.name = name
233
+ self.device = device
234
+ self.fmt = fmt
235
+ self.val = 0
236
+
237
+ def reset(self):
238
+ self.val = 0
239
+
240
+ def update(self, val):
241
+ self.val = val
242
+
243
+ def add(self, val):
244
+ self.val += val
245
+
246
+ def __str__(self):
247
+ return f"{self.name}: {human_readable_time(self.val)}"
248
+
249
+
250
+ class ProgressMeter:
251
+ def __init__(self, num_batches, meters, real_meters, prefix=""):
252
+ self.batch_fmtstr = self._get_batch_fmtstr(num_batches)
253
+ self.meters = meters
254
+ self.real_meters = real_meters
255
+ self.prefix = prefix
256
+
257
+ def display(self, batch, enable_print=False):
258
+ entries = [self.prefix + self.batch_fmtstr.format(batch)]
259
+ entries += [str(meter) for meter in self.meters]
260
+ entries += [
261
+ " | ".join(
262
+ [
263
+ f"{os.path.join(name, subname)}: {val:.4f}"
264
+ for subname, val in meter.compute().items()
265
+ ]
266
+ )
267
+ for name, meter in self.real_meters.items()
268
+ ]
269
+ logging.info(" | ".join(entries))
270
+ if enable_print:
271
+ print(" | ".join(entries))
272
+
273
+ def _get_batch_fmtstr(self, num_batches):
274
+ num_digits = len(str(num_batches // 1))
275
+ fmt = "{:" + str(num_digits) + "d}"
276
+ return "[" + fmt + "/" + fmt.format(num_batches) + "]"
277
+
278
+
279
+ def get_resume_checkpoint(checkpoint_save_dir):
280
+ if not g_pathmgr.isdir(checkpoint_save_dir):
281
+ return None
282
+ ckpt_file = os.path.join(checkpoint_save_dir, "checkpoint.pt")
283
+ if not g_pathmgr.isfile(ckpt_file):
284
+ return None
285
+
286
+ return ckpt_file
OVOW/third_party/sam3/sam3/visualization_utils.py ADDED
@@ -0,0 +1,943 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ # Copyright (c) Meta Platforms, Inc. and affiliates. All Rights Reserved
2
+
3
+ # pyre-unsafe
4
+ import json
5
+ import os
6
+ import subprocess
7
+ from pathlib import Path
8
+
9
+ import cv2
10
+ import matplotlib.patches as patches
11
+ import matplotlib.pyplot as plt
12
+ import numpy as np
13
+ import pandas as pd
14
+ import pycocotools.mask as mask_utils
15
+ import torch
16
+ from matplotlib.colors import to_rgb
17
+ from PIL import Image
18
+ from skimage.color import lab2rgb, rgb2lab
19
+ from sklearn.cluster import KMeans
20
+ from torchvision.ops import masks_to_boxes
21
+ from tqdm import tqdm
22
+
23
+
24
+ def generate_colors(n_colors=256, n_samples=5000):
25
+ # Step 1: Random RGB samples
26
+ np.random.seed(42)
27
+ rgb = np.random.rand(n_samples, 3)
28
+ # Step 2: Convert to LAB for perceptual uniformity
29
+ # print(f"Converting {n_samples} RGB samples to LAB color space...")
30
+ lab = rgb2lab(rgb.reshape(1, -1, 3)).reshape(-1, 3)
31
+ # print("Conversion to LAB complete.")
32
+ # Step 3: k-means clustering in LAB
33
+ kmeans = KMeans(n_clusters=n_colors, n_init=10)
34
+ # print(f"Fitting KMeans with {n_colors} clusters on {n_samples} samples...")
35
+ kmeans.fit(lab)
36
+ # print("KMeans fitting complete.")
37
+ centers_lab = kmeans.cluster_centers_
38
+ # Step 4: Convert LAB back to RGB
39
+ colors_rgb = lab2rgb(centers_lab.reshape(1, -1, 3)).reshape(-1, 3)
40
+ colors_rgb = np.clip(colors_rgb, 0, 1)
41
+ return colors_rgb
42
+
43
+
44
+ COLORS = generate_colors(n_colors=128, n_samples=5000)
45
+
46
+
47
+ def show_img_tensor(img_batch, vis_img_idx=0):
48
+ MEAN_IMG = np.array([0.5, 0.5, 0.5])
49
+ STD_IMG = np.array([0.5, 0.5, 0.5])
50
+ im_tensor = img_batch[vis_img_idx].detach().cpu()
51
+ assert im_tensor.dim() == 3
52
+ im_tensor = im_tensor.numpy().transpose((1, 2, 0))
53
+ im_tensor = (im_tensor * STD_IMG) + MEAN_IMG
54
+ im_tensor = np.clip(im_tensor, 0, 1)
55
+ plt.imshow(im_tensor)
56
+
57
+
58
+ def draw_box_on_image(image, box, color=(0, 255, 0)):
59
+ """
60
+ Draws a rectangle on a given PIL image using the provided box coordinates in xywh format.
61
+ :param image: PIL.Image - The image on which to draw the rectangle.
62
+ :param box: tuple - A tuple (x, y, w, h) representing the top-left corner, width, and height of the rectangle.
63
+ :param color: tuple - A tuple (R, G, B) representing the color of the rectangle. Default is red.
64
+ :return: PIL.Image - The image with the rectangle drawn on it.
65
+ """
66
+ # Ensure the image is in RGB mode
67
+ image = image.convert("RGB")
68
+ # Unpack the box coordinates
69
+ x, y, w, h = box
70
+ x, y, w, h = int(x), int(y), int(w), int(h)
71
+ # Get the pixel data
72
+ pixels = image.load()
73
+ # Draw the top and bottom edges
74
+ for i in range(x, x + w):
75
+ pixels[i, y] = color
76
+ pixels[i, y + h - 1] = color
77
+ pixels[i, y + 1] = color
78
+ pixels[i, y + h] = color
79
+ pixels[i, y - 1] = color
80
+ pixels[i, y + h - 2] = color
81
+ # Draw the left and right edges
82
+ for j in range(y, y + h):
83
+ pixels[x, j] = color
84
+ pixels[x + 1, j] = color
85
+ pixels[x - 1, j] = color
86
+ pixels[x + w - 1, j] = color
87
+ pixels[x + w, j] = color
88
+ pixels[x + w - 2, j] = color
89
+ return image
90
+
91
+
92
+ def plot_bbox(
93
+ img_height,
94
+ img_width,
95
+ box,
96
+ box_format="XYXY",
97
+ relative_coords=True,
98
+ color="r",
99
+ linestyle="solid",
100
+ text=None,
101
+ ax=None,
102
+ ):
103
+ if box_format == "XYXY":
104
+ x, y, x2, y2 = box
105
+ w = x2 - x
106
+ h = y2 - y
107
+ elif box_format == "XYWH":
108
+ x, y, w, h = box
109
+ elif box_format == "CxCyWH":
110
+ cx, cy, w, h = box
111
+ x = cx - w / 2
112
+ y = cy - h / 2
113
+ else:
114
+ raise RuntimeError(f"Invalid box_format {box_format}")
115
+
116
+ if relative_coords:
117
+ x *= img_width
118
+ w *= img_width
119
+ y *= img_height
120
+ h *= img_height
121
+
122
+ if ax is None:
123
+ ax = plt.gca()
124
+ rect = patches.Rectangle(
125
+ (x, y),
126
+ w,
127
+ h,
128
+ linewidth=1.5,
129
+ edgecolor=color,
130
+ facecolor="none",
131
+ linestyle=linestyle,
132
+ )
133
+ ax.add_patch(rect)
134
+ if text is not None:
135
+ facecolor = "w"
136
+ ax.text(
137
+ x,
138
+ y - 5,
139
+ text,
140
+ color=color,
141
+ weight="bold",
142
+ fontsize=8,
143
+ bbox={"facecolor": facecolor, "alpha": 0.75, "pad": 2},
144
+ )
145
+
146
+
147
+ def plot_mask(mask, color="r", ax=None):
148
+ im_h, im_w = mask.shape
149
+ mask_img = np.zeros((im_h, im_w, 4), dtype=np.float32)
150
+ mask_img[..., :3] = to_rgb(color)
151
+ mask_img[..., 3] = mask * 0.5
152
+ # Use the provided ax or the current axis
153
+ if ax is None:
154
+ ax = plt.gca()
155
+ ax.imshow(mask_img)
156
+
157
+
158
+ def normalize_bbox(bbox_xywh, img_w, img_h):
159
+ # Assumes bbox_xywh is in XYWH format
160
+ if isinstance(bbox_xywh, list):
161
+ assert len(bbox_xywh) == 4, (
162
+ "bbox_xywh list must have 4 elements. Batching not support except for torch tensors."
163
+ )
164
+ normalized_bbox = bbox_xywh.copy()
165
+ normalized_bbox[0] /= img_w
166
+ normalized_bbox[1] /= img_h
167
+ normalized_bbox[2] /= img_w
168
+ normalized_bbox[3] /= img_h
169
+ else:
170
+ assert isinstance(bbox_xywh, torch.Tensor), (
171
+ "Only torch tensors are supported for batching."
172
+ )
173
+ normalized_bbox = bbox_xywh.clone()
174
+ assert normalized_bbox.size(-1) == 4, (
175
+ "bbox_xywh tensor must have last dimension of size 4."
176
+ )
177
+ normalized_bbox[..., 0] /= img_w
178
+ normalized_bbox[..., 1] /= img_h
179
+ normalized_bbox[..., 2] /= img_w
180
+ normalized_bbox[..., 3] /= img_h
181
+ return normalized_bbox
182
+
183
+
184
+ def visualize_frame_output(frame_idx, video_frames, outputs, figsize=(12, 8)):
185
+ plt.figure(figsize=figsize)
186
+ plt.title(f"frame {frame_idx}")
187
+ img = load_frame(video_frames[frame_idx])
188
+ img_H, img_W, _ = img.shape
189
+ plt.imshow(img)
190
+ for i in range(len(outputs["out_probs"])):
191
+ box_xywh = outputs["out_boxes_xywh"][i]
192
+ prob = outputs["out_probs"][i]
193
+ obj_id = outputs["out_obj_ids"][i]
194
+ binary_mask = outputs["out_binary_masks"][i]
195
+ color = COLORS[obj_id % len(COLORS)]
196
+ plot_bbox(
197
+ img_H,
198
+ img_W,
199
+ box_xywh,
200
+ text=f"(id={obj_id}, {prob=:.2f})",
201
+ box_format="XYWH",
202
+ color=color,
203
+ )
204
+ plot_mask(binary_mask, color=color)
205
+
206
+
207
+ def visualize_formatted_frame_output(
208
+ frame_idx,
209
+ video_frames,
210
+ outputs_list,
211
+ titles=None,
212
+ points_list=None,
213
+ points_labels_list=None,
214
+ figsize=(12, 8),
215
+ title_suffix="",
216
+ prompt_info=None,
217
+ ):
218
+ """Visualize up to three sets of segmentation masks on a video frame.
219
+
220
+ Args:
221
+ frame_idx: Frame index to visualize
222
+ image_files: List of image file paths
223
+ outputs_list: List of {frame_idx: {obj_id: mask_tensor}} or single dict {obj_id: mask_tensor}
224
+ titles: List of titles for each set of outputs_list
225
+ points_list: Optional list of point coordinates
226
+ points_labels_list: Optional list of point labels
227
+ figsize: Figure size tuple
228
+ save: Whether to save the visualization to file
229
+ output_dir: Base output directory when saving
230
+ scenario_name: Scenario name for organizing saved files
231
+ title_suffix: Additional title suffix
232
+ prompt_info: Dictionary with prompt information (boxes, points, etc.)
233
+ """
234
+ # Handle single output dict case
235
+ if isinstance(outputs_list, dict) and frame_idx in outputs_list:
236
+ # This is a single outputs dict with frame indices as keys
237
+ outputs_list = [outputs_list]
238
+ elif isinstance(outputs_list, dict) and not any(
239
+ isinstance(k, int) for k in outputs_list.keys()
240
+ ):
241
+ # This is a single frame's outputs {obj_id: mask}
242
+ single_frame_outputs = {frame_idx: outputs_list}
243
+ outputs_list = [single_frame_outputs]
244
+
245
+ num_outputs = len(outputs_list)
246
+ if titles is None:
247
+ titles = [f"Set {i + 1}" for i in range(num_outputs)]
248
+ assert len(titles) == num_outputs, (
249
+ "length of `titles` should match that of `outputs_list` if not None."
250
+ )
251
+
252
+ _, axes = plt.subplots(1, num_outputs, figsize=figsize)
253
+ if num_outputs == 1:
254
+ axes = [axes] # Make it iterable
255
+
256
+ img = load_frame(video_frames[frame_idx])
257
+ img_H, img_W, _ = img.shape
258
+
259
+ for idx in range(num_outputs):
260
+ ax, outputs_set, ax_title = axes[idx], outputs_list[idx], titles[idx]
261
+ ax.set_title(f"Frame {frame_idx} - {ax_title}{title_suffix}")
262
+ ax.imshow(img)
263
+
264
+ if frame_idx in outputs_set:
265
+ _outputs = outputs_set[frame_idx]
266
+ else:
267
+ print(f"Warning: Frame {frame_idx} not found in outputs_set")
268
+ continue
269
+
270
+ if prompt_info and frame_idx == 0: # Show prompts on first frame
271
+ if "boxes" in prompt_info:
272
+ for box in prompt_info["boxes"]:
273
+ # box is in [x, y, w, h] normalized format
274
+ x, y, w, h = box
275
+ plot_bbox(
276
+ img_H,
277
+ img_W,
278
+ [x, y, x + w, y + h], # Convert to XYXY
279
+ box_format="XYXY",
280
+ relative_coords=True,
281
+ color="yellow",
282
+ linestyle="dashed",
283
+ text="PROMPT BOX",
284
+ ax=ax,
285
+ )
286
+
287
+ if "points" in prompt_info and "point_labels" in prompt_info:
288
+ points = np.array(prompt_info["points"])
289
+ labels = np.array(prompt_info["point_labels"])
290
+ # Convert normalized to pixel coordinates
291
+ points_pixel = points * np.array([img_W, img_H])
292
+
293
+ # Draw positive points (green stars)
294
+ pos_points = points_pixel[labels == 1]
295
+ if len(pos_points) > 0:
296
+ ax.scatter(
297
+ pos_points[:, 0],
298
+ pos_points[:, 1],
299
+ color="lime",
300
+ marker="*",
301
+ s=200,
302
+ edgecolor="white",
303
+ linewidth=2,
304
+ label="Positive Points",
305
+ zorder=10,
306
+ )
307
+
308
+ # Draw negative points (red stars)
309
+ neg_points = points_pixel[labels == 0]
310
+ if len(neg_points) > 0:
311
+ ax.scatter(
312
+ neg_points[:, 0],
313
+ neg_points[:, 1],
314
+ color="red",
315
+ marker="*",
316
+ s=200,
317
+ edgecolor="white",
318
+ linewidth=2,
319
+ label="Negative Points",
320
+ zorder=10,
321
+ )
322
+
323
+ objects_drawn = 0
324
+ for obj_id, binary_mask in _outputs.items():
325
+ mask_sum = (
326
+ binary_mask.sum()
327
+ if hasattr(binary_mask, "sum")
328
+ else np.sum(binary_mask)
329
+ )
330
+
331
+ if mask_sum > 0: # Only draw if mask has content
332
+ # Convert to torch tensor if it's not already
333
+ if not isinstance(binary_mask, torch.Tensor):
334
+ binary_mask = torch.tensor(binary_mask)
335
+
336
+ # Find bounding box from mask
337
+ if binary_mask.any():
338
+ box_xyxy = masks_to_boxes(binary_mask.unsqueeze(0)).squeeze()
339
+ box_xyxy = normalize_bbox(box_xyxy, img_W, img_H)
340
+ else:
341
+ # Fallback: create a small box at center
342
+ box_xyxy = [0.45, 0.45, 0.55, 0.55]
343
+
344
+ color = COLORS[obj_id % len(COLORS)]
345
+
346
+ plot_bbox(
347
+ img_H,
348
+ img_W,
349
+ box_xyxy,
350
+ text=f"(id={obj_id})",
351
+ box_format="XYXY",
352
+ color=color,
353
+ ax=ax,
354
+ )
355
+
356
+ # Convert back to numpy for plotting
357
+ mask_np = (
358
+ binary_mask.numpy()
359
+ if isinstance(binary_mask, torch.Tensor)
360
+ else binary_mask
361
+ )
362
+ plot_mask(mask_np, color=color, ax=ax)
363
+ objects_drawn += 1
364
+
365
+ if objects_drawn == 0:
366
+ ax.text(
367
+ 0.5,
368
+ 0.5,
369
+ "No objects detected",
370
+ transform=ax.transAxes,
371
+ fontsize=16,
372
+ ha="center",
373
+ va="center",
374
+ color="red",
375
+ weight="bold",
376
+ )
377
+
378
+ # Draw additional points if provided
379
+ if points_list is not None and points_list[idx] is not None:
380
+ show_points(
381
+ points_list[idx], points_labels_list[idx], ax=ax, marker_size=200
382
+ )
383
+
384
+ ax.axis("off")
385
+
386
+ plt.tight_layout()
387
+ plt.show()
388
+
389
+
390
+ def render_masklet_frame(img, outputs, frame_idx=None, alpha=0.5):
391
+ """
392
+ Overlays masklets and bounding boxes on a single image frame.
393
+ Args:
394
+ img: np.ndarray, shape (H, W, 3), uint8 or float32 in [0,255] or [0,1]
395
+ outputs: dict with keys: out_boxes_xywh, out_probs, out_obj_ids, out_binary_masks
396
+ frame_idx: int or None, for overlaying frame index text
397
+ alpha: float, mask overlay alpha
398
+ Returns:
399
+ overlay: np.ndarray, shape (H, W, 3), uint8
400
+ """
401
+ if img.dtype == np.float32 or img.max() <= 1.0:
402
+ img = (img * 255).astype(np.uint8)
403
+ img = img[..., :3] # drop alpha if present
404
+ height, width = img.shape[:2]
405
+ overlay = img.copy()
406
+
407
+ for i in range(len(outputs["out_probs"])):
408
+ obj_id = outputs["out_obj_ids"][i]
409
+ color = COLORS[obj_id % len(COLORS)]
410
+ color255 = (color * 255).astype(np.uint8)
411
+ mask = outputs["out_binary_masks"][i]
412
+ if mask.shape != img.shape[:2]:
413
+ mask = cv2.resize(
414
+ mask.astype(np.float32),
415
+ (img.shape[1], img.shape[0]),
416
+ interpolation=cv2.INTER_NEAREST,
417
+ )
418
+ mask_bool = mask > 0.5
419
+ for c in range(3):
420
+ overlay[..., c][mask_bool] = (
421
+ alpha * color255[c] + (1 - alpha) * overlay[..., c][mask_bool]
422
+ ).astype(np.uint8)
423
+
424
+ # Draw bounding boxes and text
425
+ for i in range(len(outputs["out_probs"])):
426
+ box_xywh = outputs["out_boxes_xywh"][i]
427
+ obj_id = outputs["out_obj_ids"][i]
428
+ prob = outputs["out_probs"][i]
429
+ color = COLORS[obj_id % len(COLORS)]
430
+ color255 = tuple(int(x * 255) for x in color)
431
+ x, y, w, h = box_xywh
432
+ x1 = int(x * width)
433
+ y1 = int(y * height)
434
+ x2 = int((x + w) * width)
435
+ y2 = int((y + h) * height)
436
+ cv2.rectangle(overlay, (x1, y1), (x2, y2), color255, 2)
437
+ if prob is not None:
438
+ label = f"id={obj_id}, p={prob:.2f}"
439
+ else:
440
+ label = f"id={obj_id}"
441
+ cv2.putText(
442
+ overlay,
443
+ label,
444
+ (x1, max(y1 - 10, 0)),
445
+ cv2.FONT_HERSHEY_SIMPLEX,
446
+ 0.5,
447
+ color255,
448
+ 1,
449
+ cv2.LINE_AA,
450
+ )
451
+
452
+ # Overlay frame index at the top-left corner
453
+ if frame_idx is not None:
454
+ cv2.putText(
455
+ overlay,
456
+ f"Frame {frame_idx}",
457
+ (10, 30),
458
+ cv2.FONT_HERSHEY_SIMPLEX,
459
+ 1.0,
460
+ (255, 255, 255),
461
+ 2,
462
+ cv2.LINE_AA,
463
+ )
464
+
465
+ return overlay
466
+
467
+
468
+ def save_masklet_video(video_frames, outputs, out_path, alpha=0.5, fps=10):
469
+ # Each outputs dict has keys: "out_boxes_xywh", "out_probs", "out_obj_ids", "out_binary_masks"
470
+ # video_frames: list of video frame data, same length as outputs_list
471
+
472
+ # Read first frame to get size
473
+ first_img = load_frame(video_frames[0])
474
+ height, width = first_img.shape[:2]
475
+ if first_img.dtype == np.float32 or first_img.max() <= 1.0:
476
+ first_img = (first_img * 255).astype(np.uint8)
477
+ # Use 'mp4v' for best compatibility with VSCode playback (.mp4 files)
478
+ fourcc = cv2.VideoWriter_fourcc(*"mp4v")
479
+ writer = cv2.VideoWriter("temp.mp4", fourcc, fps, (width, height))
480
+
481
+ outputs_list = [
482
+ (video_frames[frame_idx], frame_idx, outputs[frame_idx])
483
+ for frame_idx in sorted(outputs.keys())
484
+ ]
485
+
486
+ for frame, frame_idx, frame_outputs in tqdm(outputs_list):
487
+ img = load_frame(frame)
488
+ overlay = render_masklet_frame(
489
+ img, frame_outputs, frame_idx=frame_idx, alpha=alpha
490
+ )
491
+ writer.write(cv2.cvtColor(overlay, cv2.COLOR_RGB2BGR))
492
+
493
+ writer.release()
494
+
495
+ # Re-encode the video for VSCode compatibility using ffmpeg
496
+ subprocess.run(["ffmpeg", "-y", "-i", "temp.mp4", out_path])
497
+ print(f"Re-encoded video saved to {out_path}")
498
+
499
+ os.remove("temp.mp4") # Clean up temporary file
500
+
501
+
502
+ def save_masklet_image(frame, outputs, out_path, alpha=0.5, frame_idx=None):
503
+ """
504
+ Save a single image with masklet overlays.
505
+ """
506
+ img = load_frame(frame)
507
+ overlay = render_masklet_frame(img, outputs, frame_idx=frame_idx, alpha=alpha)
508
+ Image.fromarray(overlay).save(out_path)
509
+ print(f"Overlay image saved to {out_path}")
510
+
511
+
512
+ def prepare_masks_for_visualization(frame_to_output):
513
+ # frame_to_obj_masks --> {frame_idx: {'output_probs': np.array, `out_obj_ids`: np.array, `out_binary_masks`: np.array}}
514
+ for frame_idx, out in frame_to_output.items():
515
+ _processed_out = {}
516
+ for idx, obj_id in enumerate(out["out_obj_ids"].tolist()):
517
+ if out["out_binary_masks"][idx].any():
518
+ _processed_out[obj_id] = out["out_binary_masks"][idx]
519
+ frame_to_output[frame_idx] = _processed_out
520
+ return frame_to_output
521
+
522
+
523
+ def convert_coco_to_masklet_format(
524
+ annotations, img_info, is_prediction=False, score_threshold=0.5
525
+ ):
526
+ """
527
+ Convert COCO format annotations to format expected by render_masklet_frame
528
+ """
529
+ outputs = {
530
+ "out_boxes_xywh": [],
531
+ "out_probs": [],
532
+ "out_obj_ids": [],
533
+ "out_binary_masks": [],
534
+ }
535
+
536
+ img_h, img_w = img_info["height"], img_info["width"]
537
+
538
+ for idx, ann in enumerate(annotations):
539
+ # Get bounding box in relative XYWH format
540
+ if "bbox" in ann:
541
+ bbox = ann["bbox"]
542
+ if max(bbox) > 1.0: # Convert absolute to relative coordinates
543
+ bbox = [
544
+ bbox[0] / img_w,
545
+ bbox[1] / img_h,
546
+ bbox[2] / img_w,
547
+ bbox[3] / img_h,
548
+ ]
549
+ else:
550
+ mask = mask_utils.decode(ann["segmentation"])
551
+ rows = np.any(mask, axis=1)
552
+ cols = np.any(mask, axis=0)
553
+ if np.any(rows) and np.any(cols):
554
+ rmin, rmax = np.where(rows)[0][[0, -1]]
555
+ cmin, cmax = np.where(cols)[0][[0, -1]]
556
+ # Convert to relative XYWH
557
+ bbox = [
558
+ cmin / img_w,
559
+ rmin / img_h,
560
+ (cmax - cmin + 1) / img_w,
561
+ (rmax - rmin + 1) / img_h,
562
+ ]
563
+ else:
564
+ bbox = [0, 0, 0, 0]
565
+
566
+ outputs["out_boxes_xywh"].append(bbox)
567
+
568
+ # Get probability/score
569
+ if is_prediction:
570
+ prob = ann["score"]
571
+ else:
572
+ prob = 1.0 # GT has no probability
573
+ outputs["out_probs"].append(prob)
574
+
575
+ outputs["out_obj_ids"].append(idx)
576
+ mask = mask_utils.decode(ann["segmentation"])
577
+ mask = (mask > score_threshold).astype(np.uint8)
578
+
579
+ outputs["out_binary_masks"].append(mask)
580
+
581
+ return outputs
582
+
583
+
584
+ def save_side_by_side_visualization(img, gt_anns, pred_anns, noun_phrase):
585
+ """
586
+ Create side-by-side visualization of GT and predictions
587
+ """
588
+
589
+ # Create side-by-side visualization
590
+ fig, (ax1, ax2) = plt.subplots(1, 2, figsize=(14, 7))
591
+
592
+ main_title = f"Noun phrase: '{noun_phrase}'"
593
+ fig.suptitle(main_title, fontsize=16, fontweight="bold")
594
+
595
+ gt_overlay = render_masklet_frame(img, gt_anns, alpha=0.5)
596
+ ax1.imshow(gt_overlay)
597
+ ax1.set_title("Ground Truth", fontsize=14, fontweight="bold")
598
+ ax1.axis("off")
599
+
600
+ pred_overlay = render_masklet_frame(img, pred_anns, alpha=0.5)
601
+ ax2.imshow(pred_overlay)
602
+ ax2.set_title("Predictions", fontsize=14, fontweight="bold")
603
+ ax2.axis("off")
604
+
605
+ plt.subplots_adjust(top=0.88)
606
+ plt.tight_layout()
607
+
608
+
609
+ def bitget(val, idx):
610
+ return (val >> idx) & 1
611
+
612
+
613
+ def pascal_color_map():
614
+ colormap = np.zeros((512, 3), dtype=int)
615
+ ind = np.arange(512, dtype=int)
616
+ for shift in reversed(list(range(8))):
617
+ for channel in range(3):
618
+ colormap[:, channel] |= bitget(ind, channel) << shift
619
+ ind >>= 3
620
+
621
+ return colormap.astype(np.uint8)
622
+
623
+
624
+ def draw_masks_to_frame(
625
+ frame: np.ndarray, masks: np.ndarray, colors: np.ndarray
626
+ ) -> np.ndarray:
627
+ masked_frame = frame
628
+ for mask, color in zip(masks, colors):
629
+ curr_masked_frame = np.where(mask[..., None], color, masked_frame)
630
+ masked_frame = cv2.addWeighted(masked_frame, 0.75, curr_masked_frame, 0.25, 0)
631
+
632
+ if int(cv2.__version__[0]) > 3:
633
+ contours, _ = cv2.findContours(
634
+ np.array(mask, dtype=np.uint8).copy(),
635
+ cv2.RETR_TREE,
636
+ cv2.CHAIN_APPROX_NONE,
637
+ )
638
+ else:
639
+ _, contours, _ = cv2.findContours(
640
+ np.array(mask, dtype=np.uint8).copy(),
641
+ cv2.RETR_TREE,
642
+ cv2.CHAIN_APPROX_NONE,
643
+ )
644
+
645
+ cv2.drawContours(
646
+ masked_frame, contours, -1, (255, 255, 255), 7
647
+ ) # White outer contour
648
+ cv2.drawContours(
649
+ masked_frame, contours, -1, (0, 0, 0), 5
650
+ ) # Black middle contour
651
+ cv2.drawContours(
652
+ masked_frame, contours, -1, color.tolist(), 3
653
+ ) # Original color inner contour
654
+ return masked_frame
655
+
656
+
657
+ def get_annot_df(file_path: str):
658
+ with open(file_path, "r") as f:
659
+ data = json.load(f)
660
+
661
+ dfs = {}
662
+
663
+ for k, v in data.items():
664
+ if k in ("info", "licenses"):
665
+ dfs[k] = v
666
+ continue
667
+ df = pd.DataFrame(v)
668
+ dfs[k] = df
669
+
670
+ return dfs
671
+
672
+
673
+ def get_annot_dfs(file_list: list[str]):
674
+ dfs = {}
675
+ for annot_file in tqdm(file_list):
676
+ dataset_name = Path(annot_file).stem
677
+ dfs[dataset_name] = get_annot_df(annot_file)
678
+
679
+ return dfs
680
+
681
+
682
+ def get_media_dir(media_dir: str, dataset: str):
683
+ if dataset in ["saco_veval_sav_test", "saco_veval_sav_val"]:
684
+ return os.path.join(media_dir, "saco_sav", "JPEGImages_24fps")
685
+ elif dataset in ["saco_veval_yt1b_test", "saco_veval_yt1b_val"]:
686
+ return os.path.join(media_dir, "saco_yt1b", "JPEGImages_6fps")
687
+ elif dataset in ["saco_veval_smartglasses_test", "saco_veval_smartglasses_val"]:
688
+ return os.path.join(media_dir, "saco_sg", "JPEGImages_6fps")
689
+ elif dataset == "sa_fari_test":
690
+ return os.path.join(media_dir, "sa_fari", "JPEGImages_6fps")
691
+ else:
692
+ raise ValueError(f"Dataset {dataset} not found")
693
+
694
+
695
+ def get_all_annotations_for_frame(
696
+ dataset_df: pd.DataFrame, video_id: int, frame_idx: int, data_dir: str, dataset: str
697
+ ):
698
+ media_dir = os.path.join(data_dir, "media")
699
+
700
+ # Load the annotation and video data
701
+ annot_df = dataset_df["annotations"]
702
+ video_df = dataset_df["videos"]
703
+
704
+ # Get the frame
705
+ video_df_current = video_df[video_df.id == video_id]
706
+ assert len(video_df_current) == 1, (
707
+ f"Expected 1 video row, got {len(video_df_current)}"
708
+ )
709
+ video_row = video_df_current.iloc[0]
710
+ file_name = video_row.file_names[frame_idx]
711
+ file_path = os.path.join(
712
+ get_media_dir(media_dir=media_dir, dataset=dataset), file_name
713
+ )
714
+ frame = cv2.imread(file_path)
715
+ frame = cv2.cvtColor(frame, cv2.COLOR_BGR2RGB)
716
+
717
+ # Get the masks and noun phrases annotated in this video in this frame
718
+ annot_df_current_video = annot_df[annot_df.video_id == video_id]
719
+ if len(annot_df_current_video) == 0:
720
+ print(f"No annotations found for video_id {video_id}")
721
+ return frame, None, None
722
+ else:
723
+ empty_mask = np.zeros(frame.shape[:2], dtype=np.uint8)
724
+ mask_np_pairs = annot_df_current_video.apply(
725
+ lambda row: (
726
+ (
727
+ mask_utils.decode(row.segmentations[frame_idx])
728
+ if row.segmentations[frame_idx]
729
+ else empty_mask
730
+ ),
731
+ row.noun_phrase,
732
+ ),
733
+ axis=1,
734
+ )
735
+ # sort based on noun_phrases
736
+ mask_np_pairs = sorted(mask_np_pairs, key=lambda x: x[1])
737
+ masks, noun_phrases = zip(*mask_np_pairs)
738
+
739
+ return frame, masks, noun_phrases
740
+
741
+
742
+ def visualize_prompt_overlay(
743
+ frame_idx,
744
+ video_frames,
745
+ title="Prompt Visualization",
746
+ text_prompt=None,
747
+ point_prompts=None,
748
+ point_labels=None,
749
+ bounding_boxes=None,
750
+ box_labels=None,
751
+ obj_id=None,
752
+ ):
753
+ """Simple prompt visualization function"""
754
+ img = Image.fromarray(load_frame(video_frames[frame_idx]))
755
+ fig, ax = plt.subplots(1, figsize=(6, 4))
756
+ ax.imshow(img)
757
+
758
+ img_w, img_h = img.size
759
+
760
+ if text_prompt:
761
+ ax.text(
762
+ 0.02,
763
+ 0.98,
764
+ f'Text: "{text_prompt}"',
765
+ transform=ax.transAxes,
766
+ fontsize=12,
767
+ color="white",
768
+ weight="bold",
769
+ bbox=dict(boxstyle="round,pad=0.3", facecolor="red", alpha=0.7),
770
+ verticalalignment="top",
771
+ )
772
+
773
+ if point_prompts:
774
+ for i, point in enumerate(point_prompts):
775
+ x, y = point
776
+ # Convert relative to absolute coordinates
777
+ x_img, y_img = x * img_w, y * img_h
778
+
779
+ # Use different colors for positive/negative points
780
+ if point_labels and len(point_labels) > i:
781
+ color = "green" if point_labels[i] == 1 else "red"
782
+ marker = "o" if point_labels[i] == 1 else "x"
783
+ else:
784
+ color = "green"
785
+ marker = "o"
786
+
787
+ ax.plot(
788
+ x_img,
789
+ y_img,
790
+ marker=marker,
791
+ color=color,
792
+ markersize=10,
793
+ markeredgewidth=2,
794
+ markeredgecolor="white",
795
+ )
796
+ ax.text(
797
+ x_img + 5,
798
+ y_img - 5,
799
+ f"P{i + 1}",
800
+ color=color,
801
+ fontsize=10,
802
+ weight="bold",
803
+ bbox=dict(boxstyle="round,pad=0.2", facecolor="white", alpha=0.8),
804
+ )
805
+
806
+ if bounding_boxes:
807
+ for i, box in enumerate(bounding_boxes):
808
+ x, y, w, h = box
809
+ # Convert relative to absolute coordinates
810
+ x_img, y_img = x * img_w, y * img_h
811
+ w_img, h_img = w * img_w, h * img_h
812
+
813
+ # Use different colors for positive/negative boxes
814
+ if box_labels and len(box_labels) > i:
815
+ color = "green" if box_labels[i] == 1 else "red"
816
+ else:
817
+ color = "green"
818
+
819
+ rect = patches.Rectangle(
820
+ (x_img, y_img),
821
+ w_img,
822
+ h_img,
823
+ linewidth=2,
824
+ edgecolor=color,
825
+ facecolor="none",
826
+ )
827
+ ax.add_patch(rect)
828
+ ax.text(
829
+ x_img,
830
+ y_img - 5,
831
+ f"B{i + 1}",
832
+ color=color,
833
+ fontsize=10,
834
+ weight="bold",
835
+ bbox=dict(boxstyle="round,pad=0.2", facecolor="white", alpha=0.8),
836
+ )
837
+
838
+ # Add object ID info if provided
839
+ if obj_id is not None:
840
+ ax.text(
841
+ 0.02,
842
+ 0.02,
843
+ f"Object ID: {obj_id}",
844
+ transform=ax.transAxes,
845
+ fontsize=10,
846
+ color="white",
847
+ weight="bold",
848
+ bbox=dict(boxstyle="round,pad=0.3", facecolor="blue", alpha=0.7),
849
+ verticalalignment="bottom",
850
+ )
851
+
852
+ ax.set_title(title)
853
+ ax.axis("off")
854
+ plt.tight_layout()
855
+ plt.show()
856
+
857
+
858
+ def plot_results(img, results):
859
+ plt.figure(figsize=(12, 8))
860
+ plt.imshow(img)
861
+ nb_objects = len(results["scores"])
862
+ print(f"found {nb_objects} object(s)")
863
+ for i in range(nb_objects):
864
+ color = COLORS[i % len(COLORS)]
865
+ plot_mask(results["masks"][i].squeeze(0).cpu(), color=color)
866
+ w, h = img.size
867
+ prob = results["scores"][i].item()
868
+ plot_bbox(
869
+ h,
870
+ w,
871
+ results["boxes"][i].cpu(),
872
+ text=f"(id={i}, {prob=:.2f})",
873
+ box_format="XYXY",
874
+ color=color,
875
+ relative_coords=False,
876
+ )
877
+
878
+
879
+ def single_visualization(img, anns, title):
880
+ """
881
+ Create a single image visualization with overlays.
882
+ """
883
+ fig, ax = plt.subplots(figsize=(7, 7))
884
+ fig.suptitle(title, fontsize=16, fontweight="bold")
885
+ overlay = render_masklet_frame(img, anns, alpha=0.5)
886
+ ax.imshow(overlay)
887
+ ax.axis("off")
888
+ plt.tight_layout()
889
+
890
+
891
+ def show_mask(mask, ax, obj_id=None, random_color=False):
892
+ if random_color:
893
+ color = np.concatenate([np.random.random(3), np.array([0.6])], axis=0)
894
+ else:
895
+ cmap = plt.get_cmap("tab10")
896
+ cmap_idx = 0 if obj_id is None else obj_id
897
+ color = np.array([*cmap(cmap_idx)[:3], 0.6])
898
+ h, w = mask.shape[-2:]
899
+ mask_image = mask.reshape(h, w, 1) * color.reshape(1, 1, -1)
900
+ ax.imshow(mask_image)
901
+
902
+
903
+ def show_box(box, ax):
904
+ x0, y0 = box[0], box[1]
905
+ w, h = box[2] - box[0], box[3] - box[1]
906
+ ax.add_patch(
907
+ plt.Rectangle((x0, y0), w, h, edgecolor="green", facecolor=(0, 0, 0, 0), lw=2)
908
+ )
909
+
910
+
911
+ def show_points(coords, labels, ax, marker_size=375):
912
+ pos_points = coords[labels == 1]
913
+ neg_points = coords[labels == 0]
914
+ ax.scatter(
915
+ pos_points[:, 0],
916
+ pos_points[:, 1],
917
+ color="green",
918
+ marker="*",
919
+ s=marker_size,
920
+ edgecolor="white",
921
+ linewidth=1.25,
922
+ )
923
+ ax.scatter(
924
+ neg_points[:, 0],
925
+ neg_points[:, 1],
926
+ color="red",
927
+ marker="*",
928
+ s=marker_size,
929
+ edgecolor="white",
930
+ linewidth=1.25,
931
+ )
932
+
933
+
934
+ def load_frame(frame):
935
+ if isinstance(frame, np.ndarray):
936
+ img = frame
937
+ elif isinstance(frame, Image.Image):
938
+ img = np.array(frame)
939
+ elif isinstance(frame, str) and os.path.isfile(frame):
940
+ img = plt.imread(frame)
941
+ else:
942
+ raise ValueError(f"Invalid video frame type: {type(frame)=}")
943
+ return img
OVOW/third_party/sam3/scripts/eval/gold/README.md ADDED
@@ -0,0 +1,299 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ # SA-Co/Gold benchmark
2
+
3
+ SA-Co/Gold is a benchmark for promptable concept segmentation (PCS) in images. The benchmark contains images paired with text labels, also referred as Noun Phrases (NPs), each annotated exhaustively with masks on all object instances that match the label. SA-Co/Gold comprises 7 subsets, each targeting a different annotation domain: MetaCLIP captioner NPs, SA-1B captioner NPs, Attributes, Crowded Scenes, Wiki-Common1K, Wiki-Food/Drink, Wiki-Sports Equipment. The images are originally from the MetaCLIP and SA-1B datasets.
4
+
5
+ For each subset, the annotations are multi-reviewed by 3 independent human annotators. Each row in the figure shows an image and noun phrase pair from
6
+ one of the domains, and masks from the 3 annotators. Dashed borders indicate special group masks that cover more than a single instance, used when separating into instances is deemed too difficult. Annotators sometimes disagree on precise mask borders, the number of instances, and whether the phrase exists. Having 3 independent annotations allow us to measure human agreement on the task, which serves as an upper bound for model performance.
7
+
8
+
9
+ <p align="center">
10
+ <img src="../../../assets/saco_gold_annotation.png?" style="width:80%;" />
11
+ </p>
12
+ # Preparation
13
+
14
+ ## Download annotations
15
+
16
+ The GT annotations can be downloaded from [Hugging Face](https://huggingface.co/datasets/facebook/SACo-Gold) or [Roboflow](https://universe.roboflow.com/sa-co-gold)
17
+
18
+ ## Download images
19
+
20
+ There are two image sources for the evaluation dataset: MetaCLIP and SA-1B.
21
+
22
+ 1) The MetaCLIP images are referred in 6 out of 7 subsets (MetaCLIP captioner NPs, Attributes, Crowded Scenes, Wiki-Common1K, Wiki-Food/Drink, Wiki-Sports Equipment) and can be downloaded from [Roboflow](https://universe.roboflow.com/sa-co-gold/gold-metaclip-merged-a-release-test/).
23
+
24
+ 2) The SA-1B images are referred in 1 out of 7 subsets (SA-1B captioner NPs) and can be downloaded from [Roboflow](https://universe.roboflow.com/sa-co-gold/gold-sa-1b-merged-a-release-test/). Alternatively, they can be downloaded from [here](https://ai.meta.com/datasets/segment-anything-downloads/). Please access the link for `sa_co_gold.tar` from dynamic links available under `Download text file` to download the SA-1B images referred in SA-Co/Gold.
25
+
26
+ # Usage
27
+ ## Visualization
28
+
29
+ - Visualize GT annotations: [saco_gold_silver_vis_example.ipynb](https://github.com/facebookresearch/sam3/blob/main/examples/saco_gold_silver_vis_example.ipynb)
30
+ - Visualize GT annotations and sample predictions side-by-side: [sam3_data_and_predictions_visualization.ipynb](https://github.com/facebookresearch/sam3/blob/main/examples/sam3_data_and_predictions_visualization.ipynb)
31
+
32
+
33
+ ## Run evaluation
34
+
35
+ The official metric for SA-Co/Gold is cgF1. Please refer to the SAM3 paper for details.
36
+ Our evaluator inherits from the official COCO evaluator, with some modifications. Recall that in the Gold subset, there are three annotations for each datapoint. We evaluate against each of them and picks the most favorable (oracle setting). It has minimal dependency (pycocotools, numpy and scipy), to help reusability in other projects. In this section we provide several pointers to run evaluation of SAM3 or third-party models.
37
+
38
+ ### Evaluate SAM3
39
+
40
+ We provide inference configurations to reproduce the evaluation of SAM3.
41
+ First, please edit the file [eval_base.yaml](https://github.com/facebookresearch/sam3/blob/main/sam3/train/configs/eval_base.yaml) with the paths where you downloaded the images and annotations above.
42
+
43
+ There are 7 subsets and as many configurations to be run.
44
+ Let's take the first subset as an example. The inference can be run locally using the following command (you can adjust the number of gpus):
45
+ ```bash
46
+ python sam3/train/train.py -c configs/gold_image_evals/sam3_gold_image_metaclip_nps.yaml --use-cluster 0 --num-gpus 1
47
+ ```
48
+ The predictions will be dumped in the folder specified in eval_base.yaml.
49
+
50
+ We also provide support for SLURM-based cluster inference. Edit the eval_base.yaml file to reflect your slurm configuration (partition, qos, ...), then run
51
+
52
+ ```bash
53
+ python sam3/train/train.py -c configs/gold_image_evals/sam3_gold_image_metaclip_nps.yaml --use-cluster 1
54
+ ```
55
+
56
+ We provide the commands for all subsets below
57
+ #### MetaCLIP captioner NPs
58
+
59
+ ```bash
60
+ python sam3/train/train.py -c configs/gold_image_evals/sam3_gold_image_metaclip_nps.yaml --use-cluster 1
61
+ ```
62
+ #### SA-1B captioner NPs
63
+
64
+ Refer to SA-1B images for this subset. For the other 6 subsets, refer to MetaCLIP images.
65
+
66
+ ```bash
67
+ python sam3/train/train.py -c configs/gold_image_evals/sam3_gold_image_sa1b_nps.yaml --use-cluster 1
68
+ ```
69
+ #### Attributes
70
+
71
+ ```bash
72
+ python sam3/train/train.py -c configs/gold_image_evals/sam3_gold_image_attributes.yaml --use-cluster 1
73
+ ```
74
+ #### Crowded Scenes
75
+
76
+ ```bash
77
+ python sam3/train/train.py -c configs/gold_image_evals/sam3_gold_image_crowded.yaml --use-cluster 1
78
+ ```
79
+ #### Wiki-Common1K
80
+
81
+ ```bash
82
+ python sam3/train/train.py -c configs/gold_image_evals/sam3_gold_image_wiki_common.yaml --use-cluster 1
83
+ ```
84
+ #### Wiki-Food/Drink
85
+
86
+ ```bash
87
+ python sam3/train/train.py -c configs/gold_image_evals/sam3_gold_image_fg_food.yaml --use-cluster 1
88
+ ```
89
+
90
+ #### Wiki-Sports Equipment
91
+
92
+ ```bash
93
+ python sam3/train/train.py -c configs/gold_image_evals/sam3_gold_image_fg_sports.yaml --use-cluster 1
94
+ ```
95
+
96
+ ### Offline evaluation
97
+
98
+ If you have the predictions in the COCO result format (see [here](https://cocodataset.org/#format-results)), then we provide scripts to easily run the evaluation.
99
+
100
+ For an example on how to run the evaluator on all subsets and aggregate results, see the following notebook: [saco_gold_silver_eval_example.ipynb](https://github.com/facebookresearch/sam3/blob/main/examples/saco_gold_silver_eval_example.ipynb)
101
+ Alternatively, you can run `python scripts/eval/gold/eval_sam3.py`
102
+
103
+ If you have a prediction file for a given subset, you can run the evaluator specifically for that one using the standalone script. Example:
104
+ ```bash
105
+ python scripts/eval/standalone_cgf1.py --pred_file /path/to/coco_predictions_segm.json --gt_files /path/to/annotations/gold_metaclip_merged_a_release_test.json /path/to/annotations/gold_metaclip_merged_b_release_test.json /path/to/annotations/gold_metaclip_merged_c_release_test.json
106
+ ```
107
+
108
+
109
+ # Results
110
+ Here we collect the segmentation results for SAM3 and some baselines. Note that the baselines that do not produce masks are evaluated by converting the boxes to masks using SAM2
111
+ <table style="border-color:black;border-style:solid;border-width:1px;border-collapse:collapse;border-spacing:0;text-align:right" class="tg"><thead>
112
+ <tr><th style="text-align:center"></th><th style="text-align:center" colspan="3">Average</th><th style="text-align:center" colspan="3">Captioner metaclip</th><th style="text-align:center" colspan="3">Captioner sa1b</th>
113
+ <th style="text-align:center" colspan="3">Crowded</th><th style="text-align:center" colspan="3">FG food</th><th style="text-align:center" colspan="3">FG sport</th><th style="text-align:center" colspan="3">Attributes</th>
114
+ <th style="text-align:center" colspan="3">Wiki common</th></tr>
115
+ </thead>
116
+ <tbody>
117
+ <tr><td ></td><td >cgF1</td><td >IL_MCC</td><td >positive_micro_F1</td>
118
+ <td >cgF1</td><td >IL_MCC</td><td >positive_micro_F1</td><td >cgF1</td>
119
+ <td >IL_MCC</td><td >positive_micro_F1</td><td >cgF1</td><td >IL_MCC</td>
120
+ <td >positive_micro_F1</td><td >cgF1</td><td >IL_MCC</td><td >positive_micro_F1</td>
121
+ <td >cgF1</td><td >IL_MCC</td><td >positive_micro_F1</td><td >cgF1</td>
122
+ <td >IL_MCC</td><td >positive_micro_F1</td><td >cgF1</td><td >IL_MCC</td>
123
+ <td >positive_micro_F1</td></tr>
124
+ <tr><td >gDino-T</td><td >3.25</td><td >0.15</td><td >16.2</td>
125
+ <td >2.89</td><td >0.21</td><td >13.88</td><td >3.07</td>
126
+ <td >0.2</td><td >15.35</td><td >0.28</td><td >0.08</td>
127
+ <td >3.37</td><td >0.96</td><td >0.1</td><td >9.83</td>
128
+ <td >1.12</td><td >0.1</td><td >11.2</td><td >13.75</td>
129
+ <td >0.29</td><td >47.3</td><td >0.7</td><td >0.06</td>
130
+ <td >12.14</td></tr>
131
+ <tr><td >OWLv2*</td><td >24.59</td><td >0.57</td><td >42</td>
132
+ <td >17.69</td><td >0.52</td><td >34.27</td><td >13.32</td>
133
+ <td >0.5</td><td >26.83</td><td >15.8</td><td >0.51</td>
134
+ <td >30.74</td><td >31.96</td><td >0.65</td><td >49.35</td>
135
+ <td >36.01</td><td >0.64</td><td >56.19</td><td >35.61</td>
136
+ <td >0.63</td><td >56.23</td><td >21.73</td><td >0.54</td>
137
+ <td >40.25</td></tr>
138
+ <tr><td >OWLv2</td><td >17.27</td><td >0.46</td><td >36.8</td>
139
+ <td >12.21</td><td >0.39</td><td >31.33</td><td >9.76</td>
140
+ <td >0.45</td><td >21.65</td><td >8.87</td><td >0.36</td>
141
+ <td >24.77</td><td >24.36</td><td >0.51</td><td >47.85</td>
142
+ <td >24.44</td><td >0.52</td><td >46.97</td><td >25.85</td>
143
+ <td >0.54</td><td >48.22</td><td >15.4</td><td >0.42</td>
144
+ <td >36.64</td></tr>
145
+ <tr><td >LLMDet-L</td><td >6.5</td><td >0.21</td><td >27.3</td>
146
+ <td >4.49</td><td >0.23</td><td >19.36</td><td >5.32</td>
147
+ <td >0.23</td><td >22.81</td><td >2.42</td><td >0.18</td>
148
+ <td >13.74</td><td >5.5</td><td >0.19</td><td >29.12</td>
149
+ <td >4.39</td><td >0.17</td><td >25.34</td><td >22.17</td>
150
+ <td >0.39</td><td >57.13</td><td >1.18</td><td >0.05</td>
151
+ <td >23.3</td></tr>
152
+ <tr><td >APE</td><td >16.41</td><td >0.4</td><td >36.9</td>
153
+ <td >12.6</td><td >0.42</td><td >30.11</td><td >2.23</td>
154
+ <td >0.22</td><td >10.01</td><td >7.15</td><td >0.35</td>
155
+ <td >20.3</td><td >22.74</td><td >0.51</td><td >45.01</td>
156
+ <td >31.79</td><td >0.56</td><td >56.45</td><td >26.74</td>
157
+ <td >0.47</td><td >57.27</td><td >11.59</td><td >0.29</td>
158
+ <td >39.46</td></tr>
159
+ <tr><td >DINO-X</td><td >21.26</td><td >0.38</td><td >55.2</td>
160
+ <td >17.21</td><td >0.35</td><td >49.17</td><td >19.66</td>
161
+ <td >0.48</td><td >40.93</td><td >12.86</td><td >0.34</td>
162
+ <td >37.48</td><td >30.07</td><td >0.49</td><td >61.72</td>
163
+ <td >28.36</td><td >0.41</td><td >69.4</td><td >30.97</td>
164
+ <td >0.42</td><td >74.04</td><td >9.72</td><td >0.18</td>
165
+ <td >53.52</td></tr>
166
+ <tr><td >Gemini 2.5</td><td >13.03</td><td >0.29</td><td >46.1</td>
167
+ <td >9.9</td><td >0.29</td><td >33.79</td><td >13.1</td>
168
+ <td >0.41</td><td >32.1</td><td >8.15</td><td >0.27</td>
169
+ <td >30.34</td><td >19.63</td><td >0.33</td><td >59.52</td>
170
+ <td >15.07</td><td >0.28</td><td >53.5</td><td >18.84</td>
171
+ <td >0.3</td><td >63.14</td><td >6.5</td><td >0.13</td>
172
+ <td >50.32</td></tr>
173
+ <tr><td >SAM 3</td><td >54.06</td><td >0.82</td><td >66.11</td>
174
+ <td >47.26</td><td >0.81</td><td >58.58</td><td >53.69</td>
175
+ <td >0.86</td><td >62.55</td><td >61.08</td><td >0.9</td>
176
+ <td >67.73</td><td >53.41</td><td >0.79</td><td >67.28</td>
177
+ <td >65.52</td><td >0.89</td><td >73.75</td><td >54.93</td>
178
+ <td >0.76</td><td >72</td><td >42.53</td><td >0.7</td>
179
+ <td >60.85</td></tr>
180
+ </tbody></table>
181
+
182
+
183
+
184
+ # Annotation format
185
+
186
+ The annotation format is derived from [COCO format](https://cocodataset.org/#format-data). Notable data fields are:
187
+
188
+ - `images`: a `list` of `dict` features, contains a list of all image-NP pairs. Each entry is related to an image-NP pair and has the following items.
189
+ - `id`: an `int` feature, unique identifier for the image-NP pair
190
+ - `text_input`: a `string` feature, the noun phrase for the image-NP pair
191
+ - `file_name`: a `string` feature, the relative image path in the corresponding data folder.
192
+ - `height`/`width`: dimension of the image
193
+ - `is_instance_exhaustive`: Boolean (0 or 1). If it's 1 then all the instances are correctly annotated. For instance segmentation, we only use those datapoints. Otherwise, there may be either missing instances or crowd segments (a segment covering multiple instances)
194
+ - `is_pixel_exhaustive`: Boolean (0 or 1). If it's 1, then the union of all masks cover all pixels corresponding to the prompt. This is weaker than instance_exhaustive since it allows crowd segments. It can be used for semantic segmentation evaluations.
195
+
196
+ - `annotations`: a `list` of `dict` features, containing a list of all annotations including bounding box, segmentation mask, area etc.
197
+ - `image_id`: an `int` feature, maps to the identifier for the image-np pair in images
198
+ - `bbox`: a `list` of float features, containing bounding box in [x,y,w,h] format, normalized by the image dimensions
199
+ - `segmentation`: a dict feature, containing segmentation mask in RLE format
200
+ - `category_id`: For compatibility with the coco format. Will always be 1 and is unused.
201
+ - `is_crowd`: Boolean (0 or 1). If 1, then the segment overlaps several instances (used in cases where instances are not separable, for e.g. due to poor image quality)
202
+
203
+ - `categories`: a `list` of `dict` features, containing a list of all categories. Here, we provide the category key for compatibility with the COCO format, but in open-vocabulary detection we do not use it. Instead, the text prompt is stored directly in each image (text_input in images). Note that in our setting, a unique image (id in images) actually corresponds to an (image, text prompt) combination.
204
+
205
+
206
+ For `id` in images that have corresponding annotations (i.e. exist as `image_id` in `annotations`), we refer to them as a "positive" NP. And, for `id` in `images` that don't have any annotations (i.e. they do not exist as `image_id` in `annotations`), we refer to them as a "negative" NP.
207
+
208
+ A sample annotation from Wiki-Food/Drink domain looks as follows:
209
+
210
+ #### images
211
+
212
+ ```
213
+ [
214
+ {
215
+ "id": 10000000,
216
+ "file_name": "1/1001/metaclip_1_1001_c122868928880ae52b33fae1.jpeg",
217
+ "text_input": "chili",
218
+ "width": 600,
219
+ "height": 600,
220
+ "queried_category": "0",
221
+ "is_instance_exhaustive": 1,
222
+ "is_pixel_exhaustive": 1
223
+ },
224
+ {
225
+ "id": 10000001,
226
+ "file_name": "1/1001/metaclip_1_1001_c122868928880ae52b33fae1.jpeg",
227
+ "text_input": "the fish ball",
228
+ "width": 600,
229
+ "height": 600,
230
+ "queried_category": "2001",
231
+ "is_instance_exhaustive": 1,
232
+ "is_pixel_exhaustive": 1
233
+ }
234
+ ]
235
+ ```
236
+
237
+ #### annotations
238
+
239
+ ```
240
+ [
241
+ {
242
+ "id": 1,
243
+ "image_id": 10000000,
244
+ "source": "manual",
245
+ "area": 0.002477777777777778,
246
+ "bbox": [
247
+ 0.44333332777023315,
248
+ 0.0,
249
+ 0.10833333432674408,
250
+ 0.05833333358168602
251
+ ],
252
+ "segmentation": {
253
+ "counts": "`kk42fb01O1O1O1O001O1O1O001O1O00001O1O001O001O0000000000O1001000O010O02O001N10001N0100000O10O1000O10O010O100O1O1O1O1O0000001O0O2O1N2N2Nobm4",
254
+ "size": [
255
+ 600,
256
+ 600
257
+ ]
258
+ },
259
+ "category_id": 1,
260
+ "iscrowd": 0
261
+ },
262
+ {
263
+ "id": 2,
264
+ "image_id": 10000000,
265
+ "source": "manual",
266
+ "area": 0.001275,
267
+ "bbox": [
268
+ 0.5116666555404663,
269
+ 0.5716666579246521,
270
+ 0.061666667461395264,
271
+ 0.036666665226221085
272
+ ],
273
+ "segmentation": {
274
+ "counts": "aWd51db05M1O2N100O1O1O1O1O1O010O100O10O10O010O010O01O100O100O1O00100O1O100O1O2MZee4",
275
+ "size": [
276
+ 600,
277
+ 600
278
+ ]
279
+ },
280
+ "category_id": 1,
281
+ "iscrowd": 0
282
+ }
283
+ ]
284
+ ```
285
+
286
+ # Data Stats
287
+
288
+ Here are the stats for the 7 annotation domains. The # Image-NPs represent the total number of unique image-NP pairs including both “positive” and “negative” NPs.
289
+
290
+
291
+ | Domain | Media | # Image-NPs | # Image-NP-Masks|
292
+ |--------------------------|--------------|---------------| ----------------|
293
+ | MetaCLIP captioner NPs | MetaCLIP | 33393 | 20144 |
294
+ | SA-1B captioner NPs | SA-1B | 13258 | 30306 |
295
+ | Attributes | MetaCLIP | 9245 | 3663 |
296
+ | Crowded Scenes | MetaCLIP | 20687 | 50417 |
297
+ | Wiki-Common1K | MetaCLIP | 65502 | 6448 |
298
+ | Wiki-Food&Drink | MetaCLIP | 13951 | 9825 |
299
+ | Wiki-Sports Equipment | MetaCLIP | 12166 | 5075 |
OVOW/third_party/sam3/scripts/eval/gold/eval_sam3.py ADDED
@@ -0,0 +1,106 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ # Copyright (c) Meta Platforms, Inc. and affiliates. All Rights Reserved
2
+
3
+ # pyre-unsafe
4
+
5
+ """Script to run the evaluator offline given the GTs for SAC-Gold test set and SAM3 model prediction files.
6
+ It reports CGF1, IL_MCC, PM_F1 metrics for each subset of SAC-Gold test set.
7
+
8
+ Usage: python eval_sam3.py --gt-folder <folder_with_gts> --pred-folder <folder_with_predictions>
9
+ """
10
+
11
+ import argparse
12
+ import os
13
+
14
+ from sam3.eval.cgf1_eval import CGF1Evaluator
15
+
16
+ # Relative file names for GT files for 7 SA-Co/Gold subsets
17
+
18
+ saco_gold_gts = {
19
+ # MetaCLIP Captioner
20
+ "metaclip_nps": [
21
+ "gold_metaclip_merged_a_release_test.json",
22
+ "gold_metaclip_merged_b_release_test.json",
23
+ "gold_metaclip_merged_c_release_test.json",
24
+ ],
25
+ # SA-1B captioner
26
+ "sa1b_nps": [
27
+ "gold_sa1b_merged_a_release_test.json",
28
+ "gold_sa1b_merged_b_release_test.json",
29
+ "gold_sa1b_merged_c_release_test.json",
30
+ ],
31
+ # Crowded
32
+ "crowded": [
33
+ "gold_crowded_merged_a_release_test.json",
34
+ "gold_crowded_merged_b_release_test.json",
35
+ "gold_crowded_merged_c_release_test.json",
36
+ ],
37
+ # FG Food
38
+ "fg_food": [
39
+ "gold_fg_food_merged_a_release_test.json",
40
+ "gold_fg_food_merged_b_release_test.json",
41
+ "gold_fg_food_merged_c_release_test.json",
42
+ ],
43
+ # FG Sports
44
+ "fg_sports_equipment": [
45
+ "gold_fg_sports_equipment_merged_a_release_test.json",
46
+ "gold_fg_sports_equipment_merged_b_release_test.json",
47
+ "gold_fg_sports_equipment_merged_c_release_test.json",
48
+ ],
49
+ # Attributes
50
+ "attributes": [
51
+ "gold_attributes_merged_a_release_test.json",
52
+ "gold_attributes_merged_b_release_test.json",
53
+ "gold_attributes_merged_c_release_test.json",
54
+ ],
55
+ # Wiki common
56
+ "wiki_common": [
57
+ "gold_wiki_common_merged_a_release_test.json",
58
+ "gold_wiki_common_merged_b_release_test.json",
59
+ "gold_wiki_common_merged_c_release_test.json",
60
+ ],
61
+ }
62
+
63
+
64
+ def main():
65
+ parser = argparse.ArgumentParser()
66
+ parser.add_argument(
67
+ "-g",
68
+ "--gt-folder",
69
+ type=str,
70
+ help="Path to the folder containing the ground truth json files.",
71
+ )
72
+ parser.add_argument(
73
+ "-p",
74
+ "--pred-folder",
75
+ type=str,
76
+ help="Path to the folder containing the predictions json files.",
77
+ )
78
+ args = parser.parse_args()
79
+
80
+ results = ""
81
+
82
+ for subset_name, gts in saco_gold_gts.items():
83
+ print("Processing subset: ", subset_name)
84
+ gt_paths = [os.path.join(args.gt_folder, gt) for gt in gts]
85
+ evaluator = CGF1Evaluator(
86
+ gt_path=gt_paths, verbose=True, iou_type="segm"
87
+ ) # change to bbox if you want detection performance
88
+
89
+ pred_path = os.path.join(
90
+ args.pred_folder,
91
+ f"gold_{subset_name}/dumps/gold_{subset_name}/coco_predictions_segm.json",
92
+ )
93
+ summary = evaluator.evaluate(pred_path)
94
+
95
+ cgf1 = str(round(summary["cgF1_eval_segm_cgF1"] * 100, 2))
96
+ il_mcc = str(round(summary["cgF1_eval_segm_IL_MCC"], 2))
97
+ pmf1 = str(round(summary["cgF1_eval_segm_positive_micro_F1"] * 100, 2))
98
+ final_str = f"{cgf1},{il_mcc},{pmf1}"
99
+ results += subset_name + ": " + final_str + "\n"
100
+
101
+ print("Subset name, CG_F1, IL_MCC, pmF1")
102
+ print(results)
103
+
104
+
105
+ if __name__ == "__main__":
106
+ main()
OVOW/third_party/sam3/scripts/eval/silver/CONFIG_FRAMES.yaml ADDED
@@ -0,0 +1,24 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ path_annotations: <YOUR_ANNOTATIONS_PATH>/saco_frames_test_sets/annotations/
2
+
3
+ # Paths with downloaded data
4
+ droid_path: <YOUR_DATASET_PATH>/saco_frames_test_sets/droid/
5
+ sav_path: <YOUR_DATASET_PATH>/saco_frames_test_sets/sav/
6
+ ego4d_path: <YOUR_DATASET_PATH>/saco_frames_test_sets/ego4d/
7
+ yt1b_path: <YOUR_DATASET_PATH>/saco_frames_test_sets/yt1b/
8
+
9
+ # Configuration to download and extract video frames
10
+ cookies_path: <YOUR_COOKIES_PATH>/cookies.txt # Required to download YT1B videos
11
+ update_annotation_yt1b: true
12
+ update_annotation_ego4d: true
13
+
14
+ sav_videos_fps_6_download_path: ''
15
+
16
+ remove_downloaded_videos_yt1b: false
17
+ remove_downloaded_videos_droid: false
18
+ remove_downloaded_videos_ego4d: false
19
+ remove_downloaded_videos_sav: false
20
+
21
+ # Configuration for visualization of data
22
+ num_images_show: 5
23
+ saco_subset_show: yt1b # Options: [yt1b, ego4d, sav, droid]
24
+ directory_save: <YOUR_SAVE_DIR>
OVOW/third_party/sam3/scripts/eval/silver/README.md ADDED
@@ -0,0 +1,405 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ # SA-Co/Silver benchmark
2
+
3
+ SA-Co/Silver is a benchmark for promptable concept segmentation (PCS) in images. The benchmark contains images paired with text labels (also referred as Noun Phrases aka NPs), each annotated exhaustively with masks on all object instances that match the label.
4
+
5
+ SA-Co/Silver comprises 10 subsets, covering a diverse array of domains including food, art, robotics, driving etc. Unlike SA-Co/Gold, there is only a single ground-truth for each datapoint, which means the results may have a bit more variance and tend to underestimate model performance, since they don't account for possible different interpretations of each query.
6
+
7
+ - BDD100k
8
+ - DROID
9
+ - Ego4D
10
+ - MyFoodRepo-273
11
+ - GeoDE
12
+ - iNaturalist-2017
13
+ - National Gallery of Art
14
+ - SA-V
15
+ - YT-Temporal-1B
16
+ - Fathomnet
17
+
18
+ The README contains instructions on how to download and setup the annotations, image data to prepare them for evaluation on SA-Co/Silver.
19
+
20
+ # Preparation
21
+ ## Download annotations
22
+
23
+ The GT annotations can be downloaded from [Hugging Face](https://huggingface.co/datasets/facebook/SACo-Silver) or [Roboflow](https://universe.roboflow.com/sa-co-silver)
24
+
25
+ ## Download images and video frames
26
+
27
+ ### Image Datasets
28
+
29
+ #### GeoDE
30
+
31
+ The processed images needed for evaluation can be downloaded from [Roboflow](https://universe.roboflow.com/sa-co-silver/geode/) OR follow the below steps to prepare the processed images.
32
+
33
+ 1. Download dataset with raw images from [GeoDE](https://geodiverse-data-collection.cs.princeton.edu/).
34
+ 2. Extract the downloaded file to a location, say `<RAW_GEODE_IMAGES_FOLDER>`
35
+
36
+ 3. Run the below command to pre-process the images and prepare for evaluation. The proceesed images will be saved to the location specified in `<PROCESSED_GEODE_IMAGES_FOLDER>`
37
+ ```
38
+ python preprocess_silver_geode_bdd100k_food_rec.py --annotation_file <FOLDER_WITH_SILVER_ANNOTATIONS>/silver_geode_merged_test.json --raw_images_folder <RAW_GEODE_IMAGES_FOLDER> --processed_images_folder <PROCESSED_GEODE_IMAGES_FOLDER> --dataset_name geode
39
+ ```
40
+
41
+ #### National Gallery of Art (NGA)
42
+
43
+ The processed images needed for evaluation can be downloaded from [Roboflow](https://universe.roboflow.com/sa-co-silver/national-gallery-of-art/) OR follow the below steps to prepare the processed images.
44
+
45
+ 1. Run the below command to download raw images and pre-process the images to prepare for evaluation. The proceesed images will be saved to the location specified in `<PROCESSED_NGA_IMAGES_FOLDER>`.
46
+ ```
47
+ python download_preprocess_nga.py --annotation_file <FOLDER_WITH_SILVER_ANNOTATIONS>/silver_nga_art_merged_test.json --raw_images_folder <RAW_NGA_IMAGES_FOLDER> --processed_images_folder <PROCESSED_NGA_IMAGES_FOLDER>
48
+ ```
49
+
50
+ #### Berkeley Driving Dataset (BDD) 100k
51
+
52
+ The processed images needed for evaluation can be downloaded from [Roboflow](https://universe.roboflow.com/sa-co-silver/bdd100k-gwmh6/) OR follow the below steps to prepare the processed images.
53
+
54
+ 1. Download data with raw images from the `100K Images` dataset in [BDD100k](http://bdd-data.berkeley.edu/download.html)
55
+ 2. Extract the downloaded file to a location, say `<RAW_BDD_IMAGES_FOLDER>`
56
+ 3. Run the below command to pre-process the images and prepare for evaluation. The proceesed images will be saved to the location specified in `<PROCESSED_BDD_IMAGES_FOLDER>`
57
+ ```
58
+ python preprocess_silver_geode_bdd100k_food_rec.py --annotation_file <FOLDER_WITH_SILVER_ANNOTATIONS>/silver_bdd100k_merged_test.json --raw_images_folder <RAW_BDD_IMAGES_FOLDER> --processed_images_folder <PROCESSED_BDD_IMAGES_FOLDER> --dataset_name bdd100k
59
+ ```
60
+
61
+ #### Food Recognition Challenge 2022
62
+
63
+ 1. Download data with raw images from the [website](https://www.aicrowd.com/challenges/food-recognition-benchmark-2022). Download `[Round 2] public_validation_set_2.0.tar.gz` file.
64
+ 2. Extract the downloaded file to a location, say `<RAW_FOOD_IMAGES_FOLDER>`
65
+ 3. Run the below command to pre-process the images and prepare for evaluation. The proceesed images will be saved to the location specified in `<PROCESSED_FOOD_IMAGES_FOLDER>`
66
+ ```
67
+ python preprocess_silver_geode_bdd100k_food_rec.py --annotation_file <FOLDER_WITH_SILVER_ANNOTATIONS>/silver_food_rec_merged_test.json --raw_images_folder <RAW_FOOD_IMAGES_FOLDER> --processed_images_folder <PROCESSED_FOOD_IMAGES_FOLDER> --dataset_name food_rec
68
+ ```
69
+
70
+ #### iNaturalist
71
+
72
+ The processed images needed for evaluation can be downloaded from [Roboflow](https://universe.roboflow.com/sa-co-silver/inaturalist-2017/) OR follow the below steps to prepare the processed images.
73
+
74
+ 1. Run the below command to download, extract images in `<RAW_INATURALIST_IMAGES_FOLDER>` and prepare them for evaluation. The proceesed images will be saved to the location specified in `<PROCESSED_INATURALIST_IMAGES_FOLDER>`
75
+ ```
76
+ python download_inaturalist.py --raw_images_folder <RAW_INATURALIST_IMAGES_FOLDER> --processed_images_folder <PROCESSED_INATURALIST_IMAGES_FOLDER>
77
+ ```
78
+
79
+ #### Fathomnet
80
+
81
+ The processed images needed for evaluation can be downloaded from [Roboflow](https://universe.roboflow.com/sa-co-silver/fathomnet-kmz5d/) OR follow the below steps to prepare the processed images.
82
+
83
+ 1. Install the FathomNet API
84
+ ```
85
+ pip install fathomnet
86
+ ```
87
+
88
+ 2. Run the below command to download the images and prepare for evaluation. The proceesed images will be saved to the location specified in `<PROCESSED_BDD_IMAGES_FOLDER>`
89
+ ```
90
+ python download_fathomnet.py --processed_images_folder <PROCESSED_BFATHOMNET_IMAGES_FOLDER>
91
+ ```
92
+
93
+ ### Frame Datasets
94
+
95
+ These datasets correspond to annotations for individual frames coming from videos. The file `CONFIG_FRAMES.yaml` is used to unify the downloads for the datasets, as explained below.
96
+
97
+ Before following the other dataset steps, update `CONFIG_FRAMES.yaml` with the correct `path_annotations` path where the annotation files are.
98
+
99
+ #### DROID
100
+
101
+ The processed frames needed for evaluation can be downloaded from [Roboflow](https://universe.roboflow.com/sa-co-silver/droid-cfual/) OR follow the below steps to prepare the processed frames.
102
+
103
+ 1. Install the gsutil package:
104
+ ```bash
105
+ pip install gsutil
106
+ ```
107
+ 2. Modify the `droid_path` variable in `CONFIG_FRAMES.yaml`. This is the path where the DROID data will be downloaded.
108
+ 3. _\[Optional\] Update the variable `remove_downloaded_videos_droid` to (not) remove the videos after the frames have been extracted.
109
+ 4. Download the data:
110
+ ```bash
111
+ python download_videos.py droid
112
+ ```
113
+ 5. Extract the frames:
114
+ ```bash
115
+ python extract_frames.py droid
116
+ ```
117
+
118
+ See the [DROID website](https://droid-dataset.github.io/droid/the-droid-dataset#-using-the-dataset) for more information.
119
+
120
+ #### SA-V
121
+
122
+ The processed frames needed for evaluation can be downloaded from [Roboflow](https://universe.roboflow.com/sa-co-silver/sa-v) OR follow the below steps to prepare the processed frames.
123
+
124
+ 1. Follow instructions in the [Segment Anything official website](https://ai.meta.com/datasets/segment-anything-video-downloads/) to obtain access to the download links (they are dynamic links).
125
+ 2. Update `CONFIG_FRAMES.yaml`:
126
+ - Update the `sav_path` variable, where the frames will be saved.
127
+ - Update the `sav_videos_fps_6_download_path` variable. Copy paste the path corresponding to the `videos_fps_6.tar` in the list that you obtained in step 1.
128
+ - _\[Optional\]_ Update the variable `remove_downloaded_videos_sav` to (not) remove the videos after the frames have been extracted.
129
+ 3. Download the videos:
130
+ ```bash
131
+ python download_videos.py sav
132
+ ```
133
+ 4. Extract the frames:
134
+ ```
135
+ python extract_frames.py sav
136
+ ```
137
+
138
+ #### Ego4D
139
+
140
+ The processed frames needed for evaluation can be downloaded from [Roboflow](https://universe.roboflow.com/sa-co-silver/ego4d-w7fiu/) OR follow the below steps to prepare the processed frames.
141
+
142
+ 1. Review and accept the license agreement in the [official Ego4D website](https://ego4d-data.org/docs/start-here/#license-agreement).
143
+ 2. Configure AWS credentials. Run:
144
+ ```bash
145
+ pip install awscli
146
+ aws configure
147
+ ```
148
+ and copy the values shown in the email you received after step 1 (you can leave "region name" and "output format" empty). You can verify that the variables were set up correctly:
149
+ ```bash
150
+ cat ~/.aws/credentials
151
+ ```
152
+ 3. Install the Ego4D library:
153
+ ```bash
154
+ pip install ego4d
155
+ ```
156
+ 4. Update `CONFIG_FRAMES.yaml`:
157
+ - Set up AWS credentials following the instructions in the email you received after step 2. Modify the following variables: `aws_access_key_id` and `aws_secret_access_key`.
158
+ - Update the `ego4d_path` variable, where the frames will be saved.
159
+ - _\[Optional\]_ Update the variable `remove_downloaded_videos_ego4d` to (not) remove the videos after the frames have been extracted..
160
+ 5. Download the `clips` subset of the Ego4D dataset:
161
+ ```python
162
+ python download_videos.py ego4d
163
+ ```
164
+ 6. Extract the frames:
165
+ ```
166
+ python extract_frames.py ego4d
167
+ ```
168
+
169
+ See the [official CLI](https://ego4d-data.org/docs/CLI/) and the [explanation about the videos](https://ego4d-data.org/docs/data/videos/) for more information.
170
+
171
+ #### YT1B
172
+
173
+ The processed frames needed for evaluation can be downloaded from [Roboflow](https://universe.roboflow.com/sa-co-silver/yt-temporal-1b/) OR follow the below steps to prepare the processed frames.
174
+
175
+ 1. Install the yt-dlp library:
176
+ ```bash
177
+ python3 -m pip install -U "yt-dlp[default]"
178
+ ```
179
+ 2. Create a `cookies.txt` file following the instructions from yt-dlp [exporting-youtube-cookies](https://github.com/yt-dlp/yt-dlp/wiki/Extractors#exporting-youtube-cookies) and [pass-cookies-to-yt-dlp](https://github.com/yt-dlp/yt-dlp/wiki/FAQ#how-do-i-pass-cookies-to-yt-dlp). This is required to download youtube videos. Then, update the path for that file in the `CONFIG_FRAMES.yaml` file, in the variable `cookies_path`.
180
+ 3. Update `CONFIG_FRAMES.yaml`:
181
+ - Update the `yt1b_path`, where the frames will be saved.
182
+ - _\[Optional\]_ Some YouTube videos may not be available on YouTube anymore. Set `update_annotation_yt1b` to `True` in `CONFIG_FRAMES.yaml` to remove the annotations corresponding to such videos. Note that the evaluations will not be directly comparable with other reported evaluations.
183
+ - _\[Optional\]_ Update the variable `remove_downloaded_videos_yt1b` to (not) remove the videos after the frames have been extracted.
184
+ 4. Run the following code to download the videos:
185
+ ```
186
+ python download_videos.py yt1b
187
+ ```
188
+ 5. Extract the frames:
189
+ ```
190
+ python extract_frames.py yt1b
191
+ ```
192
+
193
+ # Usage
194
+ ## Visualization
195
+
196
+ - Visualize GT annotations: [saco_gold_silver_vis_example.ipynb](https://github.com/facebookresearch/sam3/blob/main/examples/saco_gold_silver_vis_example.ipynb)
197
+
198
+ ## Run evaluation
199
+
200
+ The official metric for SA-Co/Silver is cgF1. Please refer to the SAM3 paper for details.
201
+ Unlike Gold, the silver subset only has a single annotation per image. Therefore, the performance may be underestimated, because the model may be wrongly penalized for choosing an interpretation which is valid but different from that of the human annotator.
202
+
203
+ ### Evaluate SAM3
204
+
205
+ We provide inference configurations to reproduce the evaluation of SAM3.
206
+ First, please edit the file [eval_base.yaml](https://github.com/facebookresearch/sam3/blob/main/sam3/train/configs/eval_base.yaml) with the paths where you downloaded the images and annotations above.
207
+
208
+ There are 10 subsets and as many configurations to be run.
209
+ Let's take the first subset as an example. The inference can be run locally using the following command (you can adjust the number of gpus):
210
+ ```bash
211
+ python sam3/train/train.py -c configs/silver_image_evals/sam3_gold_image_bdd100k.yaml --use-cluster 0 --num-gpus 1
212
+ ```
213
+ The predictions will be dumped in the folder specified in eval_base.yaml.
214
+
215
+ We also provide support for SLURM-based cluster inference. Edit the eval_base.yaml file to reflect your slurm configuration (partition, qos, ...), then run
216
+
217
+ ```bash
218
+ python sam3/train/train.py -c configs/silver_image_evals/sam3_gold_image_bdd100k.yaml --use-cluster 1
219
+ ```
220
+
221
+ ### Offline evaluation
222
+
223
+ If you have the predictions in the COCO result format (see [here](https://cocodataset.org/#format-results)), then we provide scripts to easily run the evaluation.
224
+
225
+ For an example on how to run the evaluator on all subsets and aggregate results, see the following notebook: [saco_gold_silver_eval_example.ipynb](https://github.com/facebookresearch/sam3/blob/main/examples/saco_gold_silver_eval_example.ipynb)
226
+
227
+ If you have a prediction file for a given subset, you can run the evaluator specifically for that one using the standalone script. Example:
228
+ ```bash
229
+ python scripts/eval/standalone_cgf1.py --pred_file /path/to/coco_predictions_segm.json --gt_files /path/to/annotations/silver_bdd100k_merged_test.json
230
+ ```
231
+
232
+ # Results
233
+ <table style="border-color:black;border-style:solid;border-width:1px;border-collapse:collapse;border-spacing:0;text-align:right" class="tg"><thead>
234
+ <tr style="text-align:center">
235
+ <th></th>
236
+ <th colspan="3">Average</th>
237
+ <th colspan="3">BDD100k</th>
238
+ <th colspan="3">Droids</th>
239
+ <th colspan="3">Ego4d</th>
240
+ <th colspan="3">Food Rec</th>
241
+ <th colspan="3">Geode</th>
242
+ <th colspan="3">iNaturalist</th>
243
+ <th colspan="3">Nga Art</th>
244
+ <th colspan="3">SAV</th>
245
+ <th colspan="3">YT1B</th>
246
+ <th colspan="3">Fathomnet</th>
247
+ </tr></thead>
248
+ <tbody>
249
+ <tr>
250
+ <td></td>
251
+ <td>cgF1</td>
252
+ <td>IL_MCC</td>
253
+ <td>PmF1</td>
254
+ <td>CGF1</td>
255
+ <td>IL_MCC</td>
256
+ <td>pmF1</td>
257
+ <td>CGF1</td>
258
+ <td>IL_MCC</td>
259
+ <td>pmF1</td>
260
+ <td>CGF1</td>
261
+ <td>IL_MCC</td>
262
+ <td>pmF1</td>
263
+ <td>CGF1</td>
264
+ <td>IL_MCC</td>
265
+ <td>pmF1</td>
266
+ <td>CGF1</td>
267
+ <td>IL_MCC</td>
268
+ <td>pmF1</td>
269
+ <td>CGF1</td>
270
+ <td>IL_MCC</td>
271
+ <td>pmF1</td>
272
+ <td>CGF1</td>
273
+ <td>IL_MCC</td>
274
+ <td>pmF1</td>
275
+ <td>CGF1</td>
276
+ <td>IL_MCC</td>
277
+ <td>pmF1</td>
278
+ <td>CGF1</td>
279
+ <td>IL_MCC</td>
280
+ <td>pmF1</td>
281
+ <td>CGF1</td>
282
+ <td>IL_MCC</td>
283
+ <td>pmF1</td>
284
+ </tr>
285
+ <tr>
286
+ <td>gDino-T</td> <td>3.09</td> <td>0.12</td> <td>19.75</td> <td>3.33</td> <td>0.17</td> <td>19.54</td> <td>4.26</td> <td>0.15</td> <td>28.38</td> <td>2.87</td> <td>0.1</td>
287
+ <td>28.72</td> <td>0.69</td> <td>0.05</td> <td>13.88</td> <td>9.61</td> <td>0.24</td> <td>40.03</td> <td>0</td> <td>0</td> <td>1.97</td> <td>1.31</td> <td>0.09</td>
288
+ <td>14.57</td> <td>5.18</td> <td>0.19</td> <td>27.25</td> <td>3.6</td> <td>0.16</td> <td>22.5</td> <td>0</td> <td>0</td> <td>0.64</td>
289
+ </tr>
290
+ <tr>
291
+ <td>OWLv2*</td> <td>11.23</td> <td>0.32</td> <td>31.18</td> <td>14.97</td> <td>0.46</td> <td>32.34</td> <td>10.84</td> <td>0.36</td> <td>30.1</td> <td>7.36</td> <td>0.23</td>
292
+ <td>31.99</td> <td>19.35</td> <td>0.44</td> <td>43.98</td> <td>27.04</td> <td>0.5</td> <td>54.07</td> <td>3.92</td> <td>0.14</td> <td>27.98</td> <td>8.05</td> <td>0.31</td>
293
+ <td>25.98</td> <td>10.59</td> <td>0.32</td> <td>33.1</td> <td>10.15</td> <td>0.38</td> <td>26.7</td> <td>0.04</td> <td>0.01</td> <td>5.57</td>
294
+ </tr>
295
+ <tr>
296
+ <td>OWLv2</td> <td>8.18</td> <td>0.23</td> <td>32.55</td> <td>8.5</td> <td>0.31</td> <td>27.79</td> <td>7.21</td> <td>0.25</td> <td>28.84</td> <td>5.64</td> <td>0.18</td>
297
+ <td>31.35</td> <td>14.18</td> <td>0.32</td> <td>44.32</td> <td>13.04</td> <td>0.28</td> <td>46.58</td> <td>3.62</td> <td>0.1</td> <td>36.23</td> <td>7.22</td> <td>0.25</td>
298
+ <td>28.88</td> <td>10.86</td> <td>0.32</td> <td>33.93</td> <td>11.7</td> <td>0.35</td> <td>33.43</td> <td>-0.14</td> <td>-0.01</td> <td>14.15</td>
299
+ </tr>
300
+ <tr>
301
+ <td>LLMDet-L</td> <td>6.73</td> <td>0.17</td> <td>28.19</td> <td>1.69</td> <td>0.08</td> <td>19.97</td> <td>2.56</td> <td>0.1</td> <td>25.59</td> <td>2.39</td>
302
+ <td>0.08</td> <td>29.92</td> <td>0.98</td> <td>0.06</td> <td>16.26</td> <td>20.82</td> <td>0.37</td> <td>56.26</td> <td>27.37</td> <td>0.46</td> <td>59.5</td>
303
+ <td>2.17</td> <td>0.13</td> <td>16.68</td> <td>5.37</td> <td>0.19</td> <td>28.26</td> <td>3.73</td> <td>0.16</td> <td>23.32</td> <td>0.24</td> <td>0.04</td> <td>6.1</td>
304
+ </tr>
305
+ <tr>
306
+ <td>Gemini 2.5</td> <td>9.67</td> <td>0.19</td> <td>45.51</td> <td>5.83</td> <td>0.19</td> <td>30.66</td> <td>5.61</td> <td>0.14</td> <td>40.07</td>
307
+ <td>0.38</td> <td>0.01</td> <td>38.14</td> <td>10.92</td> <td>0.24</td> <td>45.52</td> <td>18.28</td> <td>0.26</td> <td>70.29</td> <td>26.57</td> <td>0.36</td>
308
+ <td>73.81</td> <td>8.18</td> <td>0.2</td> <td>40.91</td> <td>9.48</td> <td>0.22</td> <td>43.1</td> <td>8.66</td> <td>0.23</td> <td>37.65</td> <td>2.8</td>
309
+ <td>0.08</td> <td>34.99</td>
310
+ </tr>
311
+ <tr> <td>SAM3</td> <td>49.57</td> <td>0.76</td> <td>65.17</td> <td>46.61</td> <td>0.78</td> <td>60.13</td> <td>45.58</td> <td>0.76</td>
312
+ <td>60.35</td> <td>38.64</td> <td>0.62</td> <td>62.56</td> <td>52.96</td> <td>0.79</td> <td>67.21</td> <td>70.07</td> <td>0.89</td>
313
+ <td>78.73</td> <td>65.8</td> <td>0.82</td> <td>80.67</td> <td>38.06</td> <td>0.66</td> <td>57.62</td> <td>44.36</td> <td>0.67</td>
314
+ <td>66.05</td> <td>42.07</td> <td>0.72</td> <td>58.36</td> <td>51.53</td> <td>0.86</td> <td>59.98</td>
315
+ </tr>
316
+ </tbody></table>
317
+
318
+ # Annotation format
319
+
320
+ The annotation format is derived from [COCO format](https://cocodataset.org/#format-data). Notable data fields are:
321
+
322
+ - `images`: a `list` of `dict` features, contains a list of all image-NP pairs. Each entry is related to an image-NP pair and has the following items.
323
+ - `id`: an `int` feature, unique identifier for the image-NP pair
324
+ - `text_input`: a `string` feature, the noun phrase for the image-NP pair
325
+ - `file_name`: a `string` feature, the relative image path in the corresponding data folder.
326
+ - `height`/`width`: dimension of the image
327
+ - `is_instance_exhaustive`: Boolean (0 or 1). If it's 1 then all the instances are correctly annotated. For instance segmentation, we only use those datapoints. Otherwise, there may be either missing instances or crowd segments (a segment covering multiple instances)
328
+ - `is_pixel_exhaustive`: Boolean (0 or 1). If it's 1, then the union of all masks cover all pixels corresponding to the prompt. This is weaker than instance_exhaustive since it allows crowd segments. It can be used for semantic segmentation evaluations.
329
+
330
+ - `annotations`: a `list` of `dict` features, containing a list of all annotations including bounding box, segmentation mask, area etc.
331
+ - `image_id`: an `int` feature, maps to the identifier for the image-np pair in images
332
+ - `bbox`: a `list` of float features, containing bounding box in [x,y,w,h] format, normalized by the image dimensions
333
+ - `segmentation`: a dict feature, containing segmentation mask in RLE format
334
+ - `category_id`: For compatibility with the coco format. Will always be 1 and is unused.
335
+ - `is_crowd`: Boolean (0 or 1). If 1, then the segment overlaps several instances (used in cases where instances are not separable, for e.g. due to poor image quality)
336
+
337
+ - `categories`: a `list` of `dict` features, containing a list of all categories. Here, we provide the category key for compatibility with the COCO format, but in open-vocabulary detection we do not use it. Instead, the text prompt is stored directly in each image (text_input in images). Note that in our setting, a unique image (id in images) actually corresponds to an (image, text prompt) combination.
338
+
339
+
340
+ For `id` in images that have corresponding annotations (i.e. exist as `image_id` in `annotations`), we refer to them as a "positive" NP. And, for `id` in `images` that don't have any annotations (i.e. they do not exist as `image_id` in `annotations`), we refer to them as a "negative" NP.
341
+
342
+ A sample annotation from DROID domain looks as follows:
343
+
344
+ #### images
345
+
346
+ ```
347
+ [
348
+ {
349
+ "id": 10000000,
350
+ "file_name": "AUTOLab_failure_2023-07-07_Fri_Jul__7_18:50:36_2023_recordings_MP4_22008760/00002.jpg",
351
+ "text_input": "the large wooden table",
352
+ "width": 1280,
353
+ "height": 720,
354
+ "queried_category": "3",
355
+ "is_instance_exhaustive": 1,
356
+ "is_pixel_exhaustive": 1
357
+ }
358
+ ]
359
+ ```
360
+
361
+ #### annotations
362
+
363
+ ```
364
+ [
365
+ {
366
+ "area": 0.17324327256944444,
367
+ "id": 1,
368
+ "image_id": 10000000,
369
+ "source": "created by SAM3",
370
+ "bbox": [
371
+ 0.03750000149011612,
372
+ 0.5083333253860474,
373
+ 0.8382812738418579,
374
+ 0.49166667461395264
375
+ ],
376
+ "segmentation": {
377
+ "counts": "[^R11]f03O0O100O2N100O1O100O100O100O100O1O100O100O100O100O100O1O10000O1O10000O1O100O10000O1O100O100O100O100O100O100O100O100O100O100O1O100O100O10000O100O100O100O101N100O1O011O0O1O101OO0010O100O1O100O2OO0100O100O100O100O100O10000O100O100O1O100O10000O1O100O100O100O10000O1O100O100O100O10000O1O10000O1O100O100O100O100O100O100O1O100O100O100O100O100O100O100O100O100O100O100O100O100O100O10000O100O100O1O100O10000O100O100O100O100O1O100O100O100O100O100O100O10O0100O100O2O000O1O10000O1O10000O100O100O100O1O100O100O100O100O100O100O100O100O100O100O100O100O1O100O100O100O10000O100O100O100O100O100O100O100O100O100O100O100O100O100O10000O100O100O100O100O100O100O1O10000O1O10000O100O1O100O100O100O100O100O100O100O100O10000O1O100O100O100O100O1O10000O10\\MP@hNo?W1U@gNk?X1W@gNh?Y1Z@fNf?Y1\\@fNc?[1^@dNb?[1`@dN_?]1b@bN^?]1e@aNZ?_1i@_NW?a1l@\\NS?d1RAXNn>h1TAVNk>k1VATNj>k1XATNg>m1YASNg>m1YASNf>m1[ASNe>m1[ASNd>m1]ASNc>m1]ASNb>l1`ATN`>i1cAWN\\>d1jA\\NV>_1oAaNP>^1RBbNn=\\1TBdNk=\\1VBdNj=1`@dNGO02P2Z1h=L_AfNj0^1g=FmC;R<EoC;Q<DPD<o;DRD<n;DQD=n;DjAnN?^1g=DhAQO?\\1h=DhAUO<W1l=EeAZO:R1P>F]ABa0h0Q>Hd@lNDV1e17S>k1iAWNW>i1hAXNW>j1gAWNY>i1fAXNY>j1eAWNZ>k1dAVN\\>k1bAVN^>k1`AVN_>l1`ATN`>m1^ATNa>o1]AQNc>P2[AQNd>P2\\APNd>Q2[AoMd>R2[AoMd>R2\\AnMd>S2ZAnMe>S2[AmMe>T2YAmMf>T2YAmMg>T2WAmMh>U2VAlMj>U2TAlMl>U2PAnMo>U2j@PNV?e4O100O100O100O100O100O100O100O100O100O100O100O100O101N100O100O10O0100O100O100O100O100O100O1000000O1000000O100O100O1O1O1O100O100O1O100O100O100O100O100O100O100O100O100O1O100O100O100O100O100O10000O100O1O100O100O100O100O100O100OkK_B]Oa=7oBEP=4YCKg<1^CNa<1bCN^<OeC1[<LhC4W<KlC4S<KoC5Q<JPD6o;JRD6n;JSD5l;LTD4l;LTD4k;MUD3k;MUD4j;LWD2i;OWD1i;OWD1h;0XD0h;1WDOh;2XDOg;1ZDNe;3[DMe;3[DNc;3]DLd;4\\DLc;5]DKb;7]DIc;7^DHa;9_DGa;9_DG`;:`DF`;;_DE`;<`DCa;=^DDa;=_DC`;>_DCa;>^DBb;[OUCiMW1n2c;YO[CeMn0V3g;TO^CeMf0[3k;POaCdM>b3Q<iNbCfM7f3V<dNeCeMKQ4`<YNgCfMAX4g<RNiCk2W<SMlCl2S<TMnCl2R<SMoCm2Q<RMQDm2n;TMRDl2n;SMTDl2k;UMUDk2k;UMVDj2i;VMXDj2h;VMXDj2g;VM[Di2e;VM\\Dj2c;VM^Dj2b;TMaDk2^;PMhDP3X;aL`CjM`1e5o:\\L^Ed3b:WLdEh3[:nKPFR4P:jKTFV4k9hKXFX4h9hKXFX4g9hKYFY4f9hKZFX4f9hKZFX4e9iKZFW4g9iKXFX4g9iKPElN\\O\\5c;iKeDYOEo4f;iK]DAJh4g;iKTDJ3^4i;jKkCO;X4i;hMVDX2j;hMUDY2j;iMUDW2k;iMTDW2l;kMSDU2m;kMRDV2m;lMRDT2n;mMPDT2P<mMoCS2P<oMnCR2R<V4O100O100OiInCR2Q<kMWDQ2i;kM_DQ2`;lMoDi1Q;TNWEg1h:XN^Ed1a:\\NdE`1\\:^NjE^1U:aNPF]1o9aNUF]1k9bNXF\\1g9dN]FY1c9fN`FX1_9hNdFV1\\9iNhFT1W9lNmFQ1S9nNQGo0n8QOTGn0l8ROWGk0h8UO[Gi0e8VO^Gh0a8YO`Gf0`8YOcGe0\\8\\OeGc0[8\\OiGa0V8@lG>T8AnG>Q8BQH=o7CRH<m7DVH:j7FWH9h7HYH7g7H[H7d7J^H4b7L^H4b7K`H4_7MbH2^7NcH1\\7OfH0Z70gHOX72iHMW73jHLV74jHLU74mHKS75mHKS75nHJR76oHIQ77oHIR7jMkDP1U4U1S7RM_D0h0g1f3W1^8hNcGV1_8iNaGX1_8gNaGY1`8fNaGY1_8gNaGY1`8fNaGY1_8gNaGY1`8fNaGY1_8gNaGY1`8fNaGY1_8gNaGY1_8gNaGY1_8gNbGX1_8gNaGY1_8gNaGY1_8fNbGY1`8fNaGY1_8gNaGY1_8gNaGY1_8gNaGY1_8gNbGX1^8hNbGX1^8hNbGX1^8hNbGX1^8hNbGX1^8iNbGV1^8jNbGV1^8jNbGV1^8jNbGV1^8jNbGV1^8jNbGV1^8jNbGV1]8lNbGT1^8lNcGS1\\8nNdGR1\\8nNdGR1[8oNeGQ1Z8POfGP1X8SOhGl0W8UOiGk0U8WOkGi0S8YOmGg0P8\\OPHd0n7_ORH`0l7BTH>j7DVH<g7HYH7d7L\\H4b7N^H2`71_HO^74bHL[77eHIY7:fHFX7<hHDV7>jHBT7a0kH_OT7b0mH]OR7d0nH\\OQ7f0nH]OQ7g0oHZOQ7g0oHYOQ7h0nHXOR7h0nHXOR7h0nHXOR7i0mHWOT7h0kHYOU7h0jHXOV7h0iHYOW7g0iHYOW7h0hHXOY7g0fHZOZ7f0eH[O\\7e0cHhNlKSNa;U3bHeNSLTN\\;W3_HbN]LRNU;\\3]H^Nb8c1\\G\\Ng8c1XG\\Nj8e1TGZNo8e1PGYNS9h1lFUNW9l1gFRN]9m1bFRN`9o1^FPNe9o1[FoMg9R2WFnMj9S2TFmMn9R2RFnMn9S2PFmMR:R2nEmMS:T2kEmMU:T2jEkMX:T2gEmMY:T2fElMZ:U2dEkM^:T2aEmM_:T2`ElM`:U2^ElMc:S2\\EmMe:T2YEmMg:T2WEmMj:S2UEmMk:T2SEmMn:S2PEnMP;S2nDoMQ;R2mDoMT;Q2kDoMU;R2iDoMX;Q2fDQNY;P2eDQN[;P2cDQN^;o1`DSN_;n1^DTNc;l1[DVNd;k1ZDVNg;j1WDXNh;j1UDWNk;j1SDWNn;i1oCZNP<h1mCYNS<h1kCZNU<g1gC\\NX<e1fC\\N[<d1cC^N\\<d1aC^N_<c1^C_Na<b1\\CaNc<a1ZCaNf<_1XCcNg<_1UCeNj<^1oBfNP=]1iBiN?gL^;e4hCkNf0dLb;`8YDcGg;^8VDdGk;^8mChGR<_8bCfG_<U900001N101O00001O001O00001O00001O0O2N1O1O2N1O2N100O2N1O1O2N1O2N1O1O2N1O2M200O2M2O2N1N2O2N1N3N1O1N3N1N3M2O2kMkAkKW>Q4RBiKo=8^AR2j0`Mk=:aAP2i0bMh==eAj1g0eMf=?hAh1f0eMd=?lAg1c0gMc=`0nAe1c0hMa=a0oAd1b0iM`=a0QBc1c0iM]=c0SB`1d0iM\\=e0SB^1e0jMY=g0VB[1e0jMV=k0WBW1V`0gNn_OT1T`0lNo_Oo0S`0POS@i0P`0VOT@d0n?\\OT@`0n?@T@<o?CR@^OUN6ka0=P@XO\\N6ga0a0j@WOY?i0X3O001O00010O00001O0010O0001O00010O001O00001O001O01O01O00001O001O000O2O0O2O0O2N1O2N1O2M3MYl51fSJ3L3O1O100O1O100000000001O000000001O00000000001O01OO1000000000001O000001O000O10000000000000000O10000O10000O10000O100O1O100O1O1O1O1O1O1N2O1O1O1O1O1O1O1O1O1O1O1O1O1O1O1O1N2O1O1O1O1O1O1O100O100N21O00001O001O2N1O1O2N1O2N1O2M3N4IVT_3",
378
+ "size": [
379
+ 720,
380
+ 1280
381
+ ]
382
+ },
383
+ "category_id": 1,
384
+ "iscrowd": 0
385
+ }
386
+ ]
387
+ ```
388
+
389
+ ### Data Stats
390
+
391
+ Here are the stats for the 10 annotation domains. The # Image-NPs represent the total number of unique image-NP pairs including both “positive” and “negative” NPs.
392
+
393
+
394
+ | Domain | # Image-NPs | # Image-NP-Masks|
395
+ |--------------------------|--------------| ----------------|
396
+ | BDD100k | 5546 | 13210 |
397
+ | DROID | 9445 | 11098 |
398
+ | Ego4D | 12608 | 24049 |
399
+ | MyFoodRepo-273 | 20985 | 28347 |
400
+ | GeoDE | 14850 | 7570 |
401
+ | iNaturalist-2017 | 1439051 | 48899 |
402
+ | National Gallery of Art | 22294 | 18991 |
403
+ | SA-V | 18337 | 39683 |
404
+ | YT-Temporal-1B | 7816 | 12221 |
405
+ | Fathomnet | 287193 | 14174 |
OVOW/third_party/sam3/scripts/eval/silver/download_fathomnet.py ADDED
@@ -0,0 +1,64 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ # Copyright (c) Meta Platforms, Inc. and affiliates. All Rights Reserved
2
+
3
+ # pyre-unsafe
4
+ import argparse
5
+ import json
6
+ import os
7
+ from multiprocessing import Pool
8
+ from pathlib import Path
9
+
10
+ import requests
11
+ from fathomnet.api import images
12
+ from tqdm import tqdm
13
+
14
+
15
+ def download_imgs(args, image_uuids):
16
+ flag = 0
17
+ for uuid in tqdm(image_uuids, desc="Downloading images"):
18
+ image = images.find_by_uuid(uuid)
19
+ file_name = (
20
+ Path(args.processed_images_folder)
21
+ / f"{image.uuid}.{image.url.split('.')[-1]}"
22
+ )
23
+ if not file_name.exists():
24
+ try:
25
+ resp = requests.get(image.url, stream=True)
26
+ resp.raise_for_status()
27
+ with open(file_name, "wb") as f:
28
+ for chunk in resp.iter_content(chunk_size=1024):
29
+ f.write(chunk)
30
+ flag += 1
31
+ except requests.exceptions.RequestException as e:
32
+ print(f"Error downloading {image.url}: {e}")
33
+ print(f"Downloaded {flag} new images to {args.processed_images_folder}")
34
+
35
+
36
+ def main():
37
+ parser = argparse.ArgumentParser(description="Download images from FathomNet")
38
+ parser.add_argument("--processed_images_folder", help="Path to downloaded images")
39
+ parser.add_argument(
40
+ "--image-uuids",
41
+ default="fathomnet_image_uuids.json",
42
+ help="Path to JSON file containing image uuids to download",
43
+ )
44
+ parser.add_argument(
45
+ "--num-procs", type=int, default=16, help="Number of parallel processes"
46
+ )
47
+ args = parser.parse_args()
48
+
49
+ with open(args.image_uuids, "r") as f:
50
+ all_uuids = json.load(f)
51
+
52
+ Path(args.processed_images_folder).mkdir(parents=True, exist_ok=True)
53
+
54
+ chunk_size = len(all_uuids) // args.num_procs
55
+ chunks = [
56
+ all_uuids[i : i + chunk_size] for i in range(0, len(all_uuids), chunk_size)
57
+ ]
58
+
59
+ with Pool(processes=args.num_procs) as pool:
60
+ pool.starmap(download_imgs, [(args, chunk) for chunk in chunks])
61
+
62
+
63
+ if __name__ == "__main__":
64
+ main()
OVOW/third_party/sam3/scripts/eval/silver/download_inaturalist.py ADDED
@@ -0,0 +1,83 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ # Copyright (c) Meta Platforms, Inc. and affiliates. All Rights Reserved
2
+
3
+ # pyre-unsafe
4
+ import argparse
5
+ import json
6
+ import shutil
7
+ import subprocess
8
+ import sys
9
+ import tarfile
10
+ from pathlib import Path
11
+
12
+ from tqdm import tqdm
13
+
14
+
15
+ def download_archive(url, dest_dir):
16
+ dest_dir = Path(dest_dir)
17
+ dest_dir.mkdir(parents=True, exist_ok=True)
18
+ archive_path = dest_dir / url.split("/")[-1]
19
+ if not archive_path.exists():
20
+ print(f"Downloading archive to {archive_path}...")
21
+ result = subprocess.run(["wget", "-O", str(archive_path), url])
22
+ if result.returncode != 0:
23
+ print("Download failed.")
24
+ sys.exit(1)
25
+ else:
26
+ print(f"Archive already exists at {archive_path}")
27
+ return archive_path
28
+
29
+
30
+ def extract_archive(archive_path, dest_dir):
31
+ print(f"Extracting {archive_path} to {dest_dir}...")
32
+ with tarfile.open(archive_path, "r:gz") as tar:
33
+ tar.extractall(path=dest_dir)
34
+ print("Extraction complete.")
35
+
36
+
37
+ def copy_images(subset_json, untar_dir, output_dir):
38
+ with open(subset_json, "r") as f:
39
+ image_dict = json.load(f)
40
+ output_dir = Path(output_dir)
41
+ output_dir.mkdir(parents=True, exist_ok=True)
42
+ for target_name, rel_path in tqdm(image_dict.items(), "Copying image subset"):
43
+ src = Path(untar_dir) / rel_path
44
+ dst = output_dir / target_name
45
+ if not src.exists():
46
+ print(f"Warning: Source image {src} does not exist, skipping.")
47
+ continue
48
+ shutil.copy2(src, dst)
49
+ print(f"Copied {len(image_dict)} images to {output_dir}")
50
+
51
+
52
+ def main():
53
+ parser = argparse.ArgumentParser(
54
+ description="Download, extract, and copy subset of iNaturalist images from archive."
55
+ )
56
+ parser.add_argument(
57
+ "--raw_images_folder", help="Path to downloaded and extract the archive"
58
+ )
59
+ parser.add_argument("--processed_images_folder", help="Path to processed images")
60
+ parser.add_argument(
61
+ "--subset-json",
62
+ default="inaturalist_image_subset.json",
63
+ help="Path to iNaturalist images subset",
64
+ )
65
+ parser.add_argument(
66
+ "--archive-url",
67
+ default="https://ml-inat-competition-datasets.s3.amazonaws.com/2017/train_val_images.tar.gz",
68
+ help="URL of the archive to download",
69
+ )
70
+ args = parser.parse_args()
71
+
72
+ dest_dir = Path(args.raw_images_folder)
73
+ images_dir = Path(args.processed_images_folder)
74
+
75
+ archive_path = download_archive(args.archive_url, dest_dir)
76
+ extract_archive(archive_path, dest_dir)
77
+
78
+ untar_dir = dest_dir / "train_val_images"
79
+ copy_images(args.subset_json, untar_dir, images_dir)
80
+
81
+
82
+ if __name__ == "__main__":
83
+ main()
OVOW/third_party/sam3/scripts/eval/silver/download_preprocess_nga.py ADDED
@@ -0,0 +1,142 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ # Copyright (c) Meta Platforms, Inc. and affiliates. All Rights Reserved
2
+
3
+ # pyre-unsafe
4
+ import argparse
5
+ import os
6
+ from functools import partial
7
+ from multiprocessing import Pool
8
+ from pathlib import Path
9
+
10
+ import numpy as np
11
+ import pandas as pd
12
+ import requests
13
+ import utils
14
+ from PIL import Image
15
+ from tqdm import tqdm
16
+
17
+ METADATA_FILE = "published_images.csv"
18
+ METADATA_URL = "https://raw.githubusercontent.com/NationalGalleryOfArt/opendata/refs/heads/main/data" # data/published_iamges.csv from https://github.com/NationalGalleryOfArt/opendata/tree/main
19
+ IMG_URL = "https://api.nga.gov/iiif/%s/full/%s/0/default.jpg"
20
+ METADATA_FOLDER = "metadata"
21
+ EXTENSION = ".jpg"
22
+
23
+
24
+ def download_metadata(annotation_folder):
25
+ output_folder = annotation_folder / METADATA_FOLDER
26
+ output_folder.mkdir(exist_ok=True)
27
+ url = f"{METADATA_URL}/{METADATA_FILE}"
28
+ print(url)
29
+ response = requests.get(url)
30
+ if response.status_code == 200:
31
+ with open(output_folder / METADATA_FILE, "wb") as f:
32
+ f.write(response.content)
33
+
34
+
35
+ def download_url(row):
36
+ if np.isnan(row.maxpixels) or (
37
+ row.maxpixels > row.width and row.maxpixels > row.height
38
+ ):
39
+ url = IMG_URL % (row.uuid, "full")
40
+ else:
41
+ url = IMG_URL % (row.uuid, f"!{row.maxpixels},{row.maxpixels}")
42
+ return url
43
+
44
+
45
+ def download_item(item, output_folder):
46
+ uuid, url = item
47
+ try:
48
+ if (output_folder / f"{uuid}{EXTENSION}").exists():
49
+ print("skipping", uuid, "already downloaded")
50
+ return
51
+ response = requests.get(url)
52
+ if response.status_code == 200:
53
+ with open(output_folder / f"{uuid}{EXTENSION}", "wb") as f:
54
+ f.write(response.content)
55
+ except:
56
+ print("errored", item)
57
+ return
58
+
59
+
60
+ def remove_non_compliant_image(item, output_folder):
61
+ uuid, max_pixels = item
62
+ if np.isnan(max_pixels):
63
+ return
64
+ if not (output_folder / f"{uuid}{EXTENSION}").exists():
65
+ return
66
+ img = Image.open(output_folder / f"{uuid}{EXTENSION}")
67
+ if img.width > max_pixels or img.height > max_pixels:
68
+ os.remove(output_folder / f"{uuid}{EXTENSION}") # delete image
69
+ return uuid
70
+
71
+
72
+ def reshape_image(rel_path, filename_size_map, output_folder):
73
+ w, h = filename_size_map[rel_path]
74
+ path = output_folder / f"{rel_path}"
75
+ img = Image.open(path)
76
+ if img.width != w or img.height != h:
77
+ new_size = (w, h)
78
+ resized_img = img.resize(new_size)
79
+ resized_img.save(path)
80
+
81
+
82
+ def main(args, workers=20):
83
+ raw_folder = Path(args.raw_images_folder)
84
+ processed_folder = Path(args.processed_images_folder)
85
+ utils.setup(raw_folder)
86
+ utils.setup(processed_folder)
87
+ uuids = utils.get_image_ids(args.annotation_file)
88
+ filename_size_map = utils.get_filename_size_map(args.annotation_file)
89
+ if not ((raw_folder / METADATA_FOLDER) / METADATA_FILE).exists():
90
+ download_metadata(raw_folder)
91
+
92
+ metadata = pd.read_csv((raw_folder / METADATA_FOLDER) / METADATA_FILE)
93
+ metadata["download_url"] = metadata.apply(download_url, axis=1)
94
+ available_uuids = list(uuids.intersection(set(metadata["uuid"].tolist())))
95
+ print(len(available_uuids), "available for download out of", len(uuids), "target")
96
+ url_data = list(
97
+ metadata.set_index("uuid")
98
+ .loc[available_uuids]
99
+ .to_dict()["download_url"]
100
+ .items()
101
+ )
102
+
103
+ download_single = partial(download_item, output_folder=(processed_folder))
104
+
105
+ print("Preparing to download", len(url_data), "items")
106
+ with Pool(20) as p:
107
+ for _ in tqdm(p.imap(download_single, url_data), total=len(url_data)):
108
+ continue
109
+ check_img_size = partial(
110
+ remove_non_compliant_image, output_folder=(processed_folder)
111
+ )
112
+ max_pixels_dict_all = metadata.set_index("uuid").to_dict()["maxpixels"]
113
+ max_pixels_dict = {item[0]: max_pixels_dict_all[item[0]] for item in url_data}
114
+ print("Checking all images within size constraints")
115
+ non_compliant = set()
116
+ with Pool(20) as p:
117
+ for each in tqdm(
118
+ p.imap(check_img_size, max_pixels_dict.items()), total=len(max_pixels_dict)
119
+ ):
120
+ if each is not None:
121
+ non_compliant.add(each)
122
+ print(len(non_compliant), "not compliant size, removed")
123
+
124
+ reshape_single = partial(
125
+ reshape_image,
126
+ filename_size_map=(filename_size_map),
127
+ output_folder=(processed_folder),
128
+ )
129
+ rel_paths = os.listdir(args.processed_images_folder)
130
+ print("Preparing to reshape", len(rel_paths), "items")
131
+ with Pool(20) as p:
132
+ for _ in tqdm(p.imap(reshape_single, rel_paths), total=len(rel_paths)):
133
+ continue
134
+
135
+
136
+ if __name__ == "__main__":
137
+ parser = argparse.ArgumentParser()
138
+ parser.add_argument("--annotation_file", help="Path to annotation file")
139
+ parser.add_argument("--raw_images_folder", help="Path to downloaded images")
140
+ parser.add_argument("--processed_images_folder", help="Path to processed images")
141
+ args = parser.parse_args()
142
+ main(args)
OVOW/third_party/sam3/scripts/eval/silver/download_videos.py ADDED
@@ -0,0 +1,261 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ # Copyright (c) Meta Platforms, Inc. and affiliates. All Rights Reserved
2
+
3
+ # pyre-unsafe
4
+ import ast
5
+ import concurrent.futures
6
+ import os
7
+ import shutil
8
+ import subprocess
9
+ import sys
10
+ from concurrent.futures import as_completed, ThreadPoolExecutor
11
+ from pathlib import Path
12
+
13
+ import yt_dlp
14
+ from utils import (
15
+ annotation_files,
16
+ config,
17
+ load_json,
18
+ run_command,
19
+ save_json,
20
+ update_annotations,
21
+ )
22
+
23
+
24
+ def construct_gcs_path(original_video):
25
+ """
26
+ Convert original_video string to GCS path.
27
+ Example:
28
+ 'AUTOLab_failure_2023-07-07_Fri_Jul__7_18:50:36_2023_recordings_MP4_22008760.mp4'
29
+ ->
30
+ 'gs://gresearch/robotics/droid_raw/1.0.1/AUTOLab/failure/2023-07-07/Fri_Jul__7_18:50:36_2023/recordings/MP4/22008760.mp4'
31
+ """
32
+ parts = original_video.split("_")
33
+ lab = parts[0]
34
+ failure = parts[1]
35
+ date = parts[2]
36
+ time = "_".join(parts[3:-3])
37
+ recordings = parts[-3]
38
+ mp4 = parts[-2]
39
+ file_id = parts[-1].split(".")[0]
40
+ gcs_path = (
41
+ f"gs://gresearch/robotics/droid_raw/1.0.1/"
42
+ f"{lab}/{failure}/{date}/{time}/{recordings}/{mp4}/{file_id}.mp4"
43
+ )
44
+ return gcs_path
45
+
46
+
47
+ def download_video(args):
48
+ gcs_path, dst_dir, json_file = args
49
+ # Ensure subdirectory exists
50
+ subdir = Path(dst_dir)
51
+ os.makedirs(subdir, exist_ok=True)
52
+ # Save file with its original name inside the subdir
53
+ print(json_file)
54
+ local_path = subdir / json_file
55
+ cmd = f'gsutil cp "{gcs_path}" "{local_path}"'
56
+ print(f"Running: {cmd}")
57
+ try:
58
+ run_command(cmd)
59
+ return (gcs_path, True, None)
60
+ except Exception as e:
61
+ return (gcs_path, False, str(e))
62
+
63
+
64
+ def download_youtube_video(youtube_id, output_path=None):
65
+ try:
66
+ if output_path is None:
67
+ output_path = os.path.join(
68
+ config["yt1b_path"], "downloaded_videos", f"video_{youtube_id}.mp4"
69
+ )
70
+ url = f"https://www.youtube.com/watch?v={youtube_id}"
71
+ if os.path.exists(output_path):
72
+ return youtube_id, None
73
+ format = "best[height<=720][fps<=30]/best[height<=720]/best" # 720p or lower, max 30fps
74
+ ydl_opts = {
75
+ "format": format,
76
+ "outtmpl": output_path,
77
+ "merge_output_format": "mp4",
78
+ "quiet": True,
79
+ "cookiefile": config["cookies_path"],
80
+ "socket_timeout": 60, # Increase timeout to 60 seconds (default is 10)
81
+ }
82
+ with yt_dlp.YoutubeDL(ydl_opts) as ydl:
83
+ ydl.download([url])
84
+ return youtube_id, None
85
+ except Exception as e:
86
+ return youtube_id, str(e)
87
+
88
+
89
+ def download_youtube():
90
+ all_videos_to_download = set()
91
+ for annotation_file in annotation_files["yt1b"]:
92
+ ann = load_json(os.path.join(config["path_annotations"], annotation_file))
93
+ for video_info in ann["images"]:
94
+ youtube_id = video_info["original_video"]
95
+ all_videos_to_download.add(youtube_id)
96
+
97
+ videos_to_download_still = all_videos_to_download
98
+ videos_downloaded = set()
99
+ videos_unavailable = set()
100
+ num_download_retries = 3
101
+ for _ in range(num_download_retries):
102
+ if len(videos_to_download_still) == 0:
103
+ break
104
+ videos_error = set()
105
+ with concurrent.futures.ThreadPoolExecutor() as executor:
106
+ futures = [
107
+ executor.submit(download_youtube_video, youtube_id)
108
+ for youtube_id in videos_to_download_still
109
+ ]
110
+ for future in concurrent.futures.as_completed(futures):
111
+ youtube_id, exception = future.result()
112
+ if exception is None:
113
+ videos_downloaded.add(youtube_id)
114
+ elif "unavailable" in exception or "members-only" in exception:
115
+ videos_unavailable.add(youtube_id)
116
+ else:
117
+ videos_error.add(youtube_id)
118
+ videos_to_download_still = (
119
+ all_videos_to_download - videos_downloaded - videos_unavailable
120
+ )
121
+ assert videos_to_download_still == videos_error
122
+
123
+ if len(videos_unavailable) + len(videos_to_download_still) > 0:
124
+ message = "Some videos are either no longer available on YouTube, or are set to private, or resulted in some other error. "
125
+ if config["update_annotation_yt1b"]:
126
+ message += "The unavailable videos will be ***REMOVED*** from the annotation file. This will make the test results NOT DIRECTLY COMPARABLE to other reported results."
127
+ print(message)
128
+ update_annotations("yt1b", videos_downloaded)
129
+ else:
130
+ message += "You may want to either re-try the download, or remove these videos from the evaluation json"
131
+ print(message)
132
+
133
+
134
+ def download_droid():
135
+ ann_dir = Path(config["path_annotations"])
136
+ dst_dir = Path(config["droid_path"]) / "downloaded_videos"
137
+ json_files = annotation_files["droid"]
138
+
139
+ download_tasks = []
140
+ original_videos = set()
141
+ for json_file in json_files:
142
+ json_path = ann_dir / json_file
143
+ data = load_json(json_path)
144
+ for img in data["images"]:
145
+ original_video = img["original_video"]
146
+ original_videos.add(original_video)
147
+
148
+ print(len(original_videos))
149
+ for original_video in original_videos:
150
+ gcs_path = construct_gcs_path(original_video)
151
+ download_tasks.append((gcs_path, dst_dir, original_video))
152
+
153
+ max_workers = min(16, len(download_tasks))
154
+ with ThreadPoolExecutor(max_workers=max_workers) as executor:
155
+ future_to_task = {
156
+ executor.submit(download_video, task): task for task in download_tasks
157
+ }
158
+ for future in as_completed(future_to_task):
159
+ gcs_path, success, error = future.result()
160
+ if not success:
161
+ print(f"Failed to download {gcs_path}: {error}")
162
+
163
+
164
+ def download_ego4d():
165
+ output_dir = os.path.join(config["ego4d_path"], "downloaded_videos")
166
+
167
+ ann_dir = Path(config["path_annotations"])
168
+ json_files = annotation_files["ego4d"]
169
+ original_videos = set()
170
+ for json_file in json_files:
171
+ json_path = ann_dir / json_file
172
+ data = load_json(json_path)
173
+ for img in data["images"]:
174
+ original_video = img["original_video"]
175
+ original_videos.add(original_video)
176
+
177
+ original_video_uids = [
178
+ video_uid.replace(".mp4", "") for video_uid in original_videos
179
+ ]
180
+ video_ids_download = original_video_uids
181
+ num_download_retries = 2
182
+ download_correct = False
183
+ message = ""
184
+ for _ in range(num_download_retries):
185
+ cmd = (
186
+ [
187
+ # "python", "-m", "ego4d.cli.cli",
188
+ "ego4d",
189
+ "--output_directory",
190
+ output_dir,
191
+ "--datasets",
192
+ "clips",
193
+ "--version",
194
+ "v1",
195
+ "--video_uids",
196
+ ]
197
+ + video_ids_download
198
+ + ["--yes"]
199
+ )
200
+
201
+ # Run the command
202
+ result = subprocess.run(cmd, capture_output=True, text=True)
203
+ message = result.stderr
204
+ if (
205
+ "RuntimeError: The following requested video UIDs could not be found in the manifest for version:"
206
+ in result.stderr
207
+ ):
208
+ not_findable_videos = ast.literal_eval(result.stderr.split("\n")[-2])
209
+ video_ids_download = [
210
+ video_uid
211
+ for video_uid in video_ids_download
212
+ if video_uid not in not_findable_videos
213
+ ]
214
+ else:
215
+ download_correct = True
216
+ break
217
+
218
+ if not download_correct:
219
+ print(f"There was an error downloading the Ego4D data: {message}")
220
+
221
+ if len(video_ids_download) != len(original_video_uids):
222
+ message = "Some videos are no longer available. "
223
+ if config["update_annotation_ego4d"]:
224
+ message += "The unavailable videos will be ***REMOVED*** from the annotation file. This will make the test results NOT DIRECTLY COMPARABLE to other reported results."
225
+ print(message)
226
+ update_annotations("ego4d", video_ids_download)
227
+ else:
228
+ message += "You may want to either re-try the download, or remove these videos from the evaluation json"
229
+ print(message)
230
+
231
+
232
+ def download_sav():
233
+ tar_url = config["sav_videos_fps_6_download_path"]
234
+ tar_file = "videos_fps_6.tar"
235
+ sav_data_dir = os.path.join(config["sav_path"], "downloaded_videos")
236
+ os.makedirs(sav_data_dir, exist_ok=True)
237
+
238
+ subprocess.run(["wget", tar_url, "-O", tar_file], cwd=sav_data_dir, check=True)
239
+ subprocess.run(["tar", "-xvf", tar_file], cwd=sav_data_dir, check=True)
240
+ subprocess.run(["rm", tar_file], cwd=sav_data_dir, check=True)
241
+
242
+
243
+ def main():
244
+ assert len(sys.argv) > 1, "You have to provide the name of the dataset"
245
+ dataset_name = sys.argv[1]
246
+ assert dataset_name in annotation_files, (
247
+ f"The dataset can be one of {list(annotation_files.keys())}"
248
+ )
249
+
250
+ if dataset_name == "yt1b":
251
+ download_youtube()
252
+ elif dataset_name == "droid":
253
+ download_droid()
254
+ elif dataset_name == "ego4d":
255
+ download_ego4d()
256
+ elif dataset_name == "sav":
257
+ download_sav()
258
+
259
+
260
+ if __name__ == "__main__":
261
+ main()
OVOW/third_party/sam3/scripts/eval/silver/extract_frames.py ADDED
@@ -0,0 +1,101 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ # Copyright (c) Meta Platforms, Inc. and affiliates. All Rights Reserved
2
+
3
+ # pyre-unsafe
4
+ """
5
+ This file extracts the frames for the frame datasets in SA-CO/Gold and Silver.
6
+
7
+ Call like:
8
+ > python extract_frames.py <dataset_name>
9
+ """
10
+
11
+ import json
12
+ import os
13
+ import shutil
14
+ import sys
15
+ from multiprocessing import Pool
16
+
17
+ from PIL import Image
18
+ from tqdm import tqdm
19
+ from utils import (
20
+ annotation_files,
21
+ config,
22
+ get_frame_from_video,
23
+ is_valid_image,
24
+ update_annotations,
25
+ )
26
+
27
+
28
+ def extract_frame(path_video, global_frame_idx, path_frame, image_size, file_name):
29
+ frame = get_frame_from_video(path_video, global_frame_idx)
30
+ os.makedirs(os.path.dirname(path_frame), exist_ok=True)
31
+ img = Image.fromarray(frame)
32
+ if frame.shape[:2] != image_size:
33
+ print(f"Resizing image {file_name} from {frame.shape[:2]} to {image_size}")
34
+ height, width = image_size
35
+ img = img.resize((width, height)) # Uses Image.NEAREST by default
36
+ img.save(path_frame)
37
+
38
+
39
+ def process_image(args):
40
+ image, dataset_name, config = args
41
+ original_video, global_frame_idx, file_name, image_size = image
42
+ extra_subpath = ""
43
+ if dataset_name == "ego4d":
44
+ extra_subpath = "v1/clips"
45
+ elif dataset_name == "yt1b":
46
+ original_video = f"video_{original_video}.mp4"
47
+ elif dataset_name == "sav":
48
+ extra_subpath = "videos_fps_6"
49
+ path_video = os.path.join(
50
+ config[f"{dataset_name}_path"],
51
+ "downloaded_videos",
52
+ extra_subpath,
53
+ original_video,
54
+ )
55
+ path_frame = os.path.join(config[f"{dataset_name}_path"], "frames", file_name)
56
+ to_return = file_name
57
+ try:
58
+ extract_frame(path_video, global_frame_idx, path_frame, image_size, file_name)
59
+ if not is_valid_image(path_frame):
60
+ print(f"Invalid image in {path_frame}")
61
+ to_return = None
62
+ except:
63
+ print(f"Invalid image in {path_frame}")
64
+ to_return = None
65
+ return to_return
66
+
67
+
68
+ def main():
69
+ assert len(sys.argv) > 1, "You have to provide the name of the dataset"
70
+ dataset_name = sys.argv[1]
71
+ assert dataset_name in annotation_files, (
72
+ f"The dataset can be one of {list(annotation_files.keys())}"
73
+ )
74
+ all_outputs = []
75
+ for file in annotation_files[dataset_name]:
76
+ with open(os.path.join(config["path_annotations"], file), "r") as f:
77
+ annotation = json.load(f)
78
+ images = annotation["images"]
79
+ images = set(
80
+ (
81
+ image["original_video"],
82
+ image["global_frame_idx"],
83
+ image["file_name"],
84
+ tuple(image["image_size"]),
85
+ )
86
+ for image in images
87
+ )
88
+ args_list = [(image, dataset_name, config) for image in images]
89
+ with Pool(os.cpu_count()) as pool:
90
+ outputs = list(
91
+ tqdm(pool.imap_unordered(process_image, args_list), total=len(images))
92
+ )
93
+ all_outputs.extend(outputs)
94
+ if any(out is None for out in outputs):
95
+ update_annotations(dataset_name, all_outputs, key="file_name")
96
+ if config[f"remove_downloaded_videos_{dataset_name}"]:
97
+ shutil.rmtree(os.path.join(config[f"{dataset_name}_path"], "downloaded_videos"))
98
+
99
+
100
+ if __name__ == "__main__":
101
+ main()
OVOW/third_party/sam3/scripts/eval/silver/fathomnet_image_uuids.json ADDED
The diff for this file is too large to render. See raw diff
 
OVOW/third_party/sam3/scripts/eval/silver/inaturalist_image_subset.json ADDED
The diff for this file is too large to render. See raw diff
 
OVOW/third_party/sam3/scripts/eval/silver/preprocess_silver_geode_bdd100k_food_rec.py ADDED
@@ -0,0 +1,72 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ # Copyright (c) Meta Platforms, Inc. and affiliates. All Rights Reserved
2
+
3
+ # pyre-unsafe
4
+ import argparse
5
+ from multiprocessing import Pool
6
+ from pathlib import Path
7
+
8
+ import pandas as pd
9
+ import utils
10
+ from tqdm import tqdm
11
+
12
+
13
+ def main(args, n_workers=20):
14
+ raw_folder = Path(args.raw_images_folder)
15
+ processed_folder = Path(args.processed_images_folder)
16
+ utils.setup(processed_folder)
17
+ img_ids = utils.get_image_ids(args.annotation_file)
18
+ if args.dataset_name == "geode":
19
+ metadata = pd.read_csv(raw_folder / "index.csv")
20
+ metadata["flat_filepath"] = metadata.file_path.apply(
21
+ lambda x: x.replace("/", "_")
22
+ )
23
+ metadata["original_absolute_path"] = metadata.file_path.apply(
24
+ lambda x: str((raw_folder / "images") / x)
25
+ )
26
+ metadata["new_absolute_path"] = metadata.flat_filepath.apply(
27
+ lambda x: str(processed_folder / x)
28
+ )
29
+ metadata["filestem"] = metadata.new_absolute_path.apply(lambda x: Path(x).stem)
30
+ img_id_mapping = metadata.set_index("filestem").to_dict()
31
+ # print(img_id_mapping.keys())
32
+ paths = [
33
+ (
34
+ img_id_mapping["original_absolute_path"][each],
35
+ img_id_mapping["new_absolute_path"][each],
36
+ )
37
+ for each in img_ids
38
+ ]
39
+ elif args.dataset_name == "bdd100k":
40
+ bdd_subfolder = "100k/train"
41
+ img_filenames = utils.get_filenames(args.annotation_file)
42
+ raw_folder_bdd_images = raw_folder / bdd_subfolder
43
+ paths = [
44
+ (raw_folder_bdd_images / each, processed_folder / each)
45
+ for each in img_filenames
46
+ ]
47
+ elif args.dataset_name == "food_rec":
48
+ food_subfolder = "public_validation_set_2.0/images"
49
+ img_filenames = utils.get_filenames(args.annotation_file)
50
+ raw_folder_food_images = raw_folder / food_subfolder
51
+ paths = [
52
+ (
53
+ raw_folder_food_images
54
+ / f"{Path(each).stem.split('_')[-1]}{Path(each).suffix}",
55
+ processed_folder / each,
56
+ )
57
+ for each in img_filenames
58
+ ]
59
+ print("Preparing to copy and flatten filename for", len(paths), "images")
60
+ with Pool(20) as p:
61
+ for _ in tqdm(p.imap(utils.copy_file, paths), total=len(paths)):
62
+ continue
63
+
64
+
65
+ if __name__ == "__main__":
66
+ parser = argparse.ArgumentParser()
67
+ parser.add_argument("--annotation_file", help="Path to annotation file")
68
+ parser.add_argument("--raw_images_folder", help="Path to downloaded images")
69
+ parser.add_argument("--processed_images_folder", help="Path to processed images")
70
+ parser.add_argument("--dataset_name", help="Path to processed images")
71
+ args = parser.parse_args()
72
+ main(args)
OVOW/third_party/sam3/scripts/eval/silver/utils.py ADDED
@@ -0,0 +1,150 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ # Copyright (c) Meta Platforms, Inc. and affiliates. All Rights Reserved
2
+
3
+ # pyre-unsafe
4
+ import json
5
+ import os
6
+ import shutil
7
+ import subprocess
8
+ from io import BytesIO
9
+ from pathlib import Path
10
+
11
+ import cv2
12
+ import matplotlib.pyplot as plt
13
+ import numpy as np
14
+ import yaml
15
+ from PIL import Image
16
+ from pycocotools import mask as mask_utils
17
+ from tqdm import tqdm
18
+
19
+
20
+ annotation_files = {
21
+ "droid": [
22
+ "silver_droid_merged_test.json",
23
+ ],
24
+ "sav": [
25
+ "silver_sav_merged_test.json",
26
+ ],
27
+ "yt1b": [
28
+ "silver_yt1b_merged_test.json",
29
+ ],
30
+ "ego4d": [
31
+ "silver_ego4d_merged_test.json",
32
+ ],
33
+ }
34
+
35
+
36
+ def load_yaml(filename):
37
+ with open(filename, "r") as f:
38
+ return yaml.safe_load(f)
39
+
40
+
41
+ def load_json(filename):
42
+ with open(filename, "r") as f:
43
+ return json.load(f)
44
+
45
+
46
+ def save_json(content, filename):
47
+ with open(filename, "w") as f:
48
+ json.dump(content, f)
49
+
50
+
51
+ def run_command(cmd):
52
+ """Run a shell command and raise if it fails."""
53
+ result = subprocess.run(cmd, shell=True)
54
+ if result.returncode != 0:
55
+ raise RuntimeError(f"Command failed: {cmd}")
56
+
57
+
58
+ config = load_yaml("CONFIG_FRAMES.yaml")
59
+
60
+
61
+ def is_valid_image(img_path):
62
+ try:
63
+ img = Image.open(img_path).convert("RGB")
64
+ return True
65
+ except Exception:
66
+ return False
67
+
68
+
69
+ def get_frame_from_video(video_path, frame_id):
70
+ cap = cv2.VideoCapture(video_path)
71
+ cap.set(cv2.CAP_PROP_POS_FRAMES, frame_id)
72
+ ret, frame = cap.read()
73
+ cap.release()
74
+ if not ret:
75
+ # Some videos cannot be open with OpenCV
76
+ import av
77
+
78
+ container = av.open(video_path)
79
+ stream = container.streams.video[0]
80
+ for i, frame in tqdm(
81
+ enumerate(container.decode(stream)),
82
+ desc="Decoding with AV",
83
+ total=frame_id + 1,
84
+ ):
85
+ if i == frame_id:
86
+ img = frame.to_ndarray(format="rgb24")
87
+ return img
88
+ raise ValueError(
89
+ f"Could not read frame {frame_id} from video {video_path} (out of frame)"
90
+ )
91
+ frame_rgb = cv2.cvtColor(frame, cv2.COLOR_BGR2RGB)
92
+ return frame_rgb
93
+
94
+
95
+ def update_annotations(dataset_name, file_names_keep, key="original_video"):
96
+ for annotation_file in annotation_files[dataset_name]:
97
+ path_ann = os.path.join(config["path_annotations"], annotation_file)
98
+ path_original_ann = os.path.join(
99
+ config["path_annotations"],
100
+ annotation_file.replace(".json", "_original.json"),
101
+ )
102
+ ann = load_json(path_ann)
103
+ shutil.copy(path_ann, path_original_ann)
104
+ new_images = []
105
+ image_ids_keep = set()
106
+ for image in ann["images"]:
107
+ if image[key].replace(".mp4", "") in file_names_keep:
108
+ new_images.append(image)
109
+ image_ids_keep.add(image["id"])
110
+ new_annotations = []
111
+ for annotation in ann["annotations"]:
112
+ if annotation["image_id"] in image_ids_keep:
113
+ new_annotations.append(annotation)
114
+ ann["images"] = new_images
115
+ ann["annotations"] = new_annotations
116
+ save_json(ann, path_ann)
117
+
118
+
119
+ def get_filename_size_map(annotation_path):
120
+ with open(annotation_path) as f:
121
+ annotations = json.load(f)
122
+ filename_size_map = {}
123
+ for each in annotations["images"]:
124
+ filename_size_map[each["file_name"]] = (each["width"], each["height"])
125
+ return filename_size_map
126
+
127
+
128
+ def get_filenames(annotation_path):
129
+ with open(annotation_path) as f:
130
+ annotations = json.load(f)
131
+ filenames = {Path(each["file_name"]) for each in annotations["images"]}
132
+ return filenames
133
+
134
+
135
+ def get_image_ids(annotation_path):
136
+ filenames = get_filenames(annotation_path)
137
+ filestems = {Path(each).stem for each in filenames}
138
+ return filestems
139
+
140
+
141
+ def setup(folder):
142
+ print("Making dir", folder)
143
+ folder.mkdir(exist_ok=True)
144
+
145
+
146
+ def copy_file(paths):
147
+ old_path, new_path = paths
148
+ print("Copy from", old_path, "to", new_path)
149
+ if not Path(new_path).exists():
150
+ shutil.copy2(old_path, new_path)
OVOW/third_party/sam3/scripts/eval/standalone_cgf1.py ADDED
@@ -0,0 +1,50 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ # Copyright (c) Meta Platforms, Inc. and affiliates. All Rights Reserved
2
+
3
+ # pyre-unsafe
4
+
5
+ """Simple script to run the CGF1 evaluator given a prediction file and GT file(s).
6
+
7
+ Usage: python standalone_cgf1.py --pred_file <path_to_prediction_file> --gt_files <path_to_gt_file1> <path_to_gt_file2> ...
8
+ """
9
+
10
+ import argparse
11
+
12
+ from sam3.eval.cgf1_eval import CGF1Evaluator
13
+
14
+
15
+ def main():
16
+ parser = argparse.ArgumentParser()
17
+ parser.add_argument(
18
+ "--pred_file",
19
+ type=str,
20
+ required=True,
21
+ help="Path to the prediction file in COCO format.",
22
+ )
23
+ parser.add_argument(
24
+ "--gt_files",
25
+ type=str,
26
+ nargs="+",
27
+ required=True,
28
+ help="Paths to the ground truth files in COCO format.",
29
+ )
30
+ args = parser.parse_args()
31
+ if len(args.gt_files) == 0:
32
+ raise ValueError("At least one GT file must be provided.")
33
+
34
+ is_gold = args.gt_files[0].split("_")[-1].startswith("gold_")
35
+ if is_gold and len(args.gt_files) < 3:
36
+ print(
37
+ "WARNING: based on the name, it seems you are using gold GT files. Typically, there should be 3 GT files for gold subsets (a, b, c)."
38
+ )
39
+
40
+ evaluator = CGF1Evaluator(
41
+ gt_path=args.gt_files, verbose=True, iou_type="segm"
42
+ ) # change to bbox if you want detection performance
43
+
44
+ results = evaluator.evaluate(args.pred_file)
45
+
46
+ print(results)
47
+
48
+
49
+ if __name__ == "__main__":
50
+ main()
OVOW/third_party/sam3/scripts/eval/veval/README.md ADDED
@@ -0,0 +1,248 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ # SA-Co/VEval Dataset
2
+ **License** each domain has its own License
3
+ * SA-Co/VEval - SA-V: CC-BY-NC 4.0
4
+ * SA-Co/VEval - YT-Temporal-1B: CC-BY-NC 4.0
5
+ * SA-Co/VEval - SmartGlasses: CC-by-4.0
6
+
7
+ **SA-Co/VEval** is an evaluation dataset comprising of 3 domains, each domain has a val and test split.
8
+ * SA-Co/VEval - SA-V: videos are from the [SA-V dataset](https://ai.meta.com/datasets/segment-anything-video/)
9
+ * SA-Co/VEval - YT-Temporal-1B: videos are from the [YT-Temporal-1B](https://cove.thecvf.com/datasets/704)
10
+ * SA-Co/VEval - SmartGlasses: egocentric videos from [Smart Glasses](https://huggingface.co/datasets/facebook/SACo-VEval/blob/main/media/saco_sg.tar.gz)
11
+
12
+ ## Environment
13
+ Install the SA-Co/VEVal required environment
14
+ ```
15
+ pip install -e ".[veval]"
16
+ ```
17
+ This will allow us to run:
18
+ * `scripts/eval/veval/saco_yt1b_downloader.py` preparing frames for SA-Co/VEval - YT-Temporal-1B
19
+ * `examples/saco_veval_eval_example.ipynb` example of running an offline evaluator
20
+ * `examples/saco_veval_vis_example.ipynb` example of loading and visualizing the data
21
+
22
+ ## Download
23
+ ### The expected folder structure
24
+ The following folder structure is expected after finishing all the download and pre-processing steps in this section
25
+ ```
26
+ data/
27
+ ├── annotation/
28
+ │ ├── saco_veval_sav_test.json
29
+ │ ├── saco_veval_sav_val.json
30
+ │ ├── saco_veval_smartglasses_test.json
31
+ │ ├── saco_veval_smartglasses_val.json
32
+ │ ├── saco_veval_yt1b_test.json
33
+ │ ├── saco_veval_yt1b_val.json
34
+ └── media/
35
+ ├── saco_sav
36
+ │ └── JPEGImages_24fps
37
+ ├── saco_sg
38
+ │ └── JPEGImages_6fps
39
+ └── saco_yt1b
40
+ └── JPEGImages_6fps
41
+ ```
42
+ ### Download ready-to-use data
43
+ The following links provide ready-to-use data, hosted on Roboflow, after completing the pre-processing steps outlined in the next section.
44
+
45
+ For each domain:
46
+ - [SA-Co/VEval - SA-V](https://universe.roboflow.com/sa-co-veval/sa-v-test/)
47
+ - [SA-Co/VEval - YT-Temporal-1B](https://universe.roboflow.com/sa-co-veval/yt-temporal-1b-test/)
48
+ - [SA-Co/VEval - SmartGlasses](https://universe.roboflow.com/sa-co-veval/smartglasses-test/)
49
+
50
+ For all three domains:
51
+ - [SA-Co/VEval](https://universe.roboflow.com/sa-co-veval)
52
+
53
+ Special note on **SA-Co/VEval - YT-Temporal-1B**:
54
+ * **Frame Shifting Alert!**
55
+ * The ready-to-use data hosted on Roboflow was produced by following the preprocessing steps below. Therefore, the frame-shifting issue for YT-Temporal-1B still exists: due to the nature of Youtube videos, the re-downloaded videos may not be exactly the same as those used during annotation, which can affect eval number reproducibility.
56
+
57
+ ### Download via preprocessing steps
58
+ #### Download annotations
59
+ The GT annotations are available at Hugging Face:
60
+ * [SA-Co/VEval](https://huggingface.co/datasets/facebook/SACo-VEval/tree/main)
61
+ * SA-Co/VEval SA-V
62
+ * Test: `annotation/saco_veval_sav_test.json`
63
+ * Val: `annotation/saco_veval_sav_val.json`
64
+ * SA-Co/VEval YT-Temporal-1B
65
+ * Test: `annotation/saco_veval_yt1b_test.json`
66
+ * Val: `annotation/saco_veval_yt1b_val.json`
67
+ * SA-Co/VEval SmartGlasses
68
+ * Test: `annotation/saco_veval_smartglasses_test.json`
69
+ * Val: `annotation/saco_veval_smartglasses_val.json`
70
+
71
+ #### Download videos or frames
72
+ ##### SA-Co/VEval - SAV
73
+ Follow instructions in [SA-V dataset](https://ai.meta.com/datasets/segment-anything-video/). Only the following two datasets are needed:
74
+ * sav_test.tar
75
+ * sav_val.tar
76
+
77
+ After untar:
78
+ ```
79
+ sav_test/
80
+ ├── Annotations_6fps [ignore this is the SAM 2 annotation]
81
+ ├── JPEGImages_24fps
82
+ sav_val/
83
+ ├── Annotations_6fps [ignore this is the SAM 2 annotation]
84
+ └── JPEGImages_24fps
85
+ ```
86
+ Then merge the two JPEGImages_24fps together to better match our annotation json file path e.g.
87
+ ```
88
+ media/
89
+ └── saco_sav
90
+ └── JPEGImages_24fps [merged from the two JPEGImages_24fps above]
91
+ ```
92
+ Example commands to download and merge folders
93
+ ```
94
+ cd ../data/media/saco_sav
95
+ wget -O sav_test.tar <sav_test.tar download link from the SA-V dataset page>
96
+ wget -O sav_val.tar <sav_val.tar download link from the SA-V dataset page>
97
+ tar -xf sav_test.tar
98
+ tar -xf sav_val.tar
99
+ mkdir JPEGImages_24fps
100
+ chmod -R u+w sav_test/
101
+ chmod -R u+w sav_val/
102
+ mv sav_test/JPEGImages_24fps/* JPEGImages_24fps/
103
+ mv sav_val/JPEGImages_24fps/* JPEGImages_24fps/
104
+ ```
105
+
106
+ ##### SA-Co/VEval - YT-Temporal-1B
107
+ Two files are needed to download the SA-Co/VEval - YT-Temporal-1B Youtube videos.
108
+ * Download `media/yt1b_start_end_time.json` from [SA-Co/VEval](https://huggingface.co/datasets/facebook/SACo-VEval/tree/main), which contains the Youtube video ids and the start and end time used in SA-Co/VEval - YT-Temporal-1B.
109
+ * Prepare the `cookies.txt` file. Follow instruction in yt-dlp [exporting-youtube-cookies](https://github.com/yt-dlp/yt-dlp/wiki/Extractors#exporting-youtube-cookies) and [pass-cookies-to-yt-dlp](https://github.com/yt-dlp/yt-dlp/wiki/FAQ#how-do-i-pass-cookies-to-yt-dlp) to prepare the cookies_file.
110
+ * Please see the full **WARNINGS** in yt-dlp regarding the risk of Youtube account ban!!
111
+
112
+ Then run `scripts/eval/veval/saco_yt1b_downloader.py` to download the videos and prepare the frames e.g.
113
+ ```
114
+ python saco_yt1b_downloader.py \
115
+ --data_dir ../data/media/saco_yt1b \
116
+ --cookies_file ../data/media/saco_yt1b/cookies.txt \
117
+ --yt1b_start_end_time_file ../data/media/saco_yt1b/yt1b_start_end_time.json \
118
+ --yt1b_frame_prep_log_file ../data/media/saco_yt1b/yt1b_frame_prep.log
119
+ ```
120
+ * data_dir: The directoy to download the Youtube videos and store the extraced frames
121
+ * cookies_file: the `cookies.txt` downloaded above
122
+ * yt1b_start_end_time_file: the `yt1b_start_end_time.json` downloaded above
123
+ * yt1b_frame_prep_log_file: a log file to track the video downloading and frame extracting status
124
+
125
+ Then run `scripts/eval/veval/saco_yt1b_annot_update.py` to update the annotation based on the video availability e.g.
126
+ ```
127
+ python saco_yt1b_annot_update.py \
128
+ --yt1b_media_dir ../data/media/saco_yt1b/JPEGImages_6fps \
129
+ --yt1b_input_annot_path ../data/annotation/saco_veval_yt1b_val.json \
130
+ --yt1b_output_annot_path ../data/annotation/saco_veval_yt1b_val_updated.json \
131
+ --yt1b_annot_update_log_path ../data/annotation/saco_veval_yt1b_val_updated.log
132
+ ```
133
+
134
+ **NOTE**:
135
+ * Not all Youtube videos might be available as Youtube videos can be deleted or become private. The script `saco_yt1b_annot_update.py` is used to remove the annotations of the unavailable videos.
136
+ * **Frame Shifting Alert!!** Even when the videos are still available, their specifications, such as fps and duration, may differ from those used during annotation when re-downloaded from YouTube. Additionally, sometimes `ffmpeg` seems to find it hard to guarantee consistent frame extraction from the same video across different environments. This may cause the re-downloaded and re-extracted frames to have alignment issues with our annotations due to frame shifting. Please be aware of this caveat when evaluating on SA-Co/VEval - YT-Temporal-1B.
137
+
138
+ ##### SA-Co/VEval - SmartGlasses
139
+ Go to [SACo-VEval](https://huggingface.co/datasets/facebook/SACo-VEval/tree/main) download `media/saco_sg.tar.gz`
140
+ ```
141
+ cd ../data
142
+ hf download facebook/SACo-VEval media/saco_sg.tar.gz --repo-type dataset --local-dir .
143
+ cd ../data/media
144
+ tar -xzf saco_sg.tar.gz
145
+ ```
146
+
147
+ ## Annotation Format
148
+ The format is similar to the [YTVIS](https://youtube-vos.org/dataset/vis/) format.
149
+
150
+ In the annotation json, e.g. `saco_veval_sav_test.json` there are 5 fields:
151
+ * info:
152
+ * A dict containing the dataset info
153
+ * E.g. {'version': 'v1', 'date': '2025-09-24', 'description': 'SA-Co/VEval SA-V Test'}
154
+ * videos
155
+ * A list of videos that are used in the current annotation json
156
+ * It contains {id, video_name, file_names, height, width, length}
157
+ * annotations
158
+ * A list of **positive** masklets and their related info
159
+ * It contains {id, segmentations, bboxes, areas, iscrowd, video_id, height, width, category_id, noun_phrase}
160
+ * video_id should match to the `videos - id` field above
161
+ * category_id should match to the `categories - id` field below
162
+ * segmentations is a list of [RLE](https://github.com/cocodataset/cocoapi/blob/master/PythonAPI/pycocotools/mask.py)
163
+ * categories
164
+ * A **globally** used noun phrase id map, which is true across all 3 domains.
165
+ * It contains {id, name}
166
+ * name is the noun phrase
167
+ * video_np_pairs
168
+ * A list of video-np pairs, including both **positive** and **negative** used in the current annotation json
169
+ * It contains {id, video_id, category_id, noun_phrase, num_masklets}
170
+ * video_id should match the `videos - id` above
171
+ * category_id should match the `categories - id` above
172
+ * when `num_masklets > 0` it is a positive video-np pair, and the presenting masklets can be found in the annotations field
173
+ * when `num_masklets = 0` it is a negative video-np pair, meaning no masklet presenting at all
174
+ ```
175
+ data {
176
+ "info": info
177
+ "videos": [video]
178
+ "annotations": [annotation]
179
+ "categories": [category]
180
+ "video_np_pairs": [video_np_pair]
181
+ }
182
+ video {
183
+ "id": int
184
+ "video_name": str # e.g. sav_000000
185
+ "file_names": List[str]
186
+ "height": int
187
+ "width": width
188
+ "length": length
189
+ }
190
+ annotation {
191
+ "id": int
192
+ "segmentations": List[RLE]
193
+ "bboxes": List[List[int, int, int, int]]
194
+ "areas": List[int]
195
+ "iscrowd": int
196
+ "video_id": str
197
+ "height": int
198
+ "width": int
199
+ "category_id": int
200
+ "noun_phrase": str
201
+ }
202
+ category {
203
+ "id": int
204
+ "name": str
205
+ }
206
+ video_np_pair {
207
+ "id": int
208
+ "video_id": str
209
+ "category_id": int
210
+ "noun_phrase": str
211
+ "num_masklets" int
212
+ }
213
+ ```
214
+ [sam3/examples/saco_veval_vis_example.ipynb](https://github.com/facebookresearch/sam3/blob/main/examples/saco_veval_vis_example.ipynb) shows some examples of the data format and data visualization.
215
+
216
+ ## Run Offline Eval
217
+ An example notebook and an eval script have been provided for offline evaluation.
218
+ ```
219
+ sam3/
220
+ ├── examples/
221
+ │ └── saco_veval_eval_example.ipynb # this notebook will load eval res or run the eval on the fly, and print the results
222
+ └── sam3/eval/
223
+ └── saco_veval_eval.py # this script will run the offline evaluator
224
+ ```
225
+ `saco_veval_eval.py` supports two modes, `one` and `all`.
226
+ * `one`: will take only one pair of gt and pred files to eval
227
+ * `all`: will eval on all 6 SACo/VEval datasets
228
+
229
+ Example usage
230
+ ```
231
+ python saco_veval_eval.py one \
232
+ --gt_annot_file ../sam3/assets/veval/toy_gt_and_pred/toy_saco_veval_sav_test_gt.json \
233
+ --pred_file ../sam3/assets/veval/toy_gt_and_pred/toy_saco_veval_sav_test_pred.json \
234
+ --eval_res_file ../sam3/assets/veval/toy_gt_and_pred/toy_saco_veval_sav_test_eval_res.json
235
+ ```
236
+ * `gt_annot_file`: the location of the GT file
237
+ * `pred_file`: the location of the Pred file
238
+ * `eval_res_file`: the location where the eval result will be written to
239
+
240
+ ```
241
+ python saco_veval_eval.py all \
242
+ --gt_annot_dir ../data/annotation \
243
+ --pred_dir ../data/pred \
244
+ --eval_res_dir ../data/pred
245
+ ```
246
+ * `gt_annot_dir`: the location of the GT files
247
+ * `pred_dir`: the location of the Pred files
248
+ * `eval_res_dir`: the location where the eval results will be written to
OVOW/third_party/sam3/scripts/eval/veval/__init__.py ADDED
@@ -0,0 +1,3 @@
 
 
 
 
1
+ # Copyright (c) Meta Platforms, Inc. and affiliates. All Rights Reserved
2
+
3
+ # pyre-unsafe
OVOW/third_party/sam3/scripts/eval/veval/saco_yt1b_annot_update.py ADDED
@@ -0,0 +1,138 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ # Copyright (c) Meta Platforms, Inc. and affiliates. All Rights Reserved
2
+
3
+ # pyre-unsafe
4
+ import argparse
5
+ import json
6
+ import logging
7
+ import os
8
+
9
+ import pandas as pd
10
+
11
+
12
+ logger = logging.getLogger(__name__)
13
+
14
+
15
+ def get_available_saco_yt1b_ids(yt1b_meida_dir, data):
16
+ vdf = pd.DataFrame(data["videos"])
17
+ expected_saco_yt1b_ids = vdf.video_name.tolist()
18
+
19
+ yt1b_media_folders = os.listdir(yt1b_meida_dir)
20
+
21
+ available_saco_yt1b_ids = []
22
+ for yt1b_media_folder in yt1b_media_folders:
23
+ if yt1b_media_folder not in expected_saco_yt1b_ids:
24
+ continue
25
+ jpeg_folder_dir = os.path.join(yt1b_meida_dir, yt1b_media_folder)
26
+ jpeg_count = len(os.listdir(jpeg_folder_dir))
27
+ if jpeg_count > 0:
28
+ available_saco_yt1b_ids.append(yt1b_media_folder)
29
+ else:
30
+ logger.info(
31
+ f"No JPEG images found for {yt1b_media_folder}. The annotation related to this video will be removed."
32
+ )
33
+
34
+ logger.info(
35
+ f"Expected {len(expected_saco_yt1b_ids)} videos for {data['info']}. Found {len(available_saco_yt1b_ids)} videos available in {yt1b_meida_dir}."
36
+ )
37
+ return available_saco_yt1b_ids
38
+
39
+
40
+ def update_yt1b_annot_per_field(data, field, id_col, available_ids):
41
+ field_data = data[field]
42
+ new_field_data = []
43
+ for data_entry in field_data:
44
+ if data_entry[id_col] not in available_ids:
45
+ logger.info(
46
+ f"{field}: Removing {data_entry} due to the video being unavailable."
47
+ )
48
+ continue
49
+ new_field_data.append(data_entry)
50
+
51
+ data[field] = new_field_data
52
+ logger.info(
53
+ f"Updated {field} by {id_col} - Before: {len(field_data)}, After: {len(new_field_data)}, Removed: {len(field_data) - len(new_field_data)}"
54
+ )
55
+ return data
56
+
57
+
58
+ def update_yt1b_annot(yt1b_input_annot_path, yt1b_media_dir, yt1b_output_annot_path):
59
+ with open(yt1b_input_annot_path, "r") as f:
60
+ data = json.load(f)
61
+
62
+ available_saco_yt1b_ids = get_available_saco_yt1b_ids(yt1b_media_dir, data)
63
+
64
+ data = update_yt1b_annot_per_field(
65
+ data=data,
66
+ field="videos",
67
+ id_col="video_name",
68
+ available_ids=available_saco_yt1b_ids,
69
+ )
70
+
71
+ videos_data = data["videos"]
72
+ available_video_incremental_ids = [data_entry["id"] for data_entry in videos_data]
73
+
74
+ data = update_yt1b_annot_per_field(
75
+ data=data,
76
+ field="annotations",
77
+ id_col="video_id",
78
+ available_ids=available_video_incremental_ids,
79
+ )
80
+ data = update_yt1b_annot_per_field(
81
+ data=data,
82
+ field="video_np_pairs",
83
+ id_col="video_id",
84
+ available_ids=available_video_incremental_ids,
85
+ )
86
+
87
+ with open(yt1b_output_annot_path, "w") as f:
88
+ json.dump(data, f)
89
+
90
+ return data
91
+
92
+
93
+ def main():
94
+ parser = argparse.ArgumentParser(description="Run video grounding evaluators")
95
+ parser.add_argument(
96
+ "--yt1b_media_dir",
97
+ type=str,
98
+ help="Path to the directory where the yt1b media is stored e.g media/saco_yt1b/JPEGImages_6fps",
99
+ )
100
+ parser.add_argument(
101
+ "--yt1b_input_annot_path",
102
+ type=str,
103
+ help="Path to the saco_veval_yt1b input annotation file e.g annotation/saco_veval_yt1b_test.json or annotation/saco_veval_yt1b_val.json",
104
+ )
105
+ parser.add_argument(
106
+ "--yt1b_output_annot_path",
107
+ type=str,
108
+ help="Path to the output annotation file e.g annotation/saco_veval_yt1b_test_updated.json or annotation/saco_veval_yt1b_val_updated.json",
109
+ )
110
+ parser.add_argument(
111
+ "--yt1b_annot_update_log_path",
112
+ type=str,
113
+ help="Path to the yt1b annot update log file e.g annotation/yt1b_annot_update_log.log",
114
+ )
115
+
116
+ args = parser.parse_args()
117
+
118
+ os.makedirs(os.path.dirname(args.yt1b_annot_update_log_path), exist_ok=True)
119
+ os.makedirs(os.path.dirname(args.yt1b_output_annot_path), exist_ok=True)
120
+
121
+ logging.basicConfig(
122
+ filename=args.yt1b_annot_update_log_path,
123
+ format="%(asctime)s [%(threadName)s] %(levelname)s: %(message)s",
124
+ level=logging.INFO,
125
+ filemode="w",
126
+ )
127
+
128
+ _ = update_yt1b_annot(
129
+ yt1b_input_annot_path=args.yt1b_input_annot_path,
130
+ yt1b_media_dir=args.yt1b_media_dir,
131
+ yt1b_output_annot_path=args.yt1b_output_annot_path,
132
+ )
133
+
134
+ print("Done!! Check the log at", args.yt1b_annot_update_log_path)
135
+
136
+
137
+ if __name__ == "__main__":
138
+ main()
OVOW/third_party/sam3/scripts/eval/veval/saco_yt1b_downloader.py ADDED
@@ -0,0 +1,137 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ # Copyright (c) Meta Platforms, Inc. and affiliates. All Rights Reserved
2
+
3
+ # pyre-unsafe
4
+ import argparse
5
+ import logging
6
+ import multiprocessing as mp
7
+ import os
8
+ from functools import partial
9
+
10
+ import pandas as pd
11
+ from saco_yt1b_frame_prep_util import YtVideoPrep
12
+ from tqdm import tqdm
13
+
14
+ logger = logging.getLogger(__name__)
15
+
16
+
17
+ def download_and_extract_frames(saco_yt1b_id, args):
18
+ video_prep = YtVideoPrep(
19
+ saco_yt1b_id=saco_yt1b_id,
20
+ data_dir=args.data_dir,
21
+ cookies_file=args.cookies_file,
22
+ yt1b_start_end_time_file=args.yt1b_start_end_time_file,
23
+ ffmpeg_timeout=args.ffmpeg_timeout,
24
+ sleep_interval=args.sleep_interval,
25
+ max_sleep_interval=args.max_sleep_interval,
26
+ )
27
+
28
+ status = video_prep.download_youtube_video()
29
+ logger.info(f"[video download][{saco_yt1b_id}] download status {status}")
30
+
31
+ if status not in ["already exists", "success"]:
32
+ logger.warning(
33
+ f"Video download failed for {saco_yt1b_id}, skipping frame generation"
34
+ )
35
+ return False
36
+
37
+ status = video_prep.extract_frames_in_6fps_and_width_1080()
38
+ logger.info(f"[frame extracting][{saco_yt1b_id}] frame extracting status {status}")
39
+ return True
40
+
41
+
42
+ def main():
43
+ parser = argparse.ArgumentParser()
44
+ parser.add_argument(
45
+ "--data_dir",
46
+ type=str,
47
+ required=True,
48
+ )
49
+ parser.add_argument(
50
+ "--cookies_file",
51
+ type=str,
52
+ required=True,
53
+ )
54
+ parser.add_argument(
55
+ "--yt1b_start_end_time_file",
56
+ type=str,
57
+ required=True,
58
+ )
59
+ parser.add_argument(
60
+ "--yt1b_frame_prep_log_file",
61
+ type=str,
62
+ required=True,
63
+ )
64
+ parser.add_argument(
65
+ "--ffmpeg_timeout",
66
+ type=str,
67
+ default=7200, # Use longer timeout in case of large videos processing timeout
68
+ )
69
+ parser.add_argument(
70
+ "--sleep_interval",
71
+ type=int,
72
+ default=10,
73
+ )
74
+ parser.add_argument(
75
+ "--max_sleep_interval",
76
+ type=int,
77
+ default=30,
78
+ )
79
+ parser.add_argument(
80
+ "--num_workers",
81
+ type=int,
82
+ default=4,
83
+ )
84
+ args = parser.parse_args()
85
+
86
+ log_dir = os.path.dirname(args.yt1b_frame_prep_log_file)
87
+ if log_dir:
88
+ os.makedirs(log_dir, exist_ok=True)
89
+
90
+ # Set up logging to both file and console
91
+ # Configure the ROOT logger so all child loggers inherit the configuration
92
+ logging.basicConfig(
93
+ level=logging.INFO,
94
+ format="%(asctime)s [%(processName)s/%(threadName)s] %(name)s - %(levelname)s: %(message)s",
95
+ handlers=[
96
+ logging.FileHandler(args.yt1b_frame_prep_log_file, mode="w"),
97
+ logging.StreamHandler(),
98
+ ],
99
+ force=True, # Override any existing configuration
100
+ )
101
+
102
+ YT_DLP_WARNING_STR = """ ==========
103
+ NOTICE!!
104
+ This script uses yt-dlp to download youtube videos.
105
+ See the youtube account banning risk in https://github.com/yt-dlp/yt-dlp/wiki/Extractors#exporting-youtube-cookies
106
+ ==========
107
+ """
108
+
109
+ logger.info(YT_DLP_WARNING_STR)
110
+
111
+ args = parser.parse_args()
112
+
113
+ with open(args.yt1b_start_end_time_file, "r") as f:
114
+ yt1b_start_end_time_df = pd.read_json(f)
115
+
116
+ saco_yt1b_ids = yt1b_start_end_time_df.saco_yt1b_id.unique()
117
+ num_workers = args.num_workers
118
+ logger.info(
119
+ f"Starting with {num_workers} parallel worker(s) (sleep_interval={args.sleep_interval}-{args.max_sleep_interval}s)"
120
+ )
121
+
122
+ with mp.Pool(num_workers) as p:
123
+ download_func = partial(download_and_extract_frames, args=args)
124
+ list(tqdm(p.imap(download_func, saco_yt1b_ids), total=len(saco_yt1b_ids)))
125
+
126
+ done_str = f""" ==========
127
+ All DONE!!
128
+ Download, frame extraction, and frame matching is all done! YT1B frames are not ready to use in {args.data_dir}/JPEGImages_6fps
129
+ Check video frame preparing log at {args.yt1b_frame_prep_log_file}
130
+ Some videos might not be available any more which will affect the eval reproducibility
131
+ ==========
132
+ """
133
+ logger.info(done_str)
134
+
135
+
136
+ if __name__ == "__main__":
137
+ main()
OVOW/third_party/sam3/scripts/eval/veval/saco_yt1b_frame_prep_util.py ADDED
@@ -0,0 +1,267 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ # Copyright (c) Meta Platforms, Inc. and affiliates. All Rights Reserved
2
+
3
+ # pyre-unsafe
4
+ import argparse
5
+ import logging
6
+ import os
7
+ import subprocess
8
+
9
+ import pandas as pd
10
+ import yt_dlp
11
+
12
+ logger = logging.getLogger(__name__)
13
+
14
+
15
+ class YtVideoPrep:
16
+ def __init__(
17
+ self,
18
+ saco_yt1b_id: str,
19
+ data_dir: str,
20
+ cookies_file: str,
21
+ yt1b_start_end_time_file: str,
22
+ ffmpeg_timeout: int,
23
+ sleep_interval: int = 10,
24
+ max_sleep_interval: int = 30,
25
+ ):
26
+ self.saco_yt1b_id = saco_yt1b_id # saco_yt1b_id is like saco_yt1b_000000
27
+ self.data_dir = data_dir
28
+ self.cookies_file = cookies_file
29
+ self.ffmpeg_timeout = ffmpeg_timeout
30
+ self.sleep_interval = sleep_interval
31
+ self.max_sleep_interval = max_sleep_interval
32
+
33
+ self.yt1b_start_end_time_df = pd.read_json(yt1b_start_end_time_file)
34
+ (
35
+ self.yt_video_id,
36
+ self.yt_video_id_w_timestamps,
37
+ self.start_time,
38
+ self.end_time,
39
+ self.expected_num_frames,
40
+ ) = self._get_yt_video_id_map_info()
41
+
42
+ self.raw_video_dir = os.path.join(self.data_dir, "raw_videos")
43
+ self.raw_video_path = os.path.join(
44
+ self.raw_video_dir, f"{self.yt_video_id}.mp4"
45
+ )
46
+
47
+ self.JPEGImages_6fps_dir = os.path.join(
48
+ self.data_dir, "JPEGImages_6fps", self.saco_yt1b_id
49
+ )
50
+ self.JPEGImages_6fps_pattern = os.path.join(
51
+ self.JPEGImages_6fps_dir, "%05d.jpg"
52
+ )
53
+
54
+ os.makedirs(self.raw_video_dir, exist_ok=True)
55
+ os.makedirs(self.JPEGImages_6fps_dir, exist_ok=True)
56
+
57
+ def _get_yt_video_id_map_info(self):
58
+ df = self.yt1b_start_end_time_df[
59
+ self.yt1b_start_end_time_df.saco_yt1b_id == self.saco_yt1b_id
60
+ ]
61
+ assert len(df) == 1, (
62
+ f"Expected exactly 1 row for saco_yt1b_id: {self.saco_yt1b_id}, found {len(df)}"
63
+ )
64
+ id_and_frame_map_row = df.iloc[0]
65
+
66
+ yt_video_id = (
67
+ id_and_frame_map_row.yt_video_id
68
+ ) # yt_video_id is like -06NgWyZxC0
69
+ yt_video_id_w_timestamps = id_and_frame_map_row.yt_video_id_w_timestamps
70
+ start_time = id_and_frame_map_row.start_time
71
+ end_time = id_and_frame_map_row.end_time
72
+ expected_num_frames = id_and_frame_map_row.length
73
+
74
+ return (
75
+ yt_video_id,
76
+ yt_video_id_w_timestamps,
77
+ start_time,
78
+ end_time,
79
+ expected_num_frames,
80
+ )
81
+
82
+ def download_youtube_video(self):
83
+ video_url = f"https://youtube.com/watch?v={self.yt_video_id}"
84
+
85
+ assert os.path.exists(self.cookies_file), (
86
+ f"Cookies file '{self.cookies_file}' not found. Must have it to download videos."
87
+ )
88
+
89
+ outtmpl = self.raw_video_path
90
+
91
+ # Check if the output file already exists
92
+ if os.path.exists(outtmpl) and os.path.isfile(outtmpl):
93
+ return "already exists"
94
+
95
+ ydl_opts = {
96
+ "format": "best[height<=720]/best", # 720p or lower
97
+ "outtmpl": outtmpl,
98
+ "merge_output_format": "mp4",
99
+ "noplaylist": True,
100
+ "quiet": True,
101
+ "cookiefile": self.cookies_file,
102
+ "sleep_interval": self.sleep_interval, # Sleep before each download to avoid rate limiting
103
+ "max_sleep_interval": self.max_sleep_interval, # Random sleep for more human-like behavior
104
+ }
105
+
106
+ if self.yt_video_id in ["euohdDLEMRg", "nzfAn7n4d-0"]:
107
+ # For "euohdDLEMRg", we have to specify the https protocol or the video sometimes can't be downloaded completely
108
+ # For "nzfAn7n4d-0", without the https protocol, the video will be downloaded as 654×480, however we need 490×360 to match the frame matching after the 1080 width resizing
109
+ ydl_opts["format"] = (
110
+ "best[height<=720][ext=mp4][protocol^=https]/best[ext=mp4][protocol^=https]/best[height<=720]/best"
111
+ )
112
+
113
+ try:
114
+ with yt_dlp.YoutubeDL(ydl_opts) as ydl:
115
+ ydl.download([video_url])
116
+ return "success"
117
+ except Exception as e:
118
+ logger.warning(
119
+ f"[video download][{self.saco_yt1b_id}] Error downloading video {self.yt_video_id}: {e}"
120
+ )
121
+ return f"error {e}"
122
+
123
+ def extract_frames_in_6fps_and_width_1080(self):
124
+ """
125
+ Extract target frames in 6fps and width 1080.
126
+ """
127
+ if not os.path.exists(self.raw_video_path):
128
+ logger.warning(
129
+ f"[frame extracting][{self.saco_yt1b_id}] Raw video file not found at {self.raw_video_path}"
130
+ )
131
+ os.rmdir(self.JPEGImages_6fps_dir)
132
+ return False
133
+
134
+ if (
135
+ os.path.exists(self.JPEGImages_6fps_dir)
136
+ and len(os.listdir(self.JPEGImages_6fps_dir)) == self.expected_num_frames
137
+ ):
138
+ logger.info(
139
+ f"[frame extracting][{self.saco_yt1b_id}] JPEGImages_6fps directory already exists at {self.JPEGImages_6fps_dir} and expected number of frames {self.expected_num_frames} matches"
140
+ )
141
+ return True
142
+
143
+ # Clear the directory before extracting new frames
144
+ for file in os.listdir(self.JPEGImages_6fps_dir):
145
+ os.remove(os.path.join(self.JPEGImages_6fps_dir, file))
146
+
147
+ args = [
148
+ "-nostdin",
149
+ "-y",
150
+ # select video segment
151
+ "-ss",
152
+ str(self.start_time),
153
+ "-to",
154
+ str(self.end_time),
155
+ "-i",
156
+ self.raw_video_path,
157
+ # set output video resolution to be 6fps and at most 1080p
158
+ "-vf",
159
+ "fps=6,scale=1080:-2",
160
+ "-vsync",
161
+ "0", # passthrough mode - no frame duplication/dropping
162
+ "-q:v",
163
+ "2", # high quality JPEG output
164
+ "-start_number",
165
+ "0", # start frame numbering from 0
166
+ self.JPEGImages_6fps_pattern,
167
+ ]
168
+
169
+ result = subprocess.run(
170
+ ["ffmpeg"] + args,
171
+ timeout=self.ffmpeg_timeout,
172
+ capture_output=True,
173
+ text=True,
174
+ )
175
+
176
+ if result.returncode != 0:
177
+ logger.warning(
178
+ f"[frame extracting][{self.saco_yt1b_id}] Failed to extract raw frames: {result.stderr}"
179
+ )
180
+ os.rmdir(self.JPEGImages_6fps_dir)
181
+ return False
182
+
183
+ if len(os.listdir(self.JPEGImages_6fps_dir)) != self.expected_num_frames:
184
+ logger.warning(
185
+ f"[frame extracting][{self.saco_yt1b_id}] Expected {self.expected_num_frames} frames but extracted {len(os.listdir(self.JPEGImages_6fps_dir))}"
186
+ )
187
+ # Clear the directory after failed extraction
188
+ for file in os.listdir(self.JPEGImages_6fps_dir):
189
+ os.remove(os.path.join(self.JPEGImages_6fps_dir, file))
190
+
191
+ os.rmdir(self.JPEGImages_6fps_dir)
192
+ return False
193
+
194
+ logger.info(
195
+ f"[frame extracting][{self.saco_yt1b_id}] Successfully extracted {self.expected_num_frames} frames to {self.JPEGImages_6fps_dir}"
196
+ )
197
+ return True
198
+
199
+
200
+ def main():
201
+ parser = argparse.ArgumentParser()
202
+ parser.add_argument("--saco_yt1b_id", type=str, required=True)
203
+ parser.add_argument(
204
+ "--data_dir",
205
+ type=str,
206
+ required=True,
207
+ )
208
+ parser.add_argument(
209
+ "--cookies_file",
210
+ type=str,
211
+ required=True,
212
+ )
213
+ parser.add_argument(
214
+ "--yt1b_start_end_time_file",
215
+ type=str,
216
+ required=True,
217
+ )
218
+ parser.add_argument(
219
+ "--yt1b_frame_prep_log_file",
220
+ type=str,
221
+ required=True,
222
+ )
223
+ parser.add_argument(
224
+ "--ffmpeg_timeout",
225
+ type=str,
226
+ default=7200, # Use longer timeout in case of large videos processing timeout
227
+ )
228
+ parser.add_argument(
229
+ "--sleep_interval",
230
+ type=int,
231
+ default=10,
232
+ )
233
+ parser.add_argument(
234
+ "--max_sleep_interval",
235
+ type=int,
236
+ default=30,
237
+ )
238
+ args = parser.parse_args()
239
+
240
+ logging.basicConfig(
241
+ filename=args.yt1b_frame_prep_log_file,
242
+ format="%(asctime)s [%(threadName)s] %(levelname)s: %(message)s",
243
+ level=logging.INFO,
244
+ filemode="w",
245
+ )
246
+
247
+ video_prep = YtVideoPrep(
248
+ saco_yt1b_id=args.saco_yt1b_id,
249
+ data_dir=args.data_dir,
250
+ cookies_file=args.cookies_file,
251
+ yt1b_start_end_time_file=args.yt1b_start_end_time_file,
252
+ ffmpeg_timeout=args.ffmpeg_timeout,
253
+ sleep_interval=args.sleep_interval,
254
+ max_sleep_interval=args.max_sleep_interval,
255
+ )
256
+
257
+ status = video_prep.download_youtube_video()
258
+ logger.info(f"[video download][{args.saco_yt1b_id}] download status {status}")
259
+
260
+ status = video_prep.extract_frames_in_6fps_and_width_1080()
261
+ logger.info(
262
+ f"[frame extracting][{args.saco_yt1b_id}] frame extracting status {status}"
263
+ )
264
+
265
+
266
+ if __name__ == "__main__":
267
+ main()