Add files using upload-large-folder tool
Browse filesThis view is limited to 50 files because it contains too many changes. See raw diff
Files changed (50)
- source_code/sam3/assets/veval/toy_gt_and_pred/toy_saco_veval_sav_test_eval_res.jsonAdded+1
- source_code/sam3/examples/saco_gold_silver_eval_example.ipynbAdded
- source_code/sam3/examples/saco_veval_vis_example.ipynbAdded+269
- source_code/sam3/examples/sam3_for_sam1_task_example.ipynbAdded+846
- source_code/sam3/examples/sam3_image_interactive.ipynbAdded+757
- source_code/sam3/examples/sam3_image_predictor_example.ipynbAdded
- source_code/sam3/medsam3_brats/train_sam3_video_lora_ddp.pyAdded+689
- source_code/sam3/sam3.egg-info/SOURCES.txtAdded+51
- source_code/sam3/sam3/agent/__init__.pyAdded+1
- source_code/sam3/sam3/agent/client_llm.pyAdded+205
- source_code/sam3/sam3/agent/client_sam3.pyAdded+138
- source_code/sam3/sam3/agent/helpers/__init__.pyAdded+1
- source_code/sam3/sam3/agent/helpers/memory.pyAdded+87
- source_code/sam3/sam3/agent/system_prompts/system_prompt.txtAdded+242
- source_code/sam3/sam3/agent/system_prompts/system_prompt_iterative_checking.txtAdded+26
- source_code/sam3/sam3/eval/cgf1_eval.pyAdded+703
- source_code/sam3/sam3/eval/conversion_util.pyAdded+211
- source_code/sam3/sam3/eval/hota_eval_toolkit/run_ytvis_eval.pyAdded+114
- source_code/sam3/sam3/eval/hota_eval_toolkit/trackeval/datasets/_base_dataset.pyAdded+379
- source_code/sam3/sam3/eval/hota_eval_toolkit/trackeval/metrics/__init__.pyAdded+4
- source_code/sam3/sam3/eval/postprocessors.pyAdded+648
- source_code/sam3/sam3/eval/saco_veval_evaluators.pyAdded+838
- source_code/sam3/sam3/eval/teta_eval_toolkit/_timing.pyAdded+69
- source_code/sam3/sam3/eval/teta_eval_toolkit/datasets/tao.pyAdded+659
- source_code/sam3/sam3/eval/teta_eval_toolkit/eval.pyAdded+275
- source_code/sam3/sam3/eval/teta_eval_toolkit/metrics/_base_metric.pyAdded+148
- source_code/sam3/sam3/eval/ytvis_eval.pyAdded+411
- source_code/sam3/sam3/model/act_ckpt_utils.pyAdded+114
- source_code/sam3/sam3/model/encoder.pyAdded+594
- source_code/sam3/sam3/model/maskformer_segmentation.pyAdded+323
- source_code/sam3/sam3/model/sam1_task_predictor.pyAdded+458
- source_code/sam3/sam3/model/sam3_image_processor.pyAdded+222
- source_code/sam3/sam3/model/sam3_tracker_utils.pyAdded+427
- source_code/sam3/sam3/model/sam3_tracking_predictor.pyAdded+1368
- source_code/sam3/sam3/model/sam3_video_inference.pyAdded+1709
- source_code/sam3/sam3/model_builder.pyAdded+793
- source_code/sam3/sam3/perflib/__init__.pyAdded+8
- source_code/sam3/sam3/perflib/compile.pyAdded+99
- source_code/sam3/sam3/perflib/fa3.pyAdded+27
- source_code/sam3/sam3/perflib/masks_ops.pyAdded+69
- source_code/sam3/sam3/perflib/nms.pyAdded+91
- source_code/sam3/sam3/perflib/tests/tests.pyAdded+59
- source_code/sam3/sam3/perflib/triton/connected_components.pyAdded+468
- source_code/sam3/sam3/sam/prompt_encoder.pyAdded+243
- source_code/sam3/sam3/train/configs/eval_base.yamlAdded+279
- source_code/sam3/sam3/train/configs/gold_image_evals/sam3_gold_image_attributes.yamlAdded+66
- source_code/sam3/sam3/train/configs/gold_image_evals/sam3_gold_image_metaclip_nps.yamlAdded+66
- source_code/sam3/sam3/train/configs/odinw13/odinw_text_only_positive.yamlAdded+253
- source_code/sam3/sam3/train/configs/odinw13/odinw_visual_only.yamlAdded+256
- source_code/sam3/sam3/train/configs/roboflow_v100/roboflow_v100_full_ft_100_images.yamlAdded+539
1{"dataset_results": {"video_bbox_mAP_50_95": 0.25926449787835926, "video_mask_mAP_50_95": 0.34191419141914187, "video_bbox_phrase_ap_50_95": 0.1371423984673839, "video_bbox_phrase_ap_50": 0.3000915217572178, "video_bbox_phrase_ap_75": 0.08651579443658651, "video_mask_phrase_ap_50_95": 0.1935287184180603, "video_mask_phrase_ap_50": 0.3513242920930748, "video_mask_phrase_ap_75": 0.18776520509193778, "video_mask_teta": 50.647, "video_mask_loc_a": 50.969, "video_mask_assoc_a": 49.191, "video_mask_cls_a": 51.781, "video_mask_loc_re": 53.646, "video_mask_loc_pr": 59.689, "video_mask_assoc_re": 53.932, "video_mask_assoc_pr": 55.295, "video_mask_cls_re": 69.966, "video_mask_cls_pr": 51.792, "video_bbox_all_phrase_HOTA": 0.45019177261810006, "video_bbox_all_phrase_DetA": 0.3065446597162029, "video_bbox_all_phrase_AssA": 0.6620514646913795, "video_bbox_all_phrase_DetRe": 0.34337909467405614, "video_bbox_all_phrase_DetPr": 0.672412162481676, "video_bbox_all_phrase_AssRe": 0.7418235522588219, "video_bbox_all_phrase_AssPr": 0.7588797497822176, "video_bbox_all_phrase_LocA": 0.8264969431924951, "video_bbox_all_phrase_OWTA": 0.4767458776352726, "video_mask_all_phrase_HOTA": 0.4656079602771566, "video_mask_all_phrase_DetA": 0.31732796518831874, "video_mask_all_phrase_AssA": 0.6843555199075559, "video_mask_all_phrase_DetRe": 0.35291773825479045, "video_mask_all_phrase_DetPr": 0.6910909348843808, "video_mask_all_phrase_AssRe": 0.7573349011890161, "video_mask_all_phrase_AssPr": 0.7716315286320553, "video_mask_all_phrase_LocA": 0.8328852506118952, "video_mask_all_phrase_OWTA": 0.4913272309590218, "video_bbox_demo_precision_50_95": 0.3349983250083749, "video_bbox_demo_recall_50_95": 0.20302968778882485, "video_bbox_demo_f1_50_95": 0.2527916520815702, "video_bbox_demo_precision_50": 0.6499967500162499, "video_bbox_demo_recall_50": 0.3939382001872721, "video_bbox_demo_f1_50": 0.49051719921648634, "video_bbox_demo_precision_75": 0.29999850000749995, "video_bbox_demo_recall_75": 0.18181763085566405, "video_bbox_demo_f1_75": 0.2263672578625684, "video_bbox_demo_pmf1_50_95": 0.34412433298399697, "video_bbox_demo_ilmcc_50_95": 0.6546535992794136, "video_bbox_demo_cgf1_50_95": 0.22528223318760104, "video_bbox_demo_pmf1_w0dt_50_95": 0.29496371398628307, "video_bbox_demo_cgf1_w0dt_50_95": 0.19309905701794375, "video_bbox_demo_positive_micro_f1_50_95": 0.2527916520815702, "video_bbox_demo_cgf1_micro_50_95": 0.1654909649029892, "video_bbox_demo_pmf1_50": 0.6499302549834214, "video_bbox_demo_ilmcc_50": 0.6546535992794136, "video_bbox_demo_cgf1_50": 0.42547918070548385, "video_bbox_demo_positive_micro_f1_50": 0.49051719921648634, "video_bbox_demo_cgf1_micro_50": 0.3211188499755299, "video_bbox_demo_pmf1_75": 0.3666121729955099, "video_bbox_demo_ilmcc_75": 0.6546535992794136, "video_bbox_demo_cgf1_75": 0.2400039785911576, "video_bbox_demo_positive_micro_f1_75": 0.2263672578625684, "video_bbox_demo_cgf1_micro_75": 0.14819214011874154, "video_mask_demo_precision_50_95": 0.4049979750101249, "video_mask_demo_recall_50_95": 0.24545380165514646, "video_mask_demo_f1_50_95": 0.30562163642146994, "video_mask_demo_precision_50": 0.6999965000174999, "video_mask_demo_recall_50": 0.4242411386632161, "video_mask_demo_f1_50": 0.5282529055527269, "video_mask_demo_precision_75": 0.39999800000999997, "video_mask_demo_recall_75": 0.24242350780755206, "video_mask_demo_f1_75": 0.3018386687406093, "video_mask_demo_pmf1_50_95": 0.42578319170459134, "video_mask_demo_ilmcc_50_95": 0.6546535992794136, "video_mask_demo_cgf1_50_95": 0.2787404989620873, "video_mask_demo_pmf1_w0dt_50_95": 0.3649570214610783, "video_mask_demo_cgf1_w0dt_50_95": 0.23892042768178906, "video_mask_demo_positive_micro_f1_50_95": 0.30562163642146994, "video_mask_demo_cgf1_micro_50_95": 0.2000763043009796, "video_mask_demo_pmf1_50": 0.691595879731724, "video_mask_demo_ilmcc_50": 0.6546535992794136, "video_mask_demo_cgf1_50": 0.4527557319131855, "video_mask_demo_positive_micro_f1_50": 0.5282529055527269, "video_mask_demo_cgf1_micro_50": 0.34582266594990074, "video_mask_demo_pmf1_75": 0.44161046360299766, "video_mask_demo_ilmcc_75": 0.6546535992794136, "video_mask_demo_cgf1_75": 0.2891018794771529, "video_mask_demo_positive_micro_f1_75": 0.3018386687406093, "video_mask_demo_cgf1_micro_75": 0.19759977089274647}, "video_np_results": [{"video_id": 0, "category_id": 847, "bbox_HOTA": 0.5142922923345529, "bbox_DetA": 0.4728133947307452, "bbox_AssA": 0.5594614107579609, "bbox_DetRe": 0.5232999318999904, "bbox_DetPr": 0.6740601503759398, "bbox_AssRe": 0.6250872094372617, "bbox_AssPr": 0.6825128274969564, "bbox_LocA": 0.7656278351108177, "bbox_OWTA": 0.5404796613713161, "mask_HOTA": 0.5531074184495137, "mask_DetA": 0.5015830888530848, "mask_AssA": 0.6104397175171865, "mask_DetRe": 0.5479132211304601, "mask_DetPr": 0.7057644110275689, "mask_AssRe": 0.6703397116425474, "mask_AssPr": 0.7231025840584305, "mask_LocA": 0.7775805526027232, "mask_OWTA": 0.5779237956098605, "bbox_TP_50_95": 0.8, "bbox_FP_50_95": 3.2, "bbox_FN_50_95": 3.2, "bbox_F1_50_95": 0.2, "bbox_TP_50": 2.0, "bbox_FP_50": 2.0, "bbox_FN_50": 2.0, "bbox_F1_50": 0.5, "bbox_TP_75": 0.0, "bbox_FP_75": 4.0, "bbox_FN_75": 4.0, "bbox_F1_75": 0.0, "mask_TP_50_95": 1.4, "mask_FP_50_95": 2.6, "mask_FN_50_95": 2.6, "mask_F1_50_95": 0.35, "mask_TP_50": 3.0, "mask_FP_50": 1.0, "mask_FN_50": 1.0, "mask_F1_50": 0.75, "mask_TP_75": 0.0, "mask_FP_75": 4.0, "mask_FN_75": 4.0, "mask_F1_75": 0.0}, {"video_id": 0, "category_id": 1390, "bbox_HOTA": 0.7406733177321637, "bbox_DetA": 0.7406733177321637, "bbox_AssA": 0.7406733177321637, "bbox_DetRe": 0.8079854809437387, "bbox_DetPr": 0.8428625520636122, "bbox_AssRe": 0.8079854809437387, "bbox_AssPr": 0.8428625520636122, "bbox_LocA": 0.8823614751992302, "bbox_OWTA": 0.7727325543244231, "mask_HOTA": 0.8154208948182305, "mask_DetA": 0.8154208948182305, "mask_AssA": 0.8154208948182304, "mask_DetRe": 0.8508166969147005, "mask_DetPr": 0.8875425975009466, "mask_AssRe": 0.8508166969147005, "mask_AssPr": 0.8875425975009466, "mask_LocA": 0.8885850303003239, "mask_OWTA": 0.8323023646534773, "bbox_TP_50_95": 0.6, "bbox_FP_50_95": 0.4, "bbox_FN_50_95": 0.4, "bbox_F1_50_95": 0.6, "bbox_TP_50": 1.0, "bbox_FP_50": 0.0, "bbox_FN_50": 0.0, "bbox_F1_50": 1.0, "bbox_TP_75": 1.0, "bbox_FP_75": 0.0, "bbox_FN_75": 0.0, "bbox_F1_75": 1.0, "mask_TP_50_95": 0.8, "mask_FP_50_95": 0.2, "mask_FN_50_95": 0.2, "mask_F1_50_95": 0.8, "mask_TP_50": 1.0, "mask_FP_50": 0.0, "mask_FN_50": 0.0, "mask_F1_50": 1.0, "mask_TP_75": 1.0, "mask_FP_75": 0.0, "mask_FN_75": 0.0, "mask_F1_75": 1.0}, {"video_id": 0, "category_id": 1985, "bbox_HOTA": 0.6033247555682881, "bbox_DetA": 0.582364339356503, "bbox_AssA": 0.6261229142494006, "bbox_DetRe": 0.731940716536352, "bbox_DetPr": 0.6764452113891285, "bbox_AssRe": 0.7595503987929015, "bbox_AssPr": 0.7140399793949845, "bbox_LocA": 0.8359470620317413, "bbox_OWTA": 0.6767785755234768, "mask_HOTA": 0.6327138779062043, "mask_DetA": 0.607379512629533, "mask_AssA": 0.661378852549867, "mask_DetRe": 0.7515462714435757, "mask_DetPr": 0.6945642795513374, "mask_AssRe": 0.7849752407175019, "mask_AssPr": 0.7406062552585059, "mask_LocA": 0.8390964342806022, "mask_OWTA": 0.70480310037791, "bbox_TP_50_95": 1.5, "bbox_FP_50_95": 2.5, "bbox_FN_50_95": 2.5, "bbox_F1_50_95": 0.375, "bbox_TP_50": 4.0, "bbox_FP_50": 0.0, "bbox_FN_50": 0.0, "bbox_F1_50": 1.0, "bbox_TP_75": 1.0, "bbox_FP_75": 3.0, "bbox_FN_75": 3.0, "bbox_F1_75": 0.25, "mask_TP_50_95": 1.7, "mask_FP_50_95": 2.3, "mask_FN_50_95": 2.3, "mask_F1_50_95": 0.425, "mask_TP_50": 4.0, "mask_FP_50": 0.0, "mask_FN_50": 0.0, "mask_F1_50": 1.0, "mask_TP_75": 1.0, "mask_FP_75": 3.0, "mask_FN_75": 3.0, "mask_F1_75": 0.25}, {"video_id": 0, "category_id": 3802, "bbox_HOTA": 0.47649622572399936, "bbox_DetA": 0.433826727090632, "bbox_AssA": 0.5248504404498464, "bbox_DetRe": 0.6931060044477392, "bbox_DetPr": 0.49540798304486033, "bbox_AssRe": 0.5970635788657445, "bbox_AssPr": 0.6521277350832161, "bbox_LocA": 0.8179341001135264, "bbox_OWTA": 0.6029168695170898, "mask_HOTA": 0.48643902599730804, "mask_DetA": 0.45408850965718345, "mask_AssA": 0.5231400608341074, "mask_DetRe": 0.7197924388435877, "mask_DetPr": 0.5144825150123632, "mask_AssRe": 0.5970712271676157, "mask_AssPr": 0.6408536817832409, "mask_LocA": 0.8335384601792232, "mask_OWTA": 0.613243699873648, "bbox_TP_50_95": 1.2, "bbox_FP_50_95": 4.8, "bbox_FN_50_95": 2.8, "bbox_F1_50_95": 0.24000000000000005, "bbox_TP_50": 2.0, "bbox_FP_50": 4.0, "bbox_FN_50": 2.0, "bbox_F1_50": 0.4, "bbox_TP_75": 1.0, "bbox_FP_75": 5.0, "bbox_FN_75": 3.0, "bbox_F1_75": 0.2, "mask_TP_50_95": 1.4, "mask_FP_50_95": 4.6, "mask_FN_50_95": 2.6, "mask_F1_50_95": 0.28, "mask_TP_50": 2.0, "mask_FP_50": 4.0, "mask_FN_50": 2.0, "mask_F1_50": 0.4, "mask_TP_75": 2.0, "mask_FP_75": 4.0, "mask_FN_75": 2.0, "mask_F1_75": 0.4}, {"video_id": 0, "category_id": 3827, "bbox_HOTA": 0.7782356487108129, "bbox_DetA": 0.7707506578022777, "bbox_AssA": 0.7864050337062197, "bbox_DetRe": 0.8251451746704767, "bbox_DetPr": 0.8309663046505151, "bbox_AssRe": 0.8370220441715713, "bbox_AssPr": 0.8427028310094968, "bbox_LocA": 0.8515357797457908, "bbox_OWTA": 0.8052026625060156, "mask_HOTA": 0.7841937402779418, "mask_DetA": 0.7773711399985175, "mask_AssA": 0.7919510612320402, "mask_DetRe": 0.8283712784588442, "mask_DetPr": 0.8342151675485008, "mask_AssRe": 0.8407743682610512, "mask_AssPr": 0.845985151807301, "mask_LocA": 0.851867149412845, "mask_OWTA": 0.8096925025911031, "bbox_TP_50_95": 2.6, "bbox_FP_50_95": 1.4, "bbox_FN_50_95": 1.4, "bbox_F1_50_95": 0.65, "bbox_TP_50": 4.0, "bbox_FP_50": 0.0, "bbox_FN_50": 0.0, "bbox_F1_50": 1.0, "bbox_TP_75": 3.0, "bbox_FP_75": 1.0, "bbox_FN_75": 1.0, "bbox_F1_75": 0.75, "mask_TP_50_95": 2.8, "mask_FP_50_95": 1.2, "mask_FN_50_95": 1.2, "mask_F1_50_95": 0.7, "mask_TP_50": 4.0, "mask_FP_50": 0.0, "mask_FN_50": 0.0, "mask_F1_50": 1.0, "mask_TP_75": 4.0, "mask_FP_75": 0.0, "mask_FN_75": 0.0, "mask_F1_75": 1.0}, {"video_id": 0, "category_id": 49272, "bbox_HOTA": 0.0, "bbox_DetA": 0.0, "bbox_AssA": 0.0, "bbox_DetRe": 0.0, "bbox_DetPr": 0.0, "bbox_AssRe": 0.0, "bbox_AssPr": 0.0, "bbox_LocA": 1.0, "bbox_OWTA": 0.0, "mask_HOTA": 0.0, "mask_DetA": 0.0, "mask_AssA": 0.0, "mask_DetRe": 0.0, "mask_DetPr": 0.0, "mask_AssRe": 0.0, "mask_AssPr": 0.0, "mask_LocA": 1.0, "mask_OWTA": 0.0, "bbox_TP_50_95": 0.0, "bbox_FP_50_95": 0.0, "bbox_FN_50_95": 12.0, "bbox_F1_50_95": 0.0, "bbox_TP_50": 0.0, "bbox_FP_50": 0.0, "bbox_FN_50": 12.0, "bbox_F1_50": 0.0, "bbox_TP_75": 0.0, "bbox_FP_75": 0.0, "bbox_FN_75": 12.0, "bbox_F1_75": 0.0, "mask_TP_50_95": 0.0, "mask_FP_50_95": 0.0, "mask_FN_50_95": 12.0, "mask_F1_50_95": 0.0, "mask_TP_50": 0.0, "mask_FP_50": 0.0, "mask_FN_50": 12.0, "mask_F1_50": 0.0, "mask_TP_75": 0.0, "mask_FP_75": 0.0, "mask_FN_75": 12.0, "mask_F1_75": 0.0}, {"video_id": 0, "category_id": 49504, "bbox_HOTA": 0.0, "bbox_DetA": 0.0, "bbox_AssA": 0.0, "bbox_DetRe": 0.0, "bbox_DetPr": 0.0, "bbox_AssRe": 0.0, "bbox_AssPr": 0.0, "bbox_LocA": 1.0, "bbox_OWTA": 0.0, "mask_HOTA": 0.0, "mask_DetA": 0.0, "mask_AssA": 0.0, "mask_DetRe": 0.0, "mask_DetPr": 0.0, "mask_AssRe": 0.0, "mask_AssPr": 0.0, "mask_LocA": 1.0, "mask_OWTA": 0.0, "bbox_TP_50_95": 0.0, "bbox_FP_50_95": 1.0, "bbox_FN_50_95": 4.0, "bbox_F1_50_95": 0.0, "bbox_TP_50": 0.0, "bbox_FP_50": 1.0, "bbox_FN_50": 4.0, "bbox_F1_50": 0.0, "bbox_TP_75": 0.0, "bbox_FP_75": 1.0, "bbox_FN_75": 4.0, "bbox_F1_75": 0.0, "mask_TP_50_95": 0.0, "mask_FP_50_95": 1.0, "mask_FN_50_95": 4.0, "mask_F1_50_95": 0.0, "mask_TP_50": 0.0, "mask_FP_50": 1.0, "mask_FN_50": 4.0, "mask_F1_50": 0.0, "mask_TP_75": 0.0, "mask_FP_75": 1.0, "mask_FN_75": 4.0, "mask_F1_75": 0.0}, {"video_id": 0, "category_id": 50554, "bbox_TP_50_95": 0.0, "bbox_FP_50_95": 0.0, "bbox_FN_50_95": 0.0, "bbox_F1_50_95": 1.0, "bbox_TP_50": 0.0, "bbox_FP_50": 0.0, "bbox_FN_50": 0.0, "bbox_F1_50": 1.0, "bbox_TP_75": 0.0, "bbox_FP_75": 0.0, "bbox_FN_75": 0.0, "bbox_F1_75": 1.0, "mask_TP_50_95": 0.0, "mask_FP_50_95": 0.0, "mask_FN_50_95": 0.0, "mask_F1_50_95": 1.0, "mask_TP_50": 0.0, "mask_FP_50": 0.0, "mask_FN_50": 0.0, "mask_F1_50": 1.0, "mask_TP_75": 0.0, "mask_FP_75": 0.0, "mask_FN_75": 0.0, "mask_F1_75": 1.0}]}123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269{ "cells": [ { "cell_type": "code", "execution_count": null, "id": "37048f21", "metadata": {}, "outputs": [], "source": [ "# Copyright (c) Meta Platforms, Inc. and affiliates." ] }, { "cell_type": "code", "execution_count": null, "id": "154d8663", "metadata": {}, "outputs": [], "source": [ "using_colab = False" ] }, { "cell_type": "code", "execution_count": null, "id": "b85d99d9", "metadata": {}, "outputs": [], "source": [ "if using_colab:\n", " import torch\n", " import torchvision\n", " print(\"PyTorch version:\", torch.__version__)\n", " print(\"Torchvision version:\", torchvision.__version__)\n", " print(\"CUDA is available:\", torch.cuda.is_available())\n", " import sys\n", " !{sys.executable} -m pip install opencv-python matplotlib scikit-learn\n", " !{sys.executable} -m pip install 'git+https://github.com/facebookresearch/sam3.git'" ] }, { "cell_type": "code", "execution_count": null, "id": "da21a3bc", "metadata": {}, "outputs": [], "source": [ "import os\n", "from glob import glob\n", "\n", "import numpy as np\n", "import utils\n", "\n", "from matplotlib import pyplot as plt\n", "\n", "COLORS = utils.pascal_color_map()[1:]" ] }, { "cell_type": "markdown", "id": "57e85e7e", "metadata": {}, "source": [ "1. Load the data" ] }, { "cell_type": "code", "execution_count": null, "id": "a796734e", "metadata": {}, "outputs": [], "source": [ "# Preapre the data path\n", "DATA_DIR = \"./sam3_saco_veval_data\" # PUT YOUR DATA PATH HERE\n", "ANNOT_DIR = os.path.join(DATA_DIR, \"annotation\")\n", "\n", "# Load the SACO/Veval annotation files\n", "annot_file_list = glob(os.path.join(ANNOT_DIR, \"*veval*.json\"))\n", "annot_dfs = utils.get_annot_dfs(file_list=annot_file_list)" ] }, { "cell_type": "markdown", "id": "74bf92b1", "metadata": {}, "source": [ "Show the annotation files being loaded" ] }, { "cell_type": "code", "execution_count": null, "id": "a95620ec", "metadata": {}, "outputs": [], "source": [ "annot_dfs.keys()" ] }, { "cell_type": "markdown", "id": "5ce211d3", "metadata": {}, "source": [ "2. Examples of the data format" ] }, { "cell_type": "code", "execution_count": null, "id": "6ba749db", "metadata": {}, "outputs": [], "source": [ "annot_dfs[\"saco_veval_yt1b_val\"].keys()" ] }, { "cell_type": "code", "execution_count": null, "id": "4b6dc186", "metadata": {}, "outputs": [], "source": [ "annot_dfs[\"saco_veval_yt1b_val\"][\"info\"]" ] }, { "cell_type": "code", "execution_count": null, "id": "c41091b3", "metadata": {}, "outputs": [], "source": [ "annot_dfs[\"saco_veval_yt1b_val\"][\"videos\"].head(3)" ] }, { "cell_type": "code", "execution_count": null, "id": "a7df5771", "metadata": {}, "outputs": [], "source": [ "annot_dfs[\"saco_veval_yt1b_val\"][\"annotations\"].head(3)" ] }, { "cell_type": "code", "execution_count": null, "id": "24d2861c", "metadata": {}, "outputs": [], "source": [ "annot_dfs[\"saco_veval_yt1b_val\"][\"categories\"].head(3)" ] }, { "cell_type": "code", "execution_count": null, "id": "f9f98f27", "metadata": {}, "outputs": [], "source": [ "annot_dfs[\"saco_veval_yt1b_val\"][\"video_np_pairs\"].head(3)" ] }, { "cell_type": "markdown", "id": "5673a63f", "metadata": {}, "source": [ "3. Visualize the data" ] }, { "cell_type": "code", "execution_count": null, "id": "da827d09", "metadata": {}, "outputs": [], "source": [ "# Select a target dataset\n", "target_dataset_name = \"saco_veval_yt1b_val\"\n", "\n", "# visualize a random positive video-np pair\n", "df_pairs = annot_dfs[target_dataset_name][\"video_np_pairs\"]\n", "df_positive_pairs = df_pairs[df_pairs.num_masklets > 0]\n", "rand_idx = np.random.randint(len(df_positive_pairs))\n", "pair_row = df_positive_pairs.iloc[rand_idx]\n", "video_id = pair_row.video_id\n", "noun_phrase = pair_row.noun_phrase\n", "print(f\"Randomly selected video-np pair: video_id={video_id}, noun_phrase={noun_phrase}\")\n", "\n", "def display_image_in_subplot(img, axes, row, col, title=\"\"):\n", " axes[row, col].imshow(img)\n", " axes[row, col].set_title(title)\n", " axes[row, col].axis('off')\n", "\n", "num_frames_to_show = 5 # Number of frames to show per dataset\n", "every_n_frames = 4 # Interval between frames to show\n", "\n", "fig, axes = plt.subplots(num_frames_to_show, 3, figsize=(15, 5 * num_frames_to_show))\n", "\n", "for idx in range(0, num_frames_to_show):\n", " sampled_frame_idx = idx * every_n_frames\n", " print(f\"Reading annotations for frame {sampled_frame_idx}\")\n", " # Get the frame and the corresponding masks and noun phrases\n", " frame, annot_masks, annot_noun_phrases = utils.get_all_annotations_for_frame(\n", " annot_dfs[target_dataset_name], video_id=video_id, frame_idx=sampled_frame_idx, data_dir=DATA_DIR, dataset=target_dataset_name\n", " )\n", " # Filter masks and noun phrases by the selected noun phrase\n", " annot_masks = [m for m, np in zip(annot_masks, annot_noun_phrases) if np == noun_phrase]\n", "\n", " # Show the frame\n", " display_image_in_subplot(frame, axes, idx, 0, f\"{target_dataset_name} - {noun_phrase} - Frame {sampled_frame_idx}\")\n", "\n", " # Show the annotated masks\n", " if annot_masks is None:\n", " print(f\"No masks found for video_id {video_id} at frame {sampled_frame_idx}\")\n", " else:\n", " # Show all masks over a white background\n", " all_masks = utils.draw_masks_to_frame(\n", " frame=np.ones_like(frame)*255, masks=annot_masks, colors=COLORS[: len(annot_masks)]\n", " )\n", " display_image_in_subplot(all_masks, axes, idx, 1, f\"{target_dataset_name} - {noun_phrase} - Frame {sampled_frame_idx} - Masks\")\n", " \n", " # Show masks overlaid on the frame\n", " masked_frame = utils.draw_masks_to_frame(\n", " frame=frame, masks=annot_masks, colors=COLORS[: len(annot_masks)]\n", " )\n", " display_image_in_subplot(masked_frame, axes, idx, 2, f\"Dataset: {target_dataset_name} - {noun_phrase} - Frame {sampled_frame_idx} - Masks overlaid\")\n", "\n", "plt.tight_layout()\n", "plt.show()" ] }, { "cell_type": "code", "execution_count": null, "id": "a2a23152", "metadata": {}, "outputs": [], "source": [] } ], "metadata": { "kernelspec": { "display_name": "Python 3 (ipykernel)", "language": "python", "name": "python3" }, "language_info": { "codemirror_mode": { "name": "ipython", "version": 3 }, "file_extension": ".py", "mimetype": "text/x-python", "name": "python", "nbconvert_exporter": "python", "pygments_lexer": "ipython3", "version": "3.10.13" } }, "nbformat": 4, "nbformat_minor": 5}123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782783784785786787788789790791792793794795796797798799800801802803804805806807808809810811812813814815816817818819820821822823824825826827828829830831832833834835836837838839840841842843844845846{ "cells": [ { "cell_type": "code", "execution_count": null, "id": "f400486b", "metadata": {}, "outputs": [], "source": [ "# Copyright (c) Meta Platforms, Inc. and affiliates." ] }, { "cell_type": "markdown", "id": "a1ae39ff", "metadata": { "jp-MarkdownHeadingCollapsed": true }, "source": [ "# Interactive Instance Segmentation using SAM 3" ] }, { "cell_type": "markdown", "id": "b4a4b25c", "metadata": {}, "source": [ "Segment Anything Model 3 (SAM 3) predicts instance masks that indicate the desired object given geometric prompts (SAM 1 task).\n", "The `SAM3Image` and `Sam3Processor` classes provide an easy interface to prompt the model. The user first sets an image using the `Sam3Processor.set_image` method, which computes the necessary image embeddings. Then, prompts can be provided via the `predict` method to efficiently predict masks from those prompts. The model can take as input both point and box prompts, as well as masks from the previous iteration of prediction.\n", "\n", "This notebook follows the SAM 2 API for interactive image segmentation.\n", "\n", "# <a target=\"_blank\" href=\"https://colab.research.google.com/github/facebookresearch/sam3/blob/main/notebooks/sam3_for_sam1_task_example.ipynb\">\n", "# <img src=\"https://colab.research.google.com/assets/colab-badge.svg\" alt=\"Open In Colab\"/>\n", "# </a>\n" ] }, { "cell_type": "markdown", "id": "644532a8", "metadata": {}, "source": [ "## Environment Set-up" ] }, { "cell_type": "markdown", "id": "07fabfee", "metadata": {}, "source": [ "First install `sam3` in your environment using the [installation instructions](https://github.com/facebookresearch/sam3?tab=readme-ov-file#installation) in the repository." ] }, { "cell_type": "markdown", "id": "0be845da", "metadata": {}, "source": [ "## Set-up" ] }, { "cell_type": "markdown", "id": "33681dd1", "metadata": {}, "source": [ "Necessary imports and helper functions for displaying points, boxes, and masks." ] }, { "cell_type": "code", "execution_count": null, "id": "fe773ede", "metadata": {}, "outputs": [], "source": [ "using_colab = False" ] }, { "cell_type": "code", "execution_count": null, "id": "79250a4e", "metadata": {}, "outputs": [], "source": [ "if using_colab:\n", " import torch\n", " import torchvision\n", " print(\"PyTorch version:\", torch.__version__)\n", " print(\"Torchvision version:\", torchvision.__version__)\n", " print(\"CUDA is available:\", torch.cuda.is_available())\n", " import sys\n", " !{sys.executable} -m pip install opencv-python matplotlib scikit-learn\n", " !{sys.executable} -m pip install 'git+https://github.com/facebookresearch/sam3.git'" ] }, { "cell_type": "code", "execution_count": null, "id": "69b28288", "metadata": {}, "outputs": [], "source": [ "import os\n", "# if using Apple MPS, fall back to CPU for unsupported ops\n", "os.environ[\"PYTORCH_ENABLE_MPS_FALLBACK\"] = \"1\"\n", "import numpy as np\n", "import torch\n", "import matplotlib.pyplot as plt\n", "from PIL import Image\n", "import sam3\n", "sam3_root = os.path.join(os.path.dirname(sam3.__file__), \"..\")\n" ] }, { "cell_type": "code", "execution_count": null, "id": "33a15e2f-c7e1-4e5d-862f-fcb751a60b89", "metadata": {}, "outputs": [], "source": [ "# select the device for computation\n", "if torch.cuda.is_available():\n", " device = torch.device(\"cuda\")\n", "elif torch.backends.mps.is_available():\n", " device = torch.device(\"mps\")\n", "else:\n", " device = torch.device(\"cpu\")\n", "print(f\"using device: {device}\")\n", "\n", "if device.type == \"cuda\":\n", " # use bfloat16 for the entire notebook\n", " torch.autocast(\"cuda\", dtype=torch.bfloat16).__enter__()\n", " # turn on tfloat32 for Ampere GPUs (https://pytorch.org/docs/stable/notes/cuda.html#tensorfloat-32-tf32-on-ampere-devices)\n", " if torch.cuda.get_device_properties(0).major >= 8:\n", " torch.backends.cuda.matmul.allow_tf32 = True\n", " torch.backends.cudnn.allow_tf32 = True\n", "elif device.type == \"mps\":\n", " print(\n", " \"\\nSupport for MPS devices is preliminary. SAM 3 is trained with CUDA and might \"\n", " \"give numerically different outputs and sometimes degraded performance on MPS. \"\n", " \"See e.g. https://github.com/pytorch/pytorch/issues/84936 for a discussion.\"\n", " )" ] }, { "cell_type": "code", "execution_count": null, "id": "29bc90d5", "metadata": {}, "outputs": [], "source": [ "np.random.seed(3)\n", "\n", "def show_mask(mask, ax, random_color=False, borders = True):\n", " if random_color:\n", " color = np.concatenate([np.random.random(3), np.array([0.6])], axis=0)\n", " else:\n", " color = np.array([30/255, 144/255, 255/255, 0.6])\n", " h, w = mask.shape[-2:]\n", " mask = mask.astype(np.uint8)\n", " mask_image = mask.reshape(h, w, 1) * color.reshape(1, 1, -1)\n", " if borders:\n", " import cv2\n", " contours, _ = cv2.findContours(mask,cv2.RETR_EXTERNAL, cv2.CHAIN_APPROX_NONE) \n", " # Try to smooth contours\n", " contours = [cv2.approxPolyDP(contour, epsilon=0.01, closed=True) for contour in contours]\n", " mask_image = cv2.drawContours(mask_image, contours, -1, (1, 1, 1, 0.5), thickness=2) \n", " ax.imshow(mask_image)\n", "\n", "def show_points(coords, labels, ax, marker_size=375):\n", " pos_points = coords[labels==1]\n", " neg_points = coords[labels==0]\n", " ax.scatter(pos_points[:, 0], pos_points[:, 1], color='green', marker='*', s=marker_size, edgecolor='white', linewidth=1.25)\n", " ax.scatter(neg_points[:, 0], neg_points[:, 1], color='red', marker='*', s=marker_size, edgecolor='white', linewidth=1.25) \n", "\n", "def show_box(box, ax):\n", " x0, y0 = box[0], box[1]\n", " w, h = box[2] - box[0], box[3] - box[1]\n", " ax.add_patch(plt.Rectangle((x0, y0), w, h, edgecolor='green', facecolor=(0, 0, 0, 0), lw=2)) \n", "\n", "def show_masks(image, masks, scores, point_coords=None, box_coords=None, input_labels=None, borders=True):\n", " for i, (mask, score) in enumerate(zip(masks, scores)):\n", " plt.figure(figsize=(10, 10))\n", " plt.imshow(image)\n", " show_mask(mask, plt.gca(), borders=borders)\n", " if point_coords is not None:\n", " assert input_labels is not None\n", " show_points(point_coords, input_labels, plt.gca())\n", " if box_coords is not None:\n", " # boxes\n", " show_box(box_coords, plt.gca())\n", " if len(scores) > 1:\n", " plt.title(f\"Mask {i+1}, Score: {score:.3f}\", fontsize=18)\n", " plt.axis('off')\n", " plt.show()" ] }, { "cell_type": "markdown", "id": "23842fb2", "metadata": {}, "source": [ "## Example image" ] }, { "cell_type": "code", "execution_count": null, "id": "3c2e4f6b", "metadata": {}, "outputs": [], "source": [ "image = Image.open(f\"{sam3_root}/assets/images/truck.jpg\")" ] }, { "cell_type": "code", "execution_count": null, "id": "e30125fd", "metadata": {}, "outputs": [], "source": [ "plt.figure(figsize=(10, 10))\n", "plt.imshow(image)\n", "plt.axis('on')\n", "plt.show()" ] }, { "cell_type": "markdown", "id": "98b228b8", "metadata": {}, "source": [ "## Selecting objects with SAM 3" ] }, { "cell_type": "markdown", "id": "0bb1927b", "metadata": {}, "source": [ "First, load the SAM 3 model. Running on CUDA and using the default model are recommended for best results." ] }, { "cell_type": "code", "execution_count": null, "id": "7e28150b", "metadata": {}, "outputs": [], "source": [ "from sam3 import build_sam3_image_model\n", "from sam3.model.sam3_image_processor import Sam3Processor\n", "\n", "bpe_path = f\"{sam3_root}/assets/bpe_simple_vocab_16e6.txt.gz\"\n", "model = build_sam3_image_model(bpe_path=bpe_path, enable_inst_interactivity=True)\n" ] }, { "cell_type": "markdown", "id": "c925e829", "metadata": {}, "source": [ "Process the image to produce an image embedding by calling `Sam3Processor.set_image`." ] }, { "cell_type": "code", "execution_count": null, "id": "d95d48dd", "metadata": {}, "outputs": [], "source": [ "processor = Sam3Processor(model)\n", "inference_state = processor.set_image(image)" ] }, { "cell_type": "markdown", "id": "d8fc7a46", "metadata": {}, "source": [ "To select the truck, choose a point on it. Points are input to the model in (x,y) format and come with labels 1 (foreground point) or 0 (background point). Multiple points can be input; here we use only one. The chosen point will be shown as a star on the image." ] }, { "cell_type": "code", "execution_count": null, "id": "5c69570c", "metadata": {}, "outputs": [], "source": [ "input_point = np.array([[520, 375]])\n", "input_label = np.array([1])" ] }, { "cell_type": "code", "execution_count": null, "id": "a91ba973", "metadata": {}, "outputs": [], "source": [ "plt.figure(figsize=(10, 10))\n", "plt.imshow(image)\n", "show_points(input_point, input_label, plt.gca())\n", "plt.axis('on')\n", "plt.show() " ] }, { "cell_type": "markdown", "id": "c765e952", "metadata": {}, "source": [ "Predict with `SAM3Image.predict_inst`. The model returns masks, quality predictions for those masks, and low resolution mask logits that can be passed to the next iteration of prediction." ] }, { "cell_type": "code", "execution_count": null, "id": "5373fd68", "metadata": {}, "outputs": [], "source": [ "masks, scores, logits = model.predict_inst(\n", " inference_state,\n", " point_coords=input_point,\n", " point_labels=input_label,\n", " multimask_output=True,\n", ")\n", "sorted_ind = np.argsort(scores)[::-1]\n", "masks = masks[sorted_ind]\n", "scores = scores[sorted_ind]\n", "logits = logits[sorted_ind]" ] }, { "cell_type": "markdown", "id": "c7f0e938", "metadata": {}, "source": [ "With `multimask_output=True` (the default setting), SAM 3 outputs 3 masks, where `scores` gives the model's own estimation of the quality of these masks. This setting is intended for ambiguous input prompts, and helps the model disambiguate different objects consistent with the prompt. When `False`, it will return a single mask. For ambiguous prompts such as a single point, it is recommended to use `multimask_output=True` even if only a single mask is desired; the best single mask can be chosen by picking the one with the highest score returned in `scores`. This will often result in a better mask." ] }, { "cell_type": "code", "execution_count": null, "id": "47821187", "metadata": {}, "outputs": [], "source": [ "masks.shape # (number_of_masks) x H x W" ] }, { "cell_type": "code", "execution_count": null, "id": "e9c227a6", "metadata": {}, "outputs": [], "source": [ "show_masks(image, masks, scores, point_coords=input_point, input_labels=input_label, borders=True)" ] }, { "cell_type": "markdown", "id": "3fa31f7c", "metadata": {}, "source": [ "## Specifying a specific object with additional points" ] }, { "cell_type": "markdown", "id": "88d6d29a", "metadata": {}, "source": [ "The single input point is ambiguous, and the model has returned multiple objects consistent with it. To obtain a single object, multiple points can be provided. If available, a mask from a previous iteration can also be supplied to the model to aid in prediction. When specifying a single object with multiple prompts, a single mask can be requested by setting `multimask_output=False`." ] }, { "cell_type": "code", "execution_count": null, "id": "f6923b94", "metadata": {}, "outputs": [], "source": [ "input_point = np.array([[500, 375], [1125, 625]])\n", "input_label = np.array([1, 1])\n", "\n", "mask_input = logits[np.argmax(scores), :, :] # Choose the model's best mask" ] }, { "cell_type": "code", "execution_count": null, "id": "d98f96a1", "metadata": {}, "outputs": [], "source": [ "masks, scores, _ = model.predict_inst(\n", " inference_state,\n", " point_coords=input_point,\n", " point_labels=input_label,\n", " mask_input=mask_input[None, :, :],\n", " multimask_output=False,\n", ")" ] }, { "cell_type": "code", "execution_count": null, "id": "0ce8b82f", "metadata": {}, "outputs": [], "source": [ "masks.shape" ] }, { "cell_type": "code", "execution_count": null, "id": "e06d5c8d", "metadata": {}, "outputs": [], "source": [ "show_masks(image, masks, scores, point_coords=input_point, input_labels=input_label)" ] }, { "cell_type": "markdown", "id": "c93e2087", "metadata": {}, "source": [ "To exclude the car and specify just the window, a background point (with label 0, here shown in red) can be supplied." ] }, { "cell_type": "code", "execution_count": null, "id": "9a196f68", "metadata": {}, "outputs": [], "source": [ "input_point = np.array([[500, 375], [1125, 625]])\n", "input_label = np.array([1, 0])\n", "\n", "mask_input = logits[np.argmax(scores), :, :] # Choose the model's best mask" ] }, { "cell_type": "code", "execution_count": null, "id": "81a52282", "metadata": {}, "outputs": [], "source": [ "masks, scores, _ = model.predict_inst(\n", " inference_state,\n", " point_coords=input_point,\n", " point_labels=input_label,\n", " mask_input=mask_input[None, :, :],\n", " multimask_output=False,\n", ")" ] }, { "cell_type": "code", "execution_count": null, "id": "bfca709f", "metadata": {}, "outputs": [], "source": [ "show_masks(image, masks, scores, point_coords=input_point, input_labels=input_label)" ] }, { "cell_type": "markdown", "id": "41e2d5a9", "metadata": {}, "source": [ "## Specifying a specific object with a box" ] }, { "cell_type": "markdown", "id": "d61ca7ac", "metadata": {}, "source": [ "The model can also take a box as input, provided in xyxy format." ] }, { "cell_type": "code", "execution_count": null, "id": "8ea92a7b", "metadata": {}, "outputs": [], "source": [ "input_box = np.array([425, 600, 700, 875])" ] }, { "cell_type": "code", "execution_count": null, "id": "b35a8814", "metadata": {}, "outputs": [], "source": [ "masks, scores, _ = model.predict_inst(\n", " inference_state,\n", " point_coords=None,\n", " point_labels=None,\n", " box=input_box[None, :],\n", " multimask_output=False,\n", ")" ] }, { "cell_type": "code", "execution_count": null, "id": "3ffb4906", "metadata": {}, "outputs": [], "source": [ "show_masks(image, masks, scores, box_coords=input_box)" ] }, { "cell_type": "markdown", "id": "c1ed9f0a", "metadata": {}, "source": [ "## Combining points and boxes" ] }, { "cell_type": "markdown", "id": "8455d1c5", "metadata": {}, "source": [ "Points and boxes may be combined, just by including both types of prompts to the predictor. Here this can be used to select just the trucks's tire, instead of the entire wheel." ] }, { "cell_type": "code", "execution_count": null, "id": "90e2e547", "metadata": {}, "outputs": [], "source": [ "input_box = np.array([425, 600, 700, 875])\n", "input_point = np.array([[575, 750]])\n", "input_label = np.array([0])" ] }, { "cell_type": "code", "execution_count": null, "id": "6956d8c4", "metadata": {}, "outputs": [], "source": [ "masks, scores, logits = model.predict_inst(\n", " inference_state,\n", " point_coords=input_point,\n", " point_labels=input_label,\n", " box=input_box,\n", " multimask_output=False,\n", ")" ] }, { "cell_type": "code", "execution_count": null, "id": "eb519a31", "metadata": {}, "outputs": [], "source": [ "show_masks(image, masks, scores, box_coords=input_box, point_coords=input_point, input_labels=input_label)" ] }, { "cell_type": "markdown", "id": "45ddbca3", "metadata": {}, "source": [ "## Batched prompt inputs" ] }, { "cell_type": "markdown", "id": "df6f18a0", "metadata": {}, "source": [ "`SAM3Image` can take multiple input prompts for the same image, using `predict_inst` method. For example, imagine we have several box outputs from an object detector." ] }, { "cell_type": "code", "execution_count": null, "id": "0a06681b", "metadata": {}, "outputs": [], "source": [ "input_boxes = np.array([\n", " [75, 275, 1725, 850],\n", " [425, 600, 700, 875],\n", " [1375, 550, 1650, 800],\n", " [1240, 675, 1400, 750],\n", "])" ] }, { "cell_type": "code", "execution_count": null, "id": "117521a3", "metadata": {}, "outputs": [], "source": [ "masks, scores, _ = model.predict_inst(\n", " inference_state,\n", " point_coords=None,\n", " point_labels=None,\n", " box=input_boxes,\n", " multimask_output=False,\n", ")" ] }, { "cell_type": "code", "execution_count": null, "id": "6a8f5d49", "metadata": {}, "outputs": [], "source": [ "masks.shape # (batch_size) x (num_predicted_masks_per_input) x H x W" ] }, { "cell_type": "code", "execution_count": null, "id": "c00c3681", "metadata": {}, "outputs": [], "source": [ "plt.figure(figsize=(10, 10))\n", "plt.imshow(image)\n", "for mask in masks:\n", " show_mask(mask.squeeze(0), plt.gca(), random_color=True)\n", "for box in input_boxes:\n", " show_box(box, plt.gca())\n", "plt.axis('off')\n", "plt.show()" ] }, { "cell_type": "markdown", "id": "b9a27b5d", "metadata": {}, "source": [ "## End-to-end batched inference\n", "If all prompts are available in advance, it is possible to run SAM 3 directly in an end-to-end fashion. This also allows batching over images." ] }, { "cell_type": "code", "execution_count": null, "id": "d485f75b", "metadata": {}, "outputs": [], "source": [ "image1 = image # truck.jpg from above\n", "image1_boxes = np.array([\n", " [75, 275, 1725, 850],\n", " [425, 600, 700, 875],\n", " [1375, 550, 1650, 800],\n", " [1240, 675, 1400, 750],\n", "])\n", "\n", "image2 = Image.open(f\"{sam3_root}/assets/images/groceries.jpg\")\n", "image2_boxes = np.array([\n", " [450, 170, 520, 350],\n", " [350, 190, 450, 350],\n", " [500, 170, 580, 350],\n", " [580, 170, 640, 350],\n", "])\n", "\n", "img_batch = [image1, image2]\n", "boxes_batch = [image1_boxes, image2_boxes]" ] }, { "cell_type": "code", "execution_count": null, "id": "47932c99", "metadata": {}, "outputs": [], "source": [ "inference_state = processor.set_image_batch(img_batch)" ] }, { "cell_type": "code", "execution_count": null, "id": "97af3c54", "metadata": {}, "outputs": [], "source": [ "masks_batch, scores_batch, _ = model.predict_inst_batch(\n", " inference_state,\n", " None,\n", " None, \n", " box_batch=boxes_batch, \n", " multimask_output=False\n", ")" ] }, { "cell_type": "code", "execution_count": null, "id": "226df881", "metadata": {}, "outputs": [], "source": [ "for image, boxes, masks in zip(img_batch, boxes_batch, masks_batch):\n", " plt.figure(figsize=(10, 10))\n", " plt.imshow(image) \n", " for mask in masks:\n", " show_mask(mask.squeeze(0), plt.gca(), random_color=True)\n", " for box in boxes:\n", " show_box(box, plt.gca())" ] }, { "cell_type": "markdown", "id": "46f30085", "metadata": {}, "source": [ "Similarly, we can have a batch of point prompts defined over a batch of images" ] }, { "cell_type": "code", "execution_count": null, "id": "1ab929fc", "metadata": {}, "outputs": [], "source": [ "image1 = image # truck.jpg from above\n", "image1_pts = np.array([\n", " [[500, 375]],\n", " [[650, 750]]\n", " ]) # Bx1x2 where B corresponds to number of objects \n", "image1_labels = np.array([[1], [1]])\n", "\n", "image2_pts = np.array([\n", " [[400, 300]],\n", " [[630, 300]],\n", "])\n", "image2_labels = np.array([[1], [1]])\n", "\n", "pts_batch = [image1_pts, image2_pts]\n", "labels_batch = [image1_labels, image2_labels]" ] }, { "cell_type": "code", "execution_count": null, "id": "848f8287", "metadata": {}, "outputs": [], "source": [ "masks_batch, scores_batch, _ = model.predict_inst_batch(inference_state, pts_batch, labels_batch, box_batch=None, multimask_output=True)\n", "\n", "# Select the best single mask per object\n", "best_masks = []\n", "for masks, scores in zip(masks_batch,scores_batch):\n", " best_masks.append(masks[range(len(masks)), np.argmax(scores, axis=-1)])" ] }, { "cell_type": "code", "execution_count": null, "id": "99b15c6c", "metadata": {}, "outputs": [], "source": [ "for image, points, labels, masks in zip(img_batch, pts_batch, labels_batch, best_masks):\n", " plt.figure(figsize=(10, 10))\n", " plt.imshow(image) \n", " for mask in masks:\n", " show_mask(mask, plt.gca(), random_color=True)\n", " show_points(points, labels, plt.gca())" ] }, { "cell_type": "code", "execution_count": null, "id": "4c1594a5-a0de-4477-91d4-db4504a78a83", "metadata": {}, "outputs": [], "source": [] }, { "cell_type": "code", "execution_count": null, "id": "74e3d07e-b0de-48a5-9d29-d639a0dbcdfc", "metadata": {}, "outputs": [], "source": [] }, { "cell_type": "code", "execution_count": null, "id": "d8b1de3a-a253-48ff-8a1c-d80742acbe86", "metadata": {}, "outputs": [], "source": [] } ], "metadata": { "kernelspec": { "display_name": "Python 3 (ipykernel)", "language": "python", "name": "python3" }, "language_info": { "codemirror_mode": { "name": "ipython", "version": 3 }, "file_extension": ".py", "mimetype": "text/x-python", "name": "python", "nbconvert_exporter": "python", "pygments_lexer": "ipython3", "version": "3.12.11" } }, "nbformat": 4, "nbformat_minor": 5}123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757{ "cells": [ { "cell_type": "code", "execution_count": 1, "id": "5d0e0b69", "metadata": {}, "outputs": [], "source": [ "# Copyright (c) Meta Platforms, Inc. and affiliates." ] }, { "cell_type": "markdown", "id": "11912666", "metadata": {}, "source": [ "# <a target=\"_blank\" href=\"https://colab.research.google.com/github/facebookresearch/sam3/blob/main/notebooks/sam3_image_interactive.ipynb\">\n", "# <img src=\"https://colab.research.google.com/assets/colab-badge.svg\" alt=\"Open In Colab\"/>\n", "# </a>" ] }, { "cell_type": "code", "execution_count": 2, "id": "8517f5f6", "metadata": {}, "outputs": [], "source": [ "using_colab = False" ] }, { "cell_type": "code", "execution_count": 3, "id": "2540e376", "metadata": {}, "outputs": [], "source": [ "if using_colab:\n", " import torch\n", " import torchvision\n", " print(\"PyTorch version:\", torch.__version__)\n", " print(\"Torchvision version:\", torchvision.__version__)\n", " print(\"CUDA is available:\", torch.cuda.is_available())\n", " import sys\n", " !{sys.executable} -m pip install opencv-python matplotlib scikit-learn\n", " !{sys.executable} -m pip install 'git+https://github.com/facebookresearch/sam3.git'" ] }, { "cell_type": "code", "execution_count": 4, "id": "90073483-58f6-404e-90ac-c22efcd76216", "metadata": {}, "outputs": [], "source": [ "%matplotlib widget" ] }, { "cell_type": "code", "execution_count": 5, "id": "13325376-658b-48d6-8528-2a006f223d44", "metadata": {}, "outputs": [], "source": [ "import torch\n", "# turn on tfloat32 for Ampere GPUs\n", "# https://pytorch.org/docs/stable/notes/cuda.html#tensorfloat-32-tf32-on-ampere-devices\n", "torch.backends.cuda.matmul.allow_tf32 = True\n", "torch.backends.cudnn.allow_tf32 = True\n", "\n", "# use bfloat16 for the entire notebook. If your card doesn't support it, try float16 instead\n", "torch.autocast(\"cuda\", dtype=torch.bfloat16).__enter__()\n", "\n", "# inference mode for the whole notebook. Disable if you need gradients\n", "torch.inference_mode().__enter__()" ] }, { "cell_type": "markdown", "id": "fb863772-56a9-4ee2-be52-5d8933066519", "metadata": {}, "source": [ "# Load the model" ] }, { "cell_type": "code", "execution_count": 6, "id": "f84b4ccc-9db2-4d88-ac8f-4c272694d25a", "metadata": {}, "outputs": [], "source": [ "import sam3\n", "from sam3 import build_sam3_image_model\n", "import os\n", "sam3_root = os.path.join(os.path.dirname(sam3.__file__), \"..\")\n", "bpe_path = f\"{sam3_root}/assets/bpe_simple_vocab_16e6.txt.gz\"" ] }, { "cell_type": "code", "execution_count": 7, "id": "de01a36e-1221-4497-a5ab-e6c796689480", "metadata": {}, "outputs": [], "source": [ "model = build_sam3_image_model(bpe_path=bpe_path)" ] }, { "cell_type": "code", "execution_count": 8, "id": "b01ec8a9-d9f6-4baf-96ac-1e5d21fd90b8", "metadata": {}, "outputs": [], "source": [ "from sam3.model.sam3_image_processor import Sam3Processor\n", "processor = Sam3Processor(model)" ] }, { "cell_type": "markdown", "id": "e6172a69-35ca-487c-bd67-6f1f1ecb20d5", "metadata": {}, "source": [ "# Jupyter widget" ] }, { "cell_type": "code", "execution_count": 9, "id": "2a4ac22f-5d5c-4272-a5a1-dfe0c04253a7", "metadata": {}, "outputs": [], "source": [ "import io\n", "\n", "import ipywidgets as widgets\n", "import matplotlib.pyplot as plt\n", "import numpy as np\n", "import PIL.Image\n", "import requests\n", "from IPython.display import clear_output, display, HTML\n", "from matplotlib.patches import Rectangle\n", "\n", "\n", "class Sam3SegmentationWidget:\n", " \"\"\"Interactive Jupyter widget for SAM3 segmentation with text and box prompts.\"\"\"\n", "\n", " def __init__(self, processor):\n", " \"\"\"\n", " Initialize the segmentation widget.\n", "\n", " Args:\n", " processor: Sam3Processor instance\n", " \"\"\"\n", " self.processor = processor\n", " self.state = None\n", " self.current_image = None\n", " self.current_image_array = None\n", " self.box_mode = \"positive\"\n", " self.drawing_box = False\n", " self.box_start = None\n", " self.current_rect = None\n", "\n", " self._setup_ui()\n", " self._setup_plot()\n", "\n", " def _setup_ui(self):\n", " \"\"\"Set up the UI components.\"\"\"\n", " self.upload_widget = widgets.FileUpload(\n", " accept=\"image/*\", multiple=False, description=\"Upload Image\"\n", " )\n", " self.upload_widget.observe(self._on_image_upload, names=\"value\")\n", "\n", " self.url_input = widgets.Text(\n", " placeholder=\"Or enter image URL\",\n", " )\n", " self.url_button = widgets.Button(description=\"Load URL\", button_style=\"info\")\n", " self.url_button.on_click(self._on_load_url)\n", " url_box = widgets.HBox(\n", " [self.url_input, self.url_button],\n", " layout=widgets.Layout(width=\"100%\", justify_content=\"space-between\"),\n", " )\n", "\n", " self.text_input = widgets.Text(\n", " placeholder='Enter segmentation prompt (e.g., \"person\", \"dog\")',\n", " continuous_update=False,\n", " )\n", " self.text_input.observe(self._on_text_submit, names=\"value\")\n", " self.text_button = widgets.Button(description=\"Segment\", button_style=\"success\")\n", " self.text_button.on_click(self._on_text_prompt)\n", " text_box = widgets.HBox(\n", " [self.text_input, self.text_button],\n", " layout=widgets.Layout(width=\"100%\", justify_content=\"space-between\"),\n", " )\n", "\n", " self.box_mode_buttons = widgets.ToggleButtons(\n", " options=[\"Positive Boxes\", \"Negative Boxes\"],\n", " description=\"Box Mode:\",\n", " button_style=\"\",\n", " tooltips=[\n", " \"Draw boxes around objects to include\",\n", " \"Draw boxes around objects to exclude\",\n", " ],\n", " )\n", " self.box_mode_buttons.observe(self._on_box_mode_change, names=\"value\")\n", "\n", " self.clear_button = widgets.Button(\n", " description=\"Clear All Prompts\", button_style=\"warning\"\n", " )\n", " self.clear_button.on_click(self._on_clear_prompts)\n", "\n", " self.confidence_slider = widgets.FloatSlider(\n", " value=0.5,\n", " min=0.0,\n", " max=1.0,\n", " step=0.01,\n", " description=\"Confidence:\",\n", " continuous_update=False,\n", " style={\"description_width\": \"initial\"},\n", " )\n", " self.confidence_slider.observe(self._on_confidence_change, names=\"value\")\n", "\n", " self.size_slider = widgets.IntSlider(\n", " value=960,\n", " min=300,\n", " max=2000,\n", " step=10,\n", " description=\"Image Size:\",\n", " continuous_update=False,\n", " style={\"description_width\": \"initial\"},\n", " )\n", " self.size_slider.observe(self._on_size_change, names=\"value\")\n", "\n", " slider_box = widgets.HBox(\n", " [self.confidence_slider, self.size_slider],\n", " layout=widgets.Layout(justify_content=\"space-between\"),\n", " )\n", "\n", " self.output = widgets.Output()\n", " self.status_label = widgets.Label(value=\"Upload an image to begin\")\n", "\n", " # This box will hold our matplotlib output and we can target it with CSS.\n", " self.plot_container = widgets.Box([self.output])\n", " self.plot_container.add_class(\"no-drag\")\n", "\n", " # CSS to make the cursor a crosshair over the matplotlib canvas\n", " css_style = widgets.HTML(\n", " \"\"\"\n", " <style>\n", " .jupyter-matplotlib-canvas, canvas {\n", " cursor: crosshair !important;\n", " }\n", " </style>\n", " \"\"\"\n", " )\n", " # Create VBoxes for each accordion pane\n", " source_pane = widgets.VBox([self.upload_widget, url_box])\n", " prompt_pane = widgets.VBox(\n", " [\n", " widgets.Label(\"Text Prompt:\"),\n", " text_box,\n", " self.box_mode_buttons,\n", " self.confidence_slider,\n", " self.clear_button,\n", " ]\n", " )\n", " display_pane = widgets.VBox([self.size_slider])\n", "\n", " # Create the Accordion to hold the control panes\n", " self.accordion = widgets.Accordion(\n", " children=[source_pane, prompt_pane, display_pane]\n", " )\n", " self.accordion.set_title(0, \"Image Source\")\n", " self.accordion.set_title(1, \"Segmentation Prompts\")\n", " self.accordion.set_title(2, \"Display Settings\")\n", " self.accordion.selected_index = 0 # Start with the first pane open\n", "\n", " # Create the left sidebar for controls\n", " sidebar = widgets.VBox(\n", " [self.status_label, widgets.HTML(\"<h4>Controls</h4>\"), self.accordion]\n", " )\n", " sidebar.layout = widgets.Layout(\n", " width=\"380px\",\n", " min_width=\"380px\",\n", " max_width=\"380px\",\n", " border=\"1px solid #e0e0e0\",\n", " padding=\"10px\",\n", " margin=\"0 15px 0 0\",\n", " flex=\"0 0 auto\",\n", " )\n", "\n", " # Create the main area for the image display\n", " main_area = widgets.VBox([self.plot_container])\n", " main_area.layout = widgets.Layout(flex=\"1\", min_width=\"500px\", overflow=\"auto\")\n", "\n", " # Combine sidebar and main area into the final app layout\n", " app_layout = widgets.HBox([sidebar, main_area])\n", " app_layout.layout = widgets.Layout(\n", " width=\"100%\",\n", " display=\"flex\",\n", " flex_flow=\"row\",\n", " align_items=\"stretch\",\n", " )\n", "\n", " # Set the main container\n", " self.container = widgets.VBox(\n", " [\n", " css_style,\n", " widgets.HTML(\"<h3>🖼️ SAM3 Interactive Segmentation</h3>\"),\n", " app_layout,\n", " ]\n", " )\n", "\n", " def _setup_plot(self):\n", " \"\"\"Set up the matplotlib figure.\"\"\"\n", " # plt.ioff()\n", " self.fig, self.ax = plt.subplots(figsize=(12, 8))\n", " # plt.ion()\n", " self.ax.axis(\"off\")\n", " self.fig.subplots_adjust(left=0, right=1, top=1, bottom=0)\n", " self.fig.canvas.toolbar_visible = False\n", " self.fig.canvas.header_visible = False\n", " self.fig.canvas.footer_visible = False\n", " self.fig.canvas.resizable = False\n", "\n", " # plt.close(self.fig)\n", "\n", " def _set_loading(self, is_loading, message=\"Processing...\"):\n", " \"\"\"Show/hide loading state and disable/enable controls.\"\"\"\n", " if is_loading:\n", " self.status_label.value = f\"⏳ {message}\"\n", " self.upload_widget.disabled = True\n", " self.url_button.disabled = True\n", " self.text_button.disabled = True\n", " self.clear_button.disabled = True\n", " self.box_mode_buttons.disabled = True\n", " self.confidence_slider.disabled = True\n", " else:\n", " self.upload_widget.disabled = False\n", " self.url_button.disabled = False\n", " self.text_button.disabled = False\n", " self.clear_button.disabled = False\n", " self.box_mode_buttons.disabled = False\n", " self.confidence_slider.disabled = False\n", "\n", " def _on_image_upload(self, change):\n", " \"\"\"Handle image upload.\"\"\"\n", " if change[\"new\"]:\n", " uploaded_file = change[\"new\"][0]\n", " image = PIL.Image.open(io.BytesIO(uploaded_file[\"content\"])).convert(\"RGB\")\n", " self._set_image(image)\n", "\n", " def _on_load_url(self, button):\n", " \"\"\"Handle loading image from URL.\"\"\"\n", " url = self.url_input.value.strip()\n", " if not url:\n", " self.status_label.value = \"Please enter a URL\"\n", " return\n", "\n", " self._set_loading(True, \"Downloading image from URL...\")\n", "\n", " try:\n", " response = requests.get(url, timeout=10)\n", " response.raise_for_status()\n", " image = PIL.Image.open(io.BytesIO(response.content)).convert(\"RGB\")\n", " self._set_image(image)\n", " except Exception as e:\n", " self._set_loading(False)\n", " self.status_label.value = f\"Error loading image: {str(e)}\"\n", "\n", " def _set_image(self, image):\n", " \"\"\"Set the current image, adjust figure size, and initialize state.\"\"\"\n", " self._set_loading(True, \"Processing image through model...\")\n", "\n", " try:\n", "\n", " self.current_image = image\n", " self.current_image_array = np.array(image)\n", " self.state = self.processor.set_image(image)\n", " self._set_loading(False)\n", " self.status_label.value = (\n", " f\"Image loaded: {image.size[0]}x{image.size[1]} pixels\"\n", " )\n", " self._resize_figure()\n", " self._update_display()\n", " self._connect_plot_events()\n", " self.accordion.selected_index = 1\n", " except Exception as e:\n", " self._set_loading(False)\n", " self.status_label.value = f\"Error processing image: {str(e)}\"\n", "\n", " def _on_text_submit(self, change):\n", " \"\"\"Handle text prompt submission via Enter key.\"\"\"\n", " # Call the same handler as the button click\n", " self._on_text_prompt(None)\n", "\n", " def _on_text_prompt(self, button):\n", " \"\"\"Handle text prompt submission.\"\"\"\n", " if self.state is None:\n", " self.status_label.value = \"Please load an image first\"\n", " return\n", "\n", " prompt = self.text_input.value.strip()\n", " if not prompt:\n", " self.status_label.value = \"Please enter a prompt\"\n", " return\n", "\n", " self._set_loading(True, f'Segmenting with prompt: \"{prompt}\"...')\n", "\n", " try:\n", " self.state = self.processor.set_text_prompt(prompt, self.state)\n", " self._set_loading(False)\n", " self.status_label.value = f'Segmented with prompt: \"{prompt}\"'\n", " self._update_display()\n", " except Exception as e:\n", " self._set_loading(False)\n", " self.status_label.value = f\"Error: {str(e)}\"\n", "\n", " def _on_box_mode_change(self, change):\n", " \"\"\"Handle box mode toggle.\"\"\"\n", " self.box_mode = \"positive\" if change[\"new\"] == \"Positive Boxes\" else \"negative\"\n", "\n", " def _on_clear_prompts(self, button):\n", " \"\"\"Clear all prompts and reset to image only.\"\"\"\n", " if self.current_image is not None:\n", " try:\n", " self._set_loading(True, \"Clearing prompts and resetting...\")\n", " self.state = self.processor.reset_all_prompts(self.state)\n", " if \"prompted_boxes\" in self.state:\n", " del self.state[\"prompted_boxes\"]\n", " self.text_input.value = \"\"\n", " self._set_loading(False)\n", " self.status_label.value = \"Cleared all prompts\"\n", " self._update_display()\n", " except Exception as e:\n", " self._set_loading(False)\n", " import traceback\n", "\n", " self.status_label.value = f\"Error: {str(e)} {traceback.format_exc()}\"\n", "\n", " def _on_confidence_change(self, change):\n", " \"\"\"Handle confidence threshold change.\"\"\"\n", " if self.state is not None:\n", " self.state = self.processor.set_confidence_threshold(\n", " change[\"new\"], self.state\n", " )\n", " self._update_display()\n", "\n", " def _connect_plot_events(self):\n", " \"\"\"Connect matplotlib event handlers for box drawing.\"\"\"\n", " # Disable matplotlib's toolbar navigation to allow custom box drawing\n", " if hasattr(self.fig.canvas, \"toolbar\") and self.fig.canvas.toolbar is not None:\n", " self.fig.canvas.toolbar.pan()\n", " self.fig.canvas.toolbar.pan()\n", "\n", " self.fig.canvas.mpl_connect(\"button_press_event\", self._on_press)\n", " self.fig.canvas.mpl_connect(\"button_release_event\", self._on_release)\n", " self.fig.canvas.mpl_connect(\"motion_notify_event\", self._on_motion)\n", "\n", " def _on_press(self, event):\n", " \"\"\"Handle mouse press for box drawing.\"\"\"\n", " if event.inaxes != self.ax:\n", " return\n", " self.drawing_box = True\n", " self.box_start = (event.xdata, event.ydata)\n", "\n", " def _on_motion(self, event):\n", " \"\"\"Handle mouse motion for box preview.\"\"\"\n", " if not self.drawing_box or event.inaxes != self.ax or self.box_start is None:\n", " return\n", "\n", " if self.current_rect is not None:\n", " self.current_rect.remove()\n", "\n", " x0, y0 = self.box_start\n", " x1, y1 = event.xdata, event.ydata\n", " width = x1 - x0\n", " height = y1 - y0\n", "\n", " color = \"green\" if self.box_mode == \"positive\" else \"red\"\n", " self.current_rect = Rectangle(\n", " (x0, y0),\n", " width,\n", " height,\n", " fill=False,\n", " edgecolor=color,\n", " linewidth=2,\n", " linestyle=\"--\",\n", " )\n", " self.ax.add_patch(self.current_rect)\n", " self.fig.canvas.draw_idle()\n", "\n", " def _on_release(self, event):\n", " \"\"\"Handle mouse release to finalize box.\"\"\"\n", " if not self.drawing_box or event.inaxes != self.ax or self.box_start is None:\n", " self.drawing_box = False\n", " return\n", "\n", " self.drawing_box = False\n", "\n", " if self.current_rect is not None:\n", " self.current_rect.remove()\n", " self.current_rect = None\n", "\n", " if self.state is None:\n", " return\n", "\n", " x0, y0 = self.box_start\n", " x1, y1 = event.xdata, event.ydata\n", "\n", " x_min = min(x0, x1)\n", " x_max = max(x0, x1)\n", " y_min = min(y0, y1)\n", " y_max = max(y0, y1)\n", "\n", " if abs(x_max - x_min) < 5 or abs(y_max - y_min) < 5:\n", " return\n", "\n", " # Get image dimensions\n", " img_h = self.state[\"original_height\"]\n", " img_w = self.state[\"original_width\"]\n", "\n", " # Convert from xyxy pixel coordinates to cxcywh normalized format\n", " center_x = (x_min + x_max) / 2.0 / img_w\n", " center_y = (y_min + y_max) / 2.0 / img_h\n", " width = (x_max - x_min) / img_w\n", " height = (y_max - y_min) / img_h\n", "\n", " box = [center_x, center_y, width, height]\n", " label = self.box_mode == \"positive\"\n", " mode_str = \"positive\" if label else \"negative\"\n", "\n", " # Store the prompted box in pixel coordinates for display\n", " if \"prompted_boxes\" not in self.state:\n", " self.state[\"prompted_boxes\"] = []\n", " self.state[\"prompted_boxes\"].append(\n", " {\"box\": [x_min, y_min, x_max, y_max], \"label\": label}\n", " )\n", "\n", " self._set_loading(True, f\"Adding {mode_str} box and re-segmenting...\")\n", "\n", " try:\n", " self.state = self.processor.add_geometric_prompt(box, label, self.state)\n", " self._set_loading(False)\n", " self.status_label.value = f\"Added {mode_str} box\"\n", " self._update_display()\n", " except Exception as e:\n", " self._set_loading(False)\n", " self.status_label.value = f\"Error adding box: {str(e)}\"\n", "\n", " def _resize_figure(self):\n", " \"\"\"Calculate and apply new figure size based on image and slider value.\"\"\"\n", " if self.current_image is None:\n", " return\n", "\n", " # 1. Get original image dimensions\n", " img_w, img_h = self.current_image.size\n", "\n", " # 2. The slider's value is now the direct target width for the display\n", " display_w = float(self.size_slider.value)\n", "\n", " # 3. Calculate the corresponding height to maintain the original aspect ratio\n", " aspect_ratio = img_h / img_w\n", " display_h = int(display_w * aspect_ratio)\n", "\n", " # 4. Convert pixel dimensions to inches for Matplotlib and apply\n", " dpi = self.fig.dpi\n", " new_figsize = (display_w / dpi, display_h / dpi)\n", " self.fig.set_size_inches(new_figsize, forward=True)\n", "\n", " def _on_size_change(self, change):\n", " \"\"\"Handle a change from the image size slider.\"\"\"\n", " if self.current_image is not None:\n", " self._resize_figure()\n", " # After resizing the canvas, we must redraw the content\n", " self._update_display()\n", "\n", " def _update_display(self):\n", " \"\"\"Update the display with current results.\"\"\"\n", " if self.current_image_array is None:\n", " return\n", "\n", " with self.output:\n", " clear_output(wait=True)\n", "\n", " self.ax.clear()\n", " self.ax.axis(\"off\")\n", " self.ax.imshow(self.current_image_array)\n", "\n", " if self.state is not None and \"masks\" in self.state:\n", " masks = self.state.get(\"masks\", [])\n", " boxes = self.state.get(\"boxes\", [])\n", " scores = self.state.get(\"scores\", [])\n", "\n", " if len(masks) > 0:\n", " mask_overlay = np.zeros((*self.current_image_array.shape[:2], 4))\n", "\n", " for i, (mask, box, score) in enumerate(zip(masks, boxes, scores)):\n", " mask_np = mask[0].cpu().numpy()\n", "\n", " color = plt.cm.tab10(i % 10)[:3]\n", " mask_overlay[mask_np > 0.5] = (*color, 0.5)\n", "\n", " x0, y0, x1, y1 = box.cpu().numpy()\n", " rect = Rectangle(\n", " (x0, y0),\n", " x1 - x0,\n", " y1 - y0,\n", " fill=False,\n", " edgecolor=color,\n", " linewidth=2,\n", " )\n", " self.ax.add_patch(rect)\n", "\n", " self.ax.text(\n", " x0,\n", " y0 - 5,\n", " f\"{score:.2f}\",\n", " color=\"white\",\n", " fontsize=10,\n", " bbox=dict(\n", " facecolor=color, alpha=0.7, edgecolor=\"none\", pad=2\n", " ),\n", " )\n", "\n", " self.ax.imshow(mask_overlay)\n", " self.status_label.value = f\"Found {len(masks)} object(s)\"\n", " else:\n", " self.status_label.value = (\n", " \"No objects found above confidence threshold\"\n", " )\n", "\n", " # Display prompted boxes with dashed lines\n", " if self.state is not None and \"prompted_boxes\" in self.state:\n", " for prompted_box in self.state[\"prompted_boxes\"]:\n", " box_coords = prompted_box[\"box\"]\n", " is_positive = prompted_box[\"label\"]\n", "\n", " x0, y0, x1, y1 = box_coords\n", " color = \"green\" if is_positive else \"red\"\n", "\n", " rect = Rectangle(\n", " (x0, y0),\n", " x1 - x0,\n", " y1 - y0,\n", " fill=False,\n", " edgecolor=color,\n", " linewidth=2,\n", " linestyle=\"--\",\n", " )\n", " self.ax.add_patch(rect)\n", "\n", " # display(self.fig.canvas)\n", "\n", " def display(self):\n", " display(self.container)\n", "\n", " # Add this for more convenient display in notebooks\n", " def _ipython_display_(self):\n", " self.display()\n" ] }, { "cell_type": "markdown", "id": "1b9bda74-b455-4957-9767-2a46a041b50f", "metadata": {}, "source": [ "# Run!" ] }, { "cell_type": "code", "execution_count": 10, "id": "ebfb9b85-2318-4328-bb0e-e93e4a57fefe", "metadata": {}, "outputs": [ { "data": { "application/vnd.jupyter.widget-view+json": { "model_id": "ea0e04a1bfd7486b93baae650d87e0b2", "version_major": 2, "version_minor": 0 }, "text/plain": [ "VBox(children=(HTML(value='\\n <style>\\n .jupyter-matplotlib-canvas, canvas {\\n …" ] }, "metadata": {}, "output_type": "display_data" }, { "data": { "application/vnd.jupyter.widget-view+json": { "model_id": "bbdcb3374c29461bb379d4bf9c319a49", "version_major": 2, "version_minor": 0 }, "image/png": "iVBORw0KGgoAAAANSUhEUgAABLAAAAMgCAYAAAAz4JsCAAAAOnRFWHRTb2Z0d2FyZQBNYXRwbG90bGliIHZlcnNpb24zLjEwLjYsIGh0dHBzOi8vbWF0cGxvdGxpYi5vcmcvq6yFwwAAAAlwSFlzAAAPYQAAD2EBqD+naQAAFf1JREFUeJzt2DEBACAMwDDAv+fhgJceiYLe3TMzCwAAAACizu8AAAAAAHgxsAAAAABIM7AAAAAASDOwAAAAAEgzsAAAAABIM7AAAAAASDOwAAAAAEgzsAAAAABIM7AAAAAASDOwAAAAAEgzsAAAAABIM7AAAAAASDOwAAAAAEgzsAAAAABIM7AAAAAASDOwAAAAAEgzsAAAAABIM7AAAAAASDOwAAAAAEgzsAAAAABIM7AAAAAASDOwAAAAAEgzsAAAAABIM7AAAAAASDOwAAAAAEgzsAAAAABIM7AAAAAASDOwAAAAAEgzsAAAAABIM7AAAAAASDOwAAAAAEgzsAAAAABIM7AAAAAASDOwAAAAAEgzsAAAAABIM7AAAAAASDOwAAAAAEgzsAAAAABIM7AAAAAASDOwAAAAAEgzsAAAAABIM7AAAAAASDOwAAAAAEgzsAAAAABIM7AAAAAASDOwAAAAAEgzsAAAAABIM7AAAAAASDOwAAAAAEgzsAAAAABIM7AAAAAASDOwAAAAAEgzsAAAAABIM7AAAAAASDOwAAAAAEgzsAAAAABIM7AAAAAASDOwAAAAAEgzsAAAAABIM7AAAAAASDOwAAAAAEgzsAAAAABIM7AAAAAASDOwAAAAAEgzsAAAAABIM7AAAAAASDOwAAAAAEgzsAAAAABIM7AAAAAASDOwAAAAAEgzsAAAAABIM7AAAAAASDOwAAAAAEgzsAAAAABIM7AAAAAASDOwAAAAAEgzsAAAAABIM7AAAAAASDOwAAAAAEgzsAAAAABIM7AAAAAASDOwAAAAAEgzsAAAAABIM7AAAAAASDOwAAAAAEgzsAAAAABIM7AAAAAASDOwAAAAAEgzsAAAAABIM7AAAAAASDOwAAAAAEgzsAAAAABIM7AAAAAASDOwAAAAAEgzsAAAAABIM7AAAAAASDOwAAAAAEgzsAAAAABIM7AAAAAASDOwAAAAAEgzsAAAAABIM7AAAAAASDOwAAAAAEgzsAAAAABIM7AAAAAASDOwAAAAAEgzsAAAAABIM7AAAAAASDOwAAAAAEgzsAAAAABIM7AAAAAASDOwAAAAAEgzsAAAAABIM7AAAAAASDOwAAAAAEgzsAAAAABIM7AAAAAASDOwAAAAAEgzsAAAAABIM7AAAAAASDOwAAAAAEgzsAAAAABIM7AAAAAASDOwAAAAAEgzsAAAAABIM7AAAAAASDOwAAAAAEgzsAAAAABIM7AAAAAASDOwAAAAAEgzsAAAAABIM7AAAAAASDOwAAAAAEgzsAAAAABIM7AAAAAASDOwAAAAAEgzsAAAAABIM7AAAAAASDOwAAAAAEgzsAAAAABIM7AAAAAASDOwAAAAAEgzsAAAAABIM7AAAAAASDOwAAAAAEgzsAAAAABIM7AAAAAASDOwAAAAAEgzsAAAAABIM7AAAAAASDOwAAAAAEgzsAAAAABIM7AAAAAASDOwAAAAAEgzsAAAAABIM7AAAAAASDOwAAAAAEgzsAAAAABIM7AAAAAASDOwAAAAAEgzsAAAAABIM7AAAAAASDOwAAAAAEgzsAAAAABIM7AAAAAASDOwAAAAAEgzsAAAAABIM7AAAAAASDOwAAAAAEgzsAAAAABIM7AAAAAASDOwAAAAAEgzsAAAAABIM7AAAAAASDOwAAAAAEgzsAAAAABIM7AAAAAASDOwAAAAAEgzsAAAAABIM7AAAAAASDOwAAAAAEgzsAAAAABIM7AAAAAASDOwAAAAAEgzsAAAAABIM7AAAAAASDOwAAAAAEgzsAAAAABIM7AAAAAASDOwAAAAAEgzsAAAAABIM7AAAAAASDOwAAAAAEgzsAAAAABIM7AAAAAASDOwAAAAAEgzsAAAAABIM7AAAAAASDOwAAAAAEgzsAAAAABIM7AAAAAASDOwAAAAAEgzsAAAAABIM7AAAAAASDOwAAAAAEgzsAAAAABIM7AAAAAASDOwAAAAAEgzsAAAAABIM7AAAAAASDOwAAAAAEgzsAAAAABIM7AAAAAASDOwAAAAAEgzsAAAAABIM7AAAAAASDOwAAAAAEgzsAAAAABIM7AAAAAASDOwAAAAAEgzsAAAAABIM7AAAAAASDOwAAAAAEgzsAAAAABIM7AAAAAASDOwAAAAAEgzsAAAAABIM7AAAAAASDOwAAAAAEgzsAAAAABIM7AAAAAASDOwAAAAAEgzsAAAAABIM7AAAAAASDOwAAAAAEgzsAAAAABIM7AAAAAASDOwAAAAAEgzsAAAAABIM7AAAAAASDOwAAAAAEgzsAAAAABIM7AAAAAASDOwAAAAAEgzsAAAAABIM7AAAAAASDOwAAAAAEgzsAAAAABIM7AAAAAASDOwAAAAAEgzsAAAAABIM7AAAAAASDOwAAAAAEgzsAAAAABIM7AAAAAASDOwAAAAAEgzsAAAAABIM7AAAAAASDOwAAAAAEgzsAAAAABIM7AAAAAASDOwAAAAAEgzsAAAAABIM7AAAAAASDOwAAAAAEgzsAAAAABIM7AAAAAASDOwAAAAAEgzsAAAAABIM7AAAAAASDOwAAAAAEgzsAAAAABIM7AAAAAASDOwAAAAAEgzsAAAAABIM7AAAAAASDOwAAAAAEgzsAAAAABIM7AAAAAASDOwAAAAAEgzsAAAAABIM7AAAAAASDOwAAAAAEgzsAAAAABIM7AAAAAASDOwAAAAAEgzsAAAAABIM7AAAAAASDOwAAAAAEgzsAAAAABIM7AAAAAASDOwAAAAAEgzsAAAAABIM7AAAAAASDOwAAAAAEgzsAAAAABIM7AAAAAASDOwAAAAAEgzsAAAAABIM7AAAAAASDOwAAAAAEgzsAAAAABIM7AAAAAASDOwAAAAAEgzsAAAAABIM7AAAAAASDOwAAAAAEgzsAAAAABIM7AAAAAASDOwAAAAAEgzsAAAAABIM7AAAAAASDOwAAAAAEgzsAAAAABIM7AAAAAASDOwAAAAAEgzsAAAAABIM7AAAAAASDOwAAAAAEgzsAAAAABIM7AAAAAASDOwAAAAAEgzsAAAAABIM7AAAAAASDOwAAAAAEgzsAAAAABIM7AAAAAASDOwAAAAAEgzsAAAAABIM7AAAAAASDOwAAAAAEgzsAAAAABIM7AAAAAASDOwAAAAAEgzsAAAAABIM7AAAAAASDOwAAAAAEgzsAAAAABIM7AAAAAASDOwAAAAAEgzsAAAAABIM7AAAAAASDOwAAAAAEgzsAAAAABIM7AAAAAASDOwAAAAAEgzsAAAAABIM7AAAAAASDOwAAAAAEgzsAAAAABIM7AAAAAASDOwAAAAAEgzsAAAAABIM7AAAAAASDOwAAAAAEgzsAAAAABIM7AAAAAASDOwAAAAAEgzsAAAAABIM7AAAAAASDOwAAAAAEgzsAAAAABIM7AAAAAASDOwAAAAAEgzsAAAAABIM7AAAAAASDOwAAAAAEgzsAAAAABIM7AAAAAASDOwAAAAAEgzsAAAAABIM7AAAAAASDOwAAAAAEgzsAAAAABIM7AAAAAASDOwAAAAAEgzsAAAAABIM7AAAAAASDOwAAAAAEgzsAAAAABIM7AAAAAASDOwAAAAAEgzsAAAAABIM7AAAAAASDOwAAAAAEgzsAAAAABIM7AAAAAASDOwAAAAAEgzsAAAAABIM7AAAAAASDOwAAAAAEgzsAAAAABIM7AAAAAASDOwAAAAAEgzsAAAAABIM7AAAAAASDOwAAAAAEgzsAAAAABIM7AAAAAASDOwAAAAAEgzsAAAAABIM7AAAAAASDOwAAAAAEgzsAAAAABIM7AAAAAASDOwAAAAAEgzsAAAAABIM7AAAAAASDOwAAAAAEgzsAAAAABIM7AAAAAASDOwAAAAAEgzsAAAAABIM7AAAAAASDOwAAAAAEgzsAAAAABIM7AAAAAASDOwAAAAAEgzsAAAAABIM7AAAAAASDOwAAAAAEgzsAAAAABIM7AAAAAASDOwAAAAAEgzsAAAAABIM7AAAAAASDOwAAAAAEgzsAAAAABIM7AAAAAASDOwAAAAAEgzsAAAAABIM7AAAAAASDOwAAAAAEgzsAAAAABIM7AAAAAASDOwAAAAAEgzsAAAAABIM7AAAAAASDOwAAAAAEgzsAAAAABIM7AAAAAASDOwAAAAAEgzsAAAAABIM7AAAAAASDOwAAAAAEgzsAAAAABIM7AAAAAASDOwAAAAAEgzsAAAAABIM7AAAAAASDOwAAAAAEgzsAAAAABIM7AAAAAASDOwAAAAAEgzsAAAAABIM7AAAAAASDOwAAAAAEgzsAAAAABIM7AAAAAASDOwAAAAAEgzsAAAAABIM7AAAAAASDOwAAAAAEgzsAAAAABIM7AAAAAASDOwAAAAAEgzsAAAAABIM7AAAAAASDOwAAAAAEgzsAAAAABIM7AAAAAASDOwAAAAAEgzsAAAAABIM7AAAAAASDOwAAAAAEgzsAAAAABIM7AAAAAASDOwAAAAAEgzsAAAAABIM7AAAAAASDOwAAAAAEgzsAAAAABIM7AAAAAASDOwAAAAAEgzsAAAAABIM7AAAAAASDOwAAAAAEgzsAAAAABIM7AAAAAASDOwAAAAAEgzsAAAAABIM7AAAAAASDOwAAAAAEgzsAAAAABIM7AAAAAASDOwAAAAAEgzsAAAAABIM7AAAAAASDOwAAAAAEgzsAAAAABIM7AAAAAASDOwAAAAAEgzsAAAAABIM7AAAAAASDOwAAAAAEgzsAAAAABIM7AAAAAASDOwAAAAAEgzsAAAAABIM7AAAAAASDOwAAAAAEgzsAAAAABIM7AAAAAASDOwAAAAAEgzsAAAAABIM7AAAAAASDOwAAAAAEgzsAAAAABIM7AAAAAASDOwAAAAAEgzsAAAAABIM7AAAAAASDOwAAAAAEgzsAAAAABIM7AAAAAASDOwAAAAAEgzsAAAAABIM7AAAAAASDOwAAAAAEgzsAAAAABIM7AAAAAASDOwAAAAAEgzsAAAAABIM7AAAAAASDOwAAAAAEgzsAAAAABIM7AAAAAASDOwAAAAAEgzsAAAAABIM7AAAAAASDOwAAAAAEgzsAAAAABIM7AAAAAASDOwAAAAAEgzsAAAAABIM7AAAAAASDOwAAAAAEgzsAAAAABIM7AAAAAASDOwAAAAAEgzsAAAAABIM7AAAAAASDOwAAAAAEgzsAAAAABIM7AAAAAASDOwAAAAAEgzsAAAAABIM7AAAAAASDOwAAAAAEgzsAAAAABIM7AAAAAASDOwAAAAAEgzsAAAAABIM7AAAAAASDOwAAAAAEgzsAAAAABIM7AAAAAASDOwAAAAAEgzsAAAAABIM7AAAAAASDOwAAAAAEgzsAAAAABIM7AAAAAASDOwAAAAAEgzsAAAAABIM7AAAAAASDOwAAAAAEgzsAAAAABIM7AAAAAASDOwAAAAAEgzsAAAAABIM7AAAAAASDOwAAAAAEgzsAAAAABIM7AAAAAASDOwAAAAAEgzsAAAAABIM7AAAAAASDOwAAAAAEgzsAAAAABIM7AAAAAASDOwAAAAAEgzsAAAAABIM7AAAAAASDOwAAAAAEgzsAAAAABIM7AAAAAASDOwAAAAAEgzsAAAAABIM7AAAAAASDOwAAAAAEgzsAAAAABIM7AAAAAASDOwAAAAAEgzsAAAAABIM7AAAAAASDOwAAAAAEgzsAAAAABIM7AAAAAASDOwAAAAAEgzsAAAAABIM7AAAAAASDOwAAAAAEgzsAAAAABIM7AAAAAASDOwAAAAAEgzsAAAAABIM7AAAAAASDOwAAAAAEgzsAAAAABIM7AAAAAASDOwAAAAAEgzsAAAAABIM7AAAAAASDOwAAAAAEgzsAAAAABIM7AAAAAASDOwAAAAAEgzsAAAAABIM7AAAAAASDOwAAAAAEgzsAAAAABIM7AAAAAASDOwAAAAAEgzsAAAAABIM7AAAAAASDOwAAAAAEgzsAAAAABIM7AAAAAASDOwAAAAAEgzsAAAAABIM7AAAAAASDOwAAAAAEgzsAAAAABIM7AAAAAASDOwAAAAAEgzsAAAAABIM7AAAAAASDOwAAAAAEgzsAAAAABIM7AAAAAASDOwAAAAAEgzsAAAAABIM7AAAAAASDOwAAAAAEgzsAAAAABIM7AAAAAASDOwAAAAAEgzsAAAAABIM7AAAAAASDOwAAAAAEgzsAAAAABIM7AAAAAASDOwAAAAAEgzsAAAAABIM7AAAAAASDOwAAAAAEgzsAAAAABIM7AAAAAASDOwAAAAAEgzsAAAAABIM7AAAAAASDOwAAAAAEgzsAAAAABIM7AAAAAASDOwAAAAAEgzsAAAAABIM7AAAAAASDOwAAAAAEgzsAAAAABIM7AAAAAASDOwAAAAAEgzsAAAAABIM7AAAAAASDOwAAAAAEgzsAAAAABIM7AAAAAASDOwAAAAAEgzsAAAAABIM7AAAAAASDOwAAAAAEgzsAAAAABIM7AAAAAASDOwAAAAAEgzsAAAAABIM7AAAAAASDOwAAAAAEgzsAAAAABIM7AAAAAASDOwAAAAAEgzsAAAAABIM7AAAAAASDOwAAAAAEgzsAAAAABIM7AAAAAASDOwAAAAAEgzsAAAAABIM7AAAAAASDOwAAAAAEgzsAAAAABIM7AAAAAASDOwAAAAAEgzsAAAAABIM7AAAAAASDOwAAAAAEgzsAAAAABIM7AAAAAASDOwAAAAAEgzsAAAAABIM7AAAAAASDOwAAAAAEgzsAAAAABIM7AAAAAASDOwAAAAAEgzsAAAAABIM7AAAAAASDOwAAAAAEgzsAAAAABIM7AAAAAASDOwAAAAAEgzsAAAAABIM7AAAAAASDOwAAAAAEgzsAAAAABIM7AAAAAASDOwAAAAAEgzsAAAAABIM7AAAAAASDOwAAAAAEgzsAAAAABIM7AAAAAASDOwAAAAAEgzsAAAAABIM7AAAAAASDOwAAAAAEgzsAAAAABIM7AAAAAASDOwAAAAAEgzsAAAAABIM7AAAAAASDOwAAAAAEgzsAAAAABIM7AAAAAASDOwAAAAAEgzsAAAAABIM7AAAAAASDOwAAAAAEgzsAAAAABIM7AAAAAASDOwAAAAAEgzsAAAAABIM7AAAAAASDOwAAAAAEgzsAAAAABIM7AAAAAASDOwAAAAAEgzsAAAAABIM7AAAAAASDOwAAAAAEgzsAAAAABIM7AAAAAASDOwAAAAAEgzsAAAAABIM7AAAAAASDOwAAAAAEgzsAAAAABIM7AAAAAASDOwAAAAAEgzsAAAAABIM7AAAAAASDOwAAAAAEgzsAAAAABIM7AAAAAASDOwAAAAAEgzsAAAAABIM7AAAAAASDOwAAAAAEgzsAAAAABIM7AAAAAASDOwAAAAAEgzsAAAAABIM7AAAAAASDOwAAAAAEgzsAAAAABIM7AAAAAASDOwAAAAAEgzsAAAAABIM7AAAAAASDOwAAAAAEi710EKPFzQ9BwAAAAASUVORK5CYII=", "text/html": [ "\n", " <div style=\"display: inline-block;\">\n", " <div class=\"jupyter-widgets widget-label\" style=\"text-align: center;\">\n", " Figure\n", " </div>\n", " <img src='data:image/png;base64,iVBORw0KGgoAAAANSUhEUgAABLAAAAMgCAYAAAAz4JsCAAAAOnRFWHRTb2Z0d2FyZQBNYXRwbG90bGliIHZlcnNpb24zLjEwLjYsIGh0dHBzOi8vbWF0cGxvdGxpYi5vcmcvq6yFwwAAAAlwSFlzAAAPYQAAD2EBqD+naQAAFf1JREFUeJzt2DEBACAMwDDAv+fhgJceiYLe3TMzCwAAAACizu8AAAAAAHgxsAAAAABIM7AAAAAASDOwAAAAAEgzsAAAAABIM7AAAAAASDOwAAAAAEgzsAAAAABIM7AAAAAASDOwAAAAAEgzsAAAAABIM7AAAAAASDOwAAAAAEgzsAAAAABIM7AAAAAASDOwAAAAAEgzsAAAAABIM7AAAAAASDOwAAAAAEgzsAAAAABIM7AAAAAASDOwAAAAAEgzsAAAAABIM7AAAAAASDOwAAAAAEgzsAAAAABIM7AAAAAASDOwAAAAAEgzsAAAAABIM7AAAAAASDOwAAAAAEgzsAAAAABIM7AAAAAASDOwAAAAAEgzsAAAAABIM7AAAAAASDOwAAAAAEgzsAAAAABIM7AAAAAASDOwAAAAAEgzsAAAAABIM7AAAAAASDOwAAAAAEgzsAAAAABIM7AAAAAASDOwAAAAAEgzsAAAAABIM7AAAAAASDOwAAAAAEgzsAAAAABIM7AAAAAASDOwAAAAAEgzsAAAAABIM7AAAAAASDOwAAAAAEgzsAAAAABIM7AAAAAASDOwAAAAAEgzsAAAAABIM7AAAAAASDOwAAAAAEgzsAAAAABIM7AAAAAASDOwAAAAAEgzsAAAAABIM7AAAAAASDOwAAAAAEgzsAAAAABIM7AAAAAASDOwAAAAAEgzsAAAAABIM7AAAAAASDOwAAAAAEgzsAAAAABIM7AAAAAASDOwAAAAAEgzsAAAAABIM7AAAAAASDOwAAAAAEgzsAAAAABIM7AAAAAASDOwAAAAAEgzsAAAAABIM7AAAAAASDOwAAAAAEgzsAAAAABIM7AAAAAASDOwAAAAAEgzsAAAAABIM7AAAAAASDOwAAAAAEgzsAAAAABIM7AAAAAASDOwAAAAAEgzsAAAAABIM7AAAAAASDOwAAAAAEgzsAAAAABIM7AAAAAASDOwAAAAAEgzsAAAAABIM7AAAAAASDOwAAAAAEgzsAAAAABIM7AAAAAASDOwAAAAAEgzsAAAAABIM7AAAAAASDOwAAAAAEgzsAAAAABIM7AAAAAASDOwAAAAAEgzsAAAAABIM7AAAAAASDOwAAAAAEgzsAAAAABIM7AAAAAASDOwAAAAAEgzsAAAAABIM7AAAAAASDOwAAAAAEgzsAAAAABIM7AAAAAASDOwAAAAAEgzsAAAAABIM7AAAAAASDOwAAAAAEgzsAAAAABIM7AAAAAASDOwAAAAAEgzsAAAAABIM7AAAAAASDOwAAAAAEgzsAAAAABIM7AAAAAASDOwAAAAAEgzsAAAAABIM7AAAAAASDOwAAAAAEgzsAAAAABIM7AAAAAASDOwAAAAAEgzsAAAAABIM7AAAAAASDOwAAAAAEgzsAAAAABIM7AAAAAASDOwAAAAAEgzsAAAAABIM7AAAAAASDOwAAAAAEgzsAAAAABIM7AAAAAASDOwAAAAAEgzsAAAAABIM7AAAAAASDOwAAAAAEgzsAAAAABIM7AAAAAASDOwAAAAAEgzsAAAAABIM7AAAAAASDOwAAAAAEgzsAAAAABIM7AAAAAASDOwAAAAAEgzsAAAAABIM7AAAAAASDOwAAAAAEgzsAAAAABIM7AAAAAASDOwAAAAAEgzsAAAAABIM7AAAAAASDOwAAAAAEgzsAAAAABIM7AAAAAASDOwAAAAAEgzsAAAAABIM7AAAAAASDOwAAAAAEgzsAAAAABIM7AAAAAASDOwAAAAAEgzsAAAAABIM7AAAAAASDOwAAAAAEgzsAAAAABIM7AAAAAASDOwAAAAAEgzsAAAAABIM7AAAAAASDOwAAAAAEgzsAAAAABIM7AAAAAASDOwAAAAAEgzsAAAAABIM7AAAAAASDOwAAAAAEgzsAAAAABIM7AAAAAASDOwAAAAAEgzsAAAAABIM7AAAAAASDOwAAAAAEgzsAAAAABIM7AAAAAASDOwAAAAAEgzsAAAAABIM7AAAAAASDOwAAAAAEgzsAAAAABIM7AAAAAASDOwAAAAAEgzsAAAAABIM7AAAAAASDOwAAAAAEgzsAAAAABIM7AAAAAASDOwAAAAAEgzsAAAAABIM7AAAAAASDOwAAAAAEgzsAAAAABIM7AAAAAASDOwAAAAAEgzsAAAAABIM7AAAAAASDOwAAAAAEgzsAAAAABIM7AAAAAASDOwAAAAAEgzsAAAAABIM7AAAAAASDOwAAAAAEgzsAAAAABIM7AAAAAASDOwAAAAAEgzsAAAAABIM7AAAAAASDOwAAAAAEgzsAAAAABIM7AAAAAASDOwAAAAAEgzsAAAAABIM7AAAAAASDOwAAAAAEgzsAAAAABIM7AAAAAASDOwAAAAAEgzsAAAAABIM7AAAAAASDOwAAAAAEgzsAAAAABIM7AAAAAASDOwAAAAAEgzsAAAAABIM7AAAAAASDOwAAAAAEgzsAAAAABIM7AAAAAASDOwAAAAAEgzsAAAAABIM7AAAAAASDOwAAAAAEgzsAAAAABIM7AAAAAASDOwAAAAAEgzsAAAAABIM7AAAAAASDOwAAAAAEgzsAAAAABIM7AAAAAASDOwAAAAAEgzsAAAAABIM7AAAAAASDOwAAAAAEgzsAAAAABIM7AAAAAASDOwAAAAAEgzsAAAAABIM7AAAAAASDOwAAAAAEgzsAAAAABIM7AAAAAASDOwAAAAAEgzsAAAAABIM7AAAAAASDOwAAAAAEgzsAAAAABIM7AAAAAASDOwAAAAAEgzsAAAAABIM7AAAAAASDOwAAAAAEgzsAAAAABIM7AAAAAASDOwAAAAAEgzsAAAAABIM7AAAAAASDOwAAAAAEgzsAAAAABIM7AAAAAASDOwAAAAAEgzsAAAAABIM7AAAAAASDOwAAAAAEgzsAAAAABIM7AAAAAASDOwAAAAAEgzsAAAAABIM7AAAAAASDOwAAAAAEgzsAAAAABIM7AAAAAASDOwAAAAAEgzsAAAAABIM7AAAAAASDOwAAAAAEgzsAAAAABIM7AAAAAASDOwAAAAAEgzsAAAAABIM7AAAAAASDOwAAAAAEgzsAAAAABIM7AAAAAASDOwAAAAAEgzsAAAAABIM7AAAAAASDOwAAAAAEgzsAAAAABIM7AAAAAASDOwAAAAAEgzsAAAAABIM7AAAAAASDOwAAAAAEgzsAAAAABIM7AAAAAASDOwAAAAAEgzsAAAAABIM7AAAAAASDOwAAAAAEgzsAAAAABIM7AAAAAASDOwAAAAAEgzsAAAAABIM7AAAAAASDOwAAAAAEgzsAAAAABIM7AAAAAASDOwAAAAAEgzsAAAAABIM7AAAAAASDOwAAAAAEgzsAAAAABIM7AAAAAASDOwAAAAAEgzsAAAAABIM7AAAAAASDOwAAAAAEgzsAAAAABIM7AAAAAASDOwAAAAAEgzsAAAAABIM7AAAAAASDOwAAAAAEgzsAAAAABIM7AAAAAASDOwAAAAAEgzsAAAAABIM7AAAAAASDOwAAAAAEgzsAAAAABIM7AAAAAASDOwAAAAAEgzsAAAAABIM7AAAAAASDOwAAAAAEgzsAAAAABIM7AAAAAASDOwAAAAAEgzsAAAAABIM7AAAAAASDOwAAAAAEgzsAAAAABIM7AAAAAASDOwAAAAAEgzsAAAAABIM7AAAAAASDOwAAAAAEgzsAAAAABIM7AAAAAASDOwAAAAAEgzsAAAAABIM7AAAAAASDOwAAAAAEgzsAAAAABIM7AAAAAASDOwAAAAAEgzsAAAAABIM7AAAAAASDOwAAAAAEgzsAAAAABIM7AAAAAASDOwAAAAAEgzsAAAAABIM7AAAAAASDOwAAAAAEgzsAAAAABIM7AAAAAASDOwAAAAAEgzsAAAAABIM7AAAAAASDOwAAAAAEgzsAAAAABIM7AAAAAASDOwAAAAAEgzsAAAAABIM7AAAAAASDOwAAAAAEgzsAAAAABIM7AAAAAASDOwAAAAAEgzsAAAAABIM7AAAAAASDOwAAAAAEgzsAAAAABIM7AAAAAASDOwAAAAAEgzsAAAAABIM7AAAAAASDOwAAAAAEgzsAAAAABIM7AAAAAASDOwAAAAAEgzsAAAAABIM7AAAAAASDOwAAAAAEgzsAAAAABIM7AAAAAASDOwAAAAAEgzsAAAAABIM7AAAAAASDOwAAAAAEgzsAAAAABIM7AAAAAASDOwAAAAAEgzsAAAAABIM7AAAAAASDOwAAAAAEgzsAAAAABIM7AAAAAASDOwAAAAAEgzsAAAAABIM7AAAAAASDOwAAAAAEgzsAAAAABIM7AAAAAASDOwAAAAAEgzsAAAAABIM7AAAAAASDOwAAAAAEgzsAAAAABIM7AAAAAASDOwAAAAAEgzsAAAAABIM7AAAAAASDOwAAAAAEgzsAAAAABIM7AAAAAASDOwAAAAAEgzsAAAAABIM7AAAAAASDOwAAAAAEgzsAAAAABIM7AAAAAASDOwAAAAAEgzsAAAAABIM7AAAAAASDOwAAAAAEgzsAAAAABIM7AAAAAASDOwAAAAAEgzsAAAAABIM7AAAAAASDOwAAAAAEgzsAAAAABIM7AAAAAASDOwAAAAAEgzsAAAAABIM7AAAAAASDOwAAAAAEgzsAAAAABIM7AAAAAASDOwAAAAAEgzsAAAAABIM7AAAAAASDOwAAAAAEgzsAAAAABIM7AAAAAASDOwAAAAAEgzsAAAAABIM7AAAAAASDOwAAAAAEgzsAAAAABIM7AAAAAASDOwAAAAAEgzsAAAAABIM7AAAAAASDOwAAAAAEgzsAAAAABIM7AAAAAASDOwAAAAAEgzsAAAAABIM7AAAAAASDOwAAAAAEgzsAAAAABIM7AAAAAASDOwAAAAAEgzsAAAAABIM7AAAAAASDOwAAAAAEgzsAAAAABIM7AAAAAASDOwAAAAAEgzsAAAAABIM7AAAAAASDOwAAAAAEgzsAAAAABIM7AAAAAASDOwAAAAAEgzsAAAAABIM7AAAAAASDOwAAAAAEgzsAAAAABIM7AAAAAASDOwAAAAAEgzsAAAAABIM7AAAAAASDOwAAAAAEgzsAAAAABIM7AAAAAASDOwAAAAAEgzsAAAAABIM7AAAAAASDOwAAAAAEgzsAAAAABIM7AAAAAASDOwAAAAAEgzsAAAAABIM7AAAAAASDOwAAAAAEgzsAAAAABIM7AAAAAASDOwAAAAAEgzsAAAAABIM7AAAAAASDOwAAAAAEgzsAAAAABIM7AAAAAASDOwAAAAAEgzsAAAAABIM7AAAAAASDOwAAAAAEgzsAAAAABIM7AAAAAASDOwAAAAAEgzsAAAAABIM7AAAAAASDOwAAAAAEgzsAAAAABIM7AAAAAASDOwAAAAAEgzsAAAAABIM7AAAAAASDOwAAAAAEgzsAAAAABIM7AAAAAASDOwAAAAAEgzsAAAAABIM7AAAAAASDOwAAAAAEgzsAAAAABIM7AAAAAASDOwAAAAAEgzsAAAAABIM7AAAAAASDOwAAAAAEgzsAAAAABIM7AAAAAASDOwAAAAAEgzsAAAAABIM7AAAAAASDOwAAAAAEgzsAAAAABIM7AAAAAASDOwAAAAAEgzsAAAAABIM7AAAAAASDOwAAAAAEgzsAAAAABIM7AAAAAASDOwAAAAAEgzsAAAAABIM7AAAAAASDOwAAAAAEgzsAAAAABIM7AAAAAASDOwAAAAAEgzsAAAAABIM7AAAAAASDOwAAAAAEgzsAAAAABIM7AAAAAASDOwAAAAAEgzsAAAAABIM7AAAAAASDOwAAAAAEgzsAAAAABIM7AAAAAASDOwAAAAAEgzsAAAAABIM7AAAAAASDOwAAAAAEgzsAAAAABIM7AAAAAASDOwAAAAAEgzsAAAAABIM7AAAAAASDOwAAAAAEgzsAAAAABIM7AAAAAASDOwAAAAAEgzsAAAAABIM7AAAAAASDOwAAAAAEgzsAAAAABIM7AAAAAASDOwAAAAAEgzsAAAAABIM7AAAAAASDOwAAAAAEgzsAAAAABIM7AAAAAASDOwAAAAAEgzsAAAAABIM7AAAAAASDOwAAAAAEgzsAAAAABIM7AAAAAASDOwAAAAAEgzsAAAAABIM7AAAAAASDOwAAAAAEgzsAAAAABIM7AAAAAASDOwAAAAAEgzsAAAAABIM7AAAAAASDOwAAAAAEgzsAAAAABIM7AAAAAASDOwAAAAAEgzsAAAAABIM7AAAAAASDOwAAAAAEgzsAAAAABIM7AAAAAASDOwAAAAAEgzsAAAAABIM7AAAAAASDOwAAAAAEgzsAAAAABIM7AAAAAASDOwAAAAAEgzsAAAAABIM7AAAAAASDOwAAAAAEgzsAAAAABIM7AAAAAASDOwAAAAAEgzsAAAAABIM7AAAAAASDOwAAAAAEgzsAAAAABIM7AAAAAASDOwAAAAAEgzsAAAAABIM7AAAAAASDOwAAAAAEgzsAAAAABIM7AAAAAASDOwAAAAAEgzsAAAAABIM7AAAAAASDOwAAAAAEgzsAAAAABIM7AAAAAASDOwAAAAAEgzsAAAAABIM7AAAAAASDOwAAAAAEgzsAAAAABIM7AAAAAASDOwAAAAAEgzsAAAAABIM7AAAAAASDOwAAAAAEgzsAAAAABIM7AAAAAASDOwAAAAAEgzsAAAAABIM7AAAAAASDOwAAAAAEgzsAAAAABIM7AAAAAASDOwAAAAAEgzsAAAAABIM7AAAAAASDOwAAAAAEgzsAAAAABIM7AAAAAASDOwAAAAAEgzsAAAAABIM7AAAAAASDOwAAAAAEgzsAAAAABIM7AAAAAASDOwAAAAAEgzsAAAAABIM7AAAAAASDOwAAAAAEgzsAAAAABIM7AAAAAASDOwAAAAAEgzsAAAAABIM7AAAAAASDOwAAAAAEgzsAAAAABIM7AAAAAASDOwAAAAAEgzsAAAAABIM7AAAAAASDOwAAAAAEgzsAAAAABIM7AAAAAASDOwAAAAAEgzsAAAAABIM7AAAAAASDOwAAAAAEgzsAAAAABIM7AAAAAASDOwAAAAAEgzsAAAAABIM7AAAAAASDOwAAAAAEgzsAAAAABIM7AAAAAASDOwAAAAAEgzsAAAAABIM7AAAAAASDOwAAAAAEgzsAAAAABIM7AAAAAASDOwAAAAAEgzsAAAAABIM7AAAAAASDOwAAAAAEgzsAAAAABIM7AAAAAASDOwAAAAAEgzsAAAAABIM7AAAAAASDOwAAAAAEgzsAAAAABIM7AAAAAASDOwAAAAAEgzsAAAAABIM7AAAAAASDOwAAAAAEgzsAAAAABIM7AAAAAASDOwAAAAAEgzsAAAAABIM7AAAAAASDOwAAAAAEgzsAAAAABIM7AAAAAASDOwAAAAAEgzsAAAAABIM7AAAAAASDOwAAAAAEgzsAAAAABIM7AAAAAASDOwAAAAAEgzsAAAAABIM7AAAAAASDOwAAAAAEi710EKPFzQ9BwAAAAASUVORK5CYII=' width=1200.0/>\n", " </div>\n", " " ], "text/plain": [ "Canvas(footer_visible=False, header_visible=False, resizable=False, toolbar=Toolbar(toolitems=[('Home', 'Reset…" ] }, "metadata": {}, "output_type": "display_data" } ], "source": [ "widget = Sam3SegmentationWidget(processor)\n", "widget.display()" ] }, { "cell_type": "code", "execution_count": null, "id": "50a14560-573a-4784-9f55-689fda9147be", "metadata": {}, "outputs": [], "source": [] } ], "metadata": { "kernelspec": { "display_name": "Python 3 (ipykernel)", "language": "python", "name": "python3" }, "language_info": { "codemirror_mode": { "name": "ipython", "version": 3 }, "file_extension": ".py", "mimetype": "text/x-python", "name": "python", "nbconvert_exporter": "python", "pygments_lexer": "ipython3", "version": "3.12.11" } }, "nbformat": 4, "nbformat_minor": 5}123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689#!/usr/bin/env python3"""SAM3 (video model detector) + LoRA finetuning for BraTS, with optional torchrun DDP.
This script treats a 3D volume as a short video clip (slice sequence) and trains:- LoRA adapters injected into SAM3 detector (backbone/transformer attention proj layers)- a lightweight decoder head to predict a binary tumor mask per frame
It is designed to be compatible with inference in `infer_brats_sam3.py` by saving LoRAweights **on the SAM3 detector module** (so keys match `sam3_video_model.detector`)."""
import argparseimport jsonimport osimport sysfrom datetime import datetimefrom pathlib import Pathfrom typing import Dict, Optional, Tuple
import numpy as npimport torchimport torch.distributed as distimport torch.nn as nnimport torch.nn.functional as Ffrom torch.amp import autocastfrom torch.nn.parallel import DistributedDataParallel as DDPfrom torch.utils.data import DataLoaderfrom torch.utils.data.distributed import DistributedSamplerfrom torch.utils.tensorboard import SummaryWriterfrom tqdm import tqdm
# Add SAM3 repo to import pathsys.path.insert(0, "/root/githubs/sam3")
from brats_dataset import BraTSImageDataset, BraTSVideoDataset, collate_fn_bratsfrom lora import apply_lora_to_model, count_parameters, load_lora_weights, save_lora_weights
def _distributed_info(): if "RANK" in os.environ and "WORLD_SIZE" in os.environ: rank = int(os.environ["RANK"]) world_size = int(os.environ["WORLD_SIZE"]) local_rank = int(os.environ.get("LOCAL_RANK", "0")) return True, rank, world_size, local_rank return False, 0, 1, 0
def setup_distributed() -> Tuple[bool, int, int, int]: distributed, rank, world_size, local_rank = _distributed_info() if not distributed: return False, 0, 1, 0 torch.cuda.set_device(local_rank) # Newer PyTorch versions warn that NCCL may hang if the rank->GPU mapping is unknown. # Pass device_id when supported, and use explicit device_ids in barrier to avoid ambiguity. try: dist.init_process_group( backend="nccl", init_method="env://", device_id=torch.device(f"cuda:{local_rank}"), ) except TypeError: # Older PyTorch doesn't support device_id dist.init_process_group(backend="nccl", init_method="env://")
try: dist.barrier(device_ids=[local_rank]) except TypeError: dist.barrier() return True, rank, world_size, local_rank
def cleanup_distributed(): if dist.is_available() and dist.is_initialized(): # Best-effort sync before destroy; avoid hanging if device mapping is ambiguous. try: local_rank = int(os.environ.get("LOCAL_RANK", "0")) dist.barrier(device_ids=[local_rank]) except Exception: try: dist.barrier() except Exception: pass dist.destroy_process_group()
def is_main_process(rank: int) -> bool: return rank == 0
def setup_device(local_rank: int = 0) -> torch.device: if torch.cuda.is_available(): torch.cuda.set_device(local_rank) device = torch.device(f"cuda:{local_rank}") # TF32 for A100+ torch.backends.cuda.matmul.allow_tf32 = True torch.backends.cudnn.allow_tf32 = True return device return torch.device("cpu")
def multiclass_dice_loss(pred: torch.Tensor, target: torch.Tensor, num_classes: int = 4, smooth: float = 1.0) -> torch.Tensor: """ 多类 Dice Loss pred: (B, num_classes, H, W) logits target: (B, H, W) class indices """ pred_softmax = F.softmax(pred, dim=1) # (B, C, H, W) target_onehot = F.one_hot(target.long(), num_classes).permute(0, 3, 1, 2).float() # (B, C, H, W) # 计算每个类的 dice loss (跳过背景类 0) dice_losses = [] for c in range(1, num_classes): # 只计算肿瘤类 pred_c = pred_softmax[:, c].reshape(-1) target_c = target_onehot[:, c].reshape(-1) intersection = (pred_c * target_c).sum() union = pred_c.sum() + target_c.sum() dice = (2.0 * intersection + smooth) / (union + smooth) dice_losses.append(1.0 - dice) return torch.stack(dice_losses).mean()
def multiclass_ce_loss(pred: torch.Tensor, target: torch.Tensor) -> torch.Tensor: """ 多类交叉熵损失 pred: (B, num_classes, H, W) logits target: (B, H, W) class indices """ return F.cross_entropy(pred, target.long(), reduction="mean")
def combined_loss(pred: torch.Tensor, target: torch.Tensor, num_classes: int = 4) -> torch.Tensor: """组合损失: Dice Loss + CrossEntropy""" return 0.5 * multiclass_dice_loss(pred, target, num_classes) + 0.5 * multiclass_ce_loss(pred, target)
def compute_dice(pred: torch.Tensor, target: torch.Tensor, num_classes: int = 4) -> float: """ 计算多类平均 Dice (只计算肿瘤类, 跳过背景) pred: (B, num_classes, H, W) logits target: (B, H, W) class indices """ pred_class = pred.argmax(dim=1) # (B, H, W) dice_scores = [] for c in range(1, num_classes): # 跳过背景类 0 pred_c = (pred_class == c).float() target_c = (target == c).float() intersection = (pred_c * target_c).sum() union = pred_c.sum() + target_c.sum() if union == 0: # 如果 GT 和预测都没有这个类, dice = 1 dice_scores.append(1.0) else: dice_scores.append((2.0 * intersection / union).item()) return sum(dice_scores) / len(dice_scores)
class MedSAM3DetectorSeg(nn.Module): """ Minimal trainable segmentation model: SAM3 detector backbone -> lightweight decoder -> mask logits (B, num_classes, H, W)
Notes: - Inputs are expected in [0,1] float. We normalize with mean/std (0.5/0.5) like SAM3. - We always run the SAM3 backbone at 1008x1008 (SAM3 native resolution). - num_classes=4 for BraTS: 0=背景, 1=NCR, 2=ED, 3=ET """
def __init__(self, sam3_detector: nn.Module, image_size: int = 1008, num_classes: int = 4): super().__init__() self.detector = sam3_detector self.image_size = int(image_size) self.num_classes = num_classes self.register_buffer("mean", torch.tensor([0.5, 0.5, 0.5]).view(1, 3, 1, 1)) self.register_buffer("std", torch.tensor([0.5, 0.5, 0.5]).view(1, 3, 1, 1))
# lightweight decoder; expects a 256-channel feature map from SAM3 backbone # 输出 num_classes 通道 (4 类分割) self.decoder = nn.Sequential( nn.Conv2d(256, 128, 3, padding=1), nn.BatchNorm2d(128), nn.ReLU(inplace=True), nn.Upsample(scale_factor=2, mode="bilinear", align_corners=False), nn.Conv2d(128, 64, 3, padding=1), nn.BatchNorm2d(64), nn.ReLU(inplace=True), nn.Upsample(scale_factor=2, mode="bilinear", align_corners=False), nn.Conv2d(64, 32, 3, padding=1), nn.BatchNorm2d(32), nn.ReLU(inplace=True), nn.Upsample(scale_factor=2, mode="bilinear", align_corners=False), nn.Conv2d(32, num_classes, 1), # 输出 4 类 )
def _preprocess(self, images: torch.Tensor) -> torch.Tensor: # images: float in [0,1] _, _, h, w = images.shape if h != self.image_size or w != self.image_size: images = F.interpolate( images, size=(self.image_size, self.image_size), mode="bilinear", align_corners=False ) images = (images - self.mean.to(images.device)) / self.std.to(images.device) return images
def _pick_feat(self, backbone_out) -> torch.Tensor: feat = None if isinstance(backbone_out, dict): if "sam3_features" in backbone_out: feat = backbone_out["sam3_features"] elif "features" in backbone_out: feat = backbone_out["features"] else: for _, v in backbone_out.items(): if isinstance(v, torch.Tensor) and v.ndim == 4: feat = v break elif isinstance(backbone_out, torch.Tensor): feat = backbone_out if feat is None or not isinstance(feat, torch.Tensor) or feat.ndim != 4: raise RuntimeError("Could not find a 4D feature map in SAM3 backbone output") return feat
def forward(self, images: torch.Tensor) -> torch.Tensor: orig_h, orig_w = images.shape[-2:] x = self._preprocess(images) backbone_out = self.detector.backbone.forward_image(x) feat = self._pick_feat(backbone_out) logits = self.decoder(feat) # (B, num_classes, ?, ?) if logits.shape[-2:] != (orig_h, orig_w): logits = F.interpolate(logits, size=(orig_h, orig_w), mode="bilinear", align_corners=False) return logits # (B, num_classes, H, W)
class Trainer: def __init__( self, model: nn.Module, train_loader: DataLoader, val_loader: Optional[DataLoader], optimizer: torch.optim.Optimizer, scheduler: Optional[torch.optim.lr_scheduler._LRScheduler], device: torch.device, output_dir: Path, grad_accum: int = 1, use_amp: bool = False, rank: int = 0, world_size: int = 1, train_sampler: Optional[DistributedSampler] = None, ): self.model = model self.train_loader = train_loader self.val_loader = val_loader self.optimizer = optimizer self.scheduler = scheduler self.device = device self.output_dir = output_dir self.grad_accum = max(1, int(grad_accum)) self.use_amp = bool(use_amp) self.rank = rank self.world_size = world_size self.is_main = is_main_process(rank) self.train_sampler = train_sampler
self.global_step = 0 self.epoch = 0 self.best_dice = -1.0
self.writer = SummaryWriter(str(self.output_dir / "tensorboard")) if self.is_main else None
self.scaler = torch.amp.GradScaler("cuda", enabled=self.use_amp) if torch.cuda.is_available() else None
def _unwrap(self) -> nn.Module: return self.model.module if hasattr(self.model, "module") else self.model
def _save_lora(self, path: Path): # Save LoRA weights on detector ONLY so that keys match inference-time `sam3_video_model.detector`. core = self._unwrap() detector = core.detector save_lora_weights(detector, str(path)) # Also save the decoder weights (critical for inference!) decoder_path = path.parent / "best_decoder_weights.pt" torch.save(core.decoder.state_dict(), decoder_path) if self.is_main: print(f"Saved decoder weights to {decoder_path}")
def train_one_epoch(self) -> Dict[str, float]: self.model.train() if self.train_sampler is not None: self.train_sampler.set_epoch(self.epoch)
total_loss = 0.0 total_dice = 0.0 num_steps = 0
# Count total batches to ensure all ranks process the same number total_batches = len(self.train_loader) iterator = self.train_loader if self.is_main: iterator = tqdm(iterator, desc=f"Epoch {self.epoch}", dynamic_ncols=True)
self.optimizer.zero_grad(set_to_none=True)
for step_idx, batch in enumerate(iterator): if "images" in batch: images = batch["images"].to(self.device, non_blocking=True) # (B,3,H,W) in [0,1] masks = batch["masks"].to(self.device, non_blocking=True) # (B,H,W) {0,1} else: frames = batch["frames"].to(self.device, non_blocking=True) # (B,T,3,H,W) masks_bt = batch["masks"].to(self.device, non_blocking=True) # (B,T,H,W) b, t = frames.shape[:2] images = frames.view(b * t, *frames.shape[2:]) masks = masks_bt.view(b * t, *masks_bt.shape[2:])
with autocast("cuda", enabled=self.use_amp): logits = self.model(images) loss = combined_loss(logits, masks) loss = loss / self.grad_accum
if self.use_amp and self.scaler is not None: self.scaler.scale(loss).backward() else: loss.backward()
do_step = ((step_idx + 1) % self.grad_accum) == 0 if do_step: if self.use_amp and self.scaler is not None: self.scaler.step(self.optimizer) self.scaler.update() else: self.optimizer.step() self.optimizer.zero_grad(set_to_none=True) self.global_step += 1
with torch.no_grad(): dice = compute_dice(logits, masks)
total_loss += loss.item() * self.grad_accum total_dice += dice num_steps += 1
if self.is_main and hasattr(iterator, "set_postfix"): iterator.set_postfix({"loss": f"{total_loss/num_steps:.4f}", "dice": f"{total_dice/num_steps:.4f}"}) if self.is_main and self.writer is not None and self.global_step % 10 == 0 and do_step: self.writer.add_scalar("train/loss", total_loss / num_steps, self.global_step) self.writer.add_scalar("train/dice", total_dice / num_steps, self.global_step) self.writer.add_scalar("train/lr", self.optimizer.param_groups[0]["lr"], self.global_step)
# Synchronize all ranks at the end of each epoch to prevent drift if self.world_size > 1: dist.barrier() return {"loss": total_loss / max(1, num_steps), "dice": total_dice / max(1, num_steps)}
@torch.no_grad() def validate(self) -> Dict[str, float]: """Validate using the underlying model (not DDP wrapper) to avoid NCCL sync issues.""" if self.val_loader is None: return {"loss": float("nan"), "dice": float("nan")} # Use the underlying model to avoid DDP NCCL sync during validation raw_model = self.model.module if hasattr(self.model, "module") else self.model raw_model.eval()
total_loss = 0.0 total_dice = 0.0 num_steps = 0
iterator = self.val_loader if self.is_main: iterator = tqdm(iterator, desc="Validating", dynamic_ncols=True)
for batch in iterator: if "images" in batch: images = batch["images"].to(self.device, non_blocking=True) masks = batch["masks"].to(self.device, non_blocking=True) else: frames = batch["frames"].to(self.device, non_blocking=True) masks_bt = batch["masks"].to(self.device, non_blocking=True) b, t = frames.shape[:2] images = frames.view(b * t, *frames.shape[2:]) masks = masks_bt.view(b * t, *masks_bt.shape[2:])
logits = raw_model(images) loss = combined_loss(logits, masks) dice = compute_dice(logits, masks) total_loss += loss.item() total_dice += dice num_steps += 1
avg_loss = total_loss / max(1, num_steps) avg_dice = total_dice / max(1, num_steps) if self.is_main and self.writer is not None: self.writer.add_scalar("val/loss", avg_loss, self.global_step) self.writer.add_scalar("val/dice", avg_dice, self.global_step) return {"loss": avg_loss, "dice": avg_dice}
def train(self, epochs: int, val_freq: int): ckpt_dir = self.output_dir / "checkpoints" ckpt_dir.mkdir(parents=True, exist_ok=True)
if self.is_main: print(f"Output dir: {self.output_dir}") print(f"World size: {self.world_size}")
for ep in range(int(epochs)): self.epoch = ep train_m = self.train_one_epoch() if self.is_main: print(f"Epoch {ep}: train_loss={train_m['loss']:.4f}, train_dice={train_m['dice']:.4f}") if self.scheduler is not None: self.scheduler.step()
is_best = False # Only rank0 does validation (using raw model, no DDP sync needed). if (ep + 1) % int(val_freq) == 0 and self.is_main: val_m = self.validate() print(f"Epoch {ep}: val_loss={val_m['loss']:.4f}, val_dice={val_m['dice']:.4f}") if val_m["dice"] > self.best_dice: self.best_dice = val_m["dice"] is_best = True print(f" New best val dice: {self.best_dice:.4f}")
# Save ONLY best checkpoint (rank0 only) to avoid writing many epoch checkpoints. if self.is_main and is_best: self._save_lora(ckpt_dir / "best_lora_weights.pt") torch.save( { "epoch": ep, "global_step": self.global_step, "best_dice": self.best_dice, "optimizer": self.optimizer.state_dict(), "scheduler": self.scheduler.state_dict() if self.scheduler is not None else None, }, ckpt_dir / "best_trainer_state.pt", ) # Synchronize all ranks after validation/save to prevent drift between ranks # This barrier ensures rank 0 (which may do validation/save) catches up with others if self.world_size > 1: dist.barrier()
if self.is_main and self.writer is not None: self.writer.close()
def main(): parser = argparse.ArgumentParser(description="SAM3 video(detector)+LoRA finetuning for BraTS (DDP-ready)")
# data parser.add_argument( "--data_root", type=str, default="/data/yty/brats2023/ASNR-MICCAI-BraTS2023-GLI-Challenge-TrainingData", ) parser.add_argument("--dataset_type", type=str, default="video", choices=["image", "video"]) parser.add_argument("--modality", type=int, default=0, help="0=t1c, 1=t1n, 2=t2f, 3=t2w") parser.add_argument("--target_size", type=int, nargs=2, default=[512, 512]) parser.add_argument("--num_frames", type=int, default=8) parser.add_argument("--frame_stride", type=int, default=1) parser.add_argument("--split_json", type=str, default="", help="Optional splits.json (case-level). If set, ratios are ignored.") parser.add_argument("--train_ratio", type=float, default=0.7) parser.add_argument("--val_ratio", type=float, default=0.1) parser.add_argument("--test_ratio", type=float, default=0.2)
# model / lora parser.add_argument("--checkpoint", type=str, default="/data/yty/sam3/sam3.pt") parser.add_argument("--lora_rank", type=int, default=8) parser.add_argument("--lora_alpha", type=float, default=16.0) parser.add_argument("--lora_dropout", type=float, default=0.1) parser.add_argument( "--lora_target_modules", type=str, default="q_proj,k_proj,v_proj,out_proj,qkv,proj", help="Comma-separated module name substrings to inject LoRA into.", )
# train parser.add_argument("--epochs", type=int, default=50) parser.add_argument("--batch_size", type=int, default=1, help="Per-GPU batch size") parser.add_argument("--lr", type=float, default=1e-4) parser.add_argument("--weight_decay", type=float, default=0.01) parser.add_argument("--grad_accum", type=int, default=1) parser.add_argument("--num_workers", type=int, default=4) parser.add_argument("--val_freq", type=int, default=5) parser.add_argument("--seed", type=int, default=42) parser.add_argument("--use_amp", action="store_true", help="Enable AMP (saves VRAM, may change numerics).")
# io parser.add_argument("--output_dir", type=str, default="/data/yty/brats23_sam3_video_lora_output") parser.add_argument("--resume_lora", type=str, default="", help="Path to lora_weights.pt to resume adapters.")
args = parser.parse_args()
torch.manual_seed(args.seed) np.random.seed(args.seed)
distributed, rank, world_size, local_rank = setup_distributed() device = setup_device(local_rank=local_rank)
if is_main_process(rank): Path(args.output_dir).mkdir(parents=True, exist_ok=True) with open(Path(args.output_dir) / "config.json", "w") as f: json.dump({**vars(args), "timestamp": datetime.now().isoformat()}, f, indent=2)
# datasets (we output images in [0,1] and let the model normalize) target_size = tuple(args.target_size) split_json = args.split_json.strip() or None if args.dataset_type == "video": train_ds = BraTSVideoDataset( data_root=args.data_root, split="train", modality=args.modality, target_size=target_size, num_frames=args.num_frames, frame_stride=args.frame_stride, augment=True, train_ratio=args.train_ratio, val_ratio=args.val_ratio, test_ratio=args.test_ratio, seed=args.seed, split_json=split_json, normalize_mean=(0.0, 0.0, 0.0), normalize_std=(1.0, 1.0, 1.0), ) val_ds = BraTSVideoDataset( data_root=args.data_root, split="val", modality=args.modality, target_size=target_size, num_frames=args.num_frames, frame_stride=args.frame_stride, augment=False, train_ratio=args.train_ratio, val_ratio=args.val_ratio, test_ratio=args.test_ratio, seed=args.seed, split_json=split_json, normalize_mean=(0.0, 0.0, 0.0), normalize_std=(1.0, 1.0, 1.0), ) else: train_ds = BraTSImageDataset( data_root=args.data_root, split="train", modality=args.modality, target_size=target_size, augment=True, train_ratio=args.train_ratio, val_ratio=args.val_ratio, test_ratio=args.test_ratio, seed=args.seed, split_json=split_json, normalize_mean=(0.0, 0.0, 0.0), normalize_std=(1.0, 1.0, 1.0), ) val_ds = BraTSImageDataset( data_root=args.data_root, split="val", modality=args.modality, target_size=target_size, augment=False, train_ratio=args.train_ratio, val_ratio=args.val_ratio, test_ratio=args.test_ratio, seed=args.seed, split_json=split_json, normalize_mean=(0.0, 0.0, 0.0), normalize_std=(1.0, 1.0, 1.0), )
train_sampler = DistributedSampler(train_ds, shuffle=True, seed=args.seed, drop_last=True) if distributed else None train_loader = DataLoader( train_ds, batch_size=args.batch_size, shuffle=(train_sampler is None), sampler=train_sampler, num_workers=args.num_workers, pin_memory=True, collate_fn=collate_fn_brats, drop_last=True, )
# validation only on rank0 (simple & stable) val_loader = None if is_main_process(rank): val_loader = DataLoader( val_ds, batch_size=args.batch_size, shuffle=False, num_workers=args.num_workers, pin_memory=True, collate_fn=collate_fn_brats, drop_last=False, )
# build SAM3 video model, then take its detector from sam3.model_builder import build_sam3_video_model
if is_main_process(rank): print("Loading SAM3 video model...") sam3_video = build_sam3_video_model( checkpoint_path=args.checkpoint, load_from_HF=False, device=str(device), apply_temporal_disambiguation=True, ) detector = sam3_video.detector
# create trainable wrapper (detector is part of it) # num_classes=4 for BraTS: 背景(0) + NCR(1) + ED(2) + ET(3) model = MedSAM3DetectorSeg(detector, image_size=1008, num_classes=4).to(device)
# inject LoRA into detector only (avoid unused params from tracker) target_modules = [s.strip() for s in args.lora_target_modules.split(",") if s.strip()] if is_main_process(rank): print(f"Applying LoRA to detector: rank={args.lora_rank}, alpha={args.lora_alpha}, targets={target_modules}") apply_lora_to_model( model.detector, rank=args.lora_rank, alpha=args.lora_alpha, dropout=args.lora_dropout, target_modules=target_modules, exclude_modules=[], )
if args.resume_lora: if is_main_process(rank): print(f"Loading LoRA weights from: {args.resume_lora}") load_lora_weights(model.detector, args.resume_lora)
# IMPORTANT: LoRA modules are created on CPU by default; move them to the target device # before wrapping with DDP (DDP requires all params on the same device type). model = model.to(device)
# freeze everything except LoRA + decoder for name, p in model.named_parameters(): if "lora_" in name or name.startswith("decoder."): p.requires_grad = True else: p.requires_grad = False
if is_main_process(rank): stats = count_parameters(model) print( f"Params total={stats['total']:,} trainable={stats['trainable']:,} " f"ratio={stats['trainable_ratio']:.4%}" )
trainable_params = [p for p in model.parameters() if p.requires_grad] optimizer = torch.optim.AdamW(trainable_params, lr=args.lr, weight_decay=args.weight_decay) scheduler = torch.optim.lr_scheduler.CosineAnnealingLR(optimizer, T_max=args.epochs, eta_min=args.lr * 0.01)
if distributed: # We inject LoRA into the detector broadly; some injected layers may not be exercised by # our simplified forward (we only use `detector.backbone.forward_image`), so we must # enable unused-parameter detection to avoid DDP reduction errors. model = DDP(model, device_ids=[local_rank], output_device=local_rank, find_unused_parameters=True)
trainer = Trainer( model=model, train_loader=train_loader, val_loader=val_loader, optimizer=optimizer, scheduler=scheduler, device=device, output_dir=Path(args.output_dir), grad_accum=args.grad_accum, use_amp=args.use_amp, rank=rank, world_size=world_size, train_sampler=train_sampler, )
trainer.train(epochs=args.epochs, val_freq=args.val_freq)
cleanup_distributed()
if __name__ == "__main__": main()
123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051LICENSEMANIFEST.inREADME.mdpyproject.tomlexamples/saco_gold_silver_eval_example.ipynbexamples/saco_gold_silver_vis_example.ipynbexamples/saco_veval_eval_example.ipynbexamples/saco_veval_vis_example.ipynbexamples/sam3_agent.ipynbexamples/sam3_for_sam1_task_example.ipynbexamples/sam3_for_sam2_video_task_example.ipynbexamples/sam3_image_batched_inference.ipynbexamples/sam3_image_interactive.ipynbexamples/sam3_image_predictor_example.ipynbexamples/sam3_video_predictor_example.ipynbsam3/__init__.pysam3/logger.pysam3/model_builder.pysam3/visualization_utils.pysam3.egg-info/PKG-INFOsam3.egg-info/SOURCES.txtsam3.egg-info/dependency_links.txtsam3.egg-info/requires.txtsam3.egg-info/top_level.txtsam3/model/__init__.pysam3/model/act_ckpt_utils.pysam3/model/box_ops.pysam3/model/data_misc.pysam3/model/decoder.pysam3/model/edt.pysam3/model/encoder.pysam3/model/geometry_encoders.pysam3/model/io_utils.pysam3/model/maskformer_segmentation.pysam3/model/memory.pysam3/model/model_misc.pysam3/model/necks.pysam3/model/position_encoding.pysam3/model/sam1_task_predictor.pysam3/model/sam3_image.pysam3/model/sam3_image_processor.pysam3/model/sam3_tracker_base.pysam3/model/sam3_tracker_utils.pysam3/model/sam3_tracking_predictor.pysam3/model/sam3_video_base.pysam3/model/sam3_video_inference.pysam3/model/sam3_video_predictor.pysam3/model/text_encoder_ve.pysam3/model/tokenizer_ve.pysam3/model/vitdet.pysam3/model/vl_combiner.py1# Copyright (c) Meta Platforms, Inc. and affiliates. All Rights Reserved123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205# Copyright (c) Meta Platforms, Inc. and affiliates. All Rights Reserved
import base64import osfrom typing import Any, Optional
from openai import OpenAI
def get_image_base64_and_mime(image_path): """Convert image file to base64 string and get MIME type""" try: # Get MIME type based on file extension ext = os.path.splitext(image_path)[1].lower() mime_types = { ".jpg": "image/jpeg", ".jpeg": "image/jpeg", ".png": "image/png", ".gif": "image/gif", ".webp": "image/webp", ".bmp": "image/bmp", } mime_type = mime_types.get(ext, "image/jpeg") # Default to JPEG
# Convert image to base64 with open(image_path, "rb") as image_file: base64_data = base64.b64encode(image_file.read()).decode("utf-8") return base64_data, mime_type except Exception as e: print(f"Error converting image to base64: {e}") return None, None
def send_generate_request( messages, server_url=None, model="meta-llama/Llama-4-Maverick-17B-128E-Instruct-FP8", api_key=None, max_tokens=4096,): """ Sends a request to the OpenAI-compatible API endpoint using the OpenAI client library.
Args: server_url (str): The base URL of the server, e.g. "http://127.0.0.1:8000" messages (list): A list of message dicts, each containing role and content. model (str): The model to use for generation (default: "llama-4") max_tokens (int): Maximum number of tokens to generate (default: 4096)
Returns: str: The generated response text from the server. """ # Process messages to convert image paths to base64 processed_messages = [] for message in messages: processed_message = message.copy() if message["role"] == "user" and "content" in message: processed_content = [] for c in message["content"]: if isinstance(c, dict) and c.get("type") == "image": # Convert image path to base64 format image_path = c["image"]
print("image_path", image_path) new_image_path = image_path.replace( "?", "%3F" ) # Escape ? in the path
# Read the image file and convert to base64 try: base64_image, mime_type = get_image_base64_and_mime( new_image_path ) if base64_image is None: print( f"Warning: Could not convert image to base64: {new_image_path}" ) continue
# Create the proper image_url structure with base64 data processed_content.append( { "type": "image_url", "image_url": { "url": f"data:{mime_type};base64,{base64_image}", "detail": "high", }, } )
except FileNotFoundError: print(f"Warning: Image file not found: {new_image_path}") continue except Exception as e: print(f"Warning: Error processing image {new_image_path}: {e}") continue else: processed_content.append(c)
processed_message["content"] = processed_content processed_messages.append(processed_message)
# Create OpenAI client with custom base URL client = OpenAI(api_key=api_key, base_url=server_url)
try: print(f"🔍 Calling model {model}...") response = client.chat.completions.create( model=model, messages=processed_messages, max_completion_tokens=max_tokens, n=1, ) # print(f"Received response: {response.choices[0].message}")
# Extract the response content if response.choices and len(response.choices) > 0: return response.choices[0].message.content else: print(f"Unexpected response format: {response}") return None
except Exception as e: print(f"Request failed: {e}") return None
def send_direct_request( llm: Any, messages: list[dict[str, Any]], sampling_params: Any,) -> Optional[str]: """ Run inference on a vLLM model instance directly without using a server.
Args: llm: Initialized vLLM LLM instance (passed from external initialization) messages: List of message dicts with role and content (OpenAI format) sampling_params: vLLM SamplingParams instance (initialized externally)
Returns: str: Generated response text, or None if inference fails """ try: # Process messages to handle images (convert to base64 if needed) processed_messages = [] for message in messages: processed_message = message.copy() if message["role"] == "user" and "content" in message: processed_content = [] for c in message["content"]: if isinstance(c, dict) and c.get("type") == "image": # Convert image path to base64 format image_path = c["image"] new_image_path = image_path.replace("?", "%3F")
try: base64_image, mime_type = get_image_base64_and_mime( new_image_path ) if base64_image is None: print( f"Warning: Could not convert image: {new_image_path}" ) continue
# vLLM expects image_url format processed_content.append( { "type": "image_url", "image_url": { "url": f"data:{mime_type};base64,{base64_image}" }, } ) except Exception as e: print( f"Warning: Error processing image {new_image_path}: {e}" ) continue else: processed_content.append(c)
processed_message["content"] = processed_content processed_messages.append(processed_message)
print("🔍 Running direct inference with vLLM...")
# Run inference using vLLM's chat interface outputs = llm.chat( messages=processed_messages, sampling_params=sampling_params, )
# Extract the generated text from the first output if outputs and len(outputs) > 0: generated_text = outputs[0].outputs[0].text return generated_text else: print(f"Unexpected output format: {outputs}") return None
except Exception as e: print(f"Direct inference failed: {e}") return None123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138# Copyright (c) Meta Platforms, Inc. and affiliates. All Rights Reserved
import jsonimport os
import torchfrom PIL import Image
from sam3.model.box_ops import box_xyxy_to_xywhfrom sam3.train.masks_ops import rle_encode
from .helpers.mask_overlap_removal import remove_overlapping_masksfrom .viz import visualize
def sam3_inference(processor, image_path, text_prompt): """Run SAM 3 image inference with text prompts and format the outputs""" image = Image.open(image_path) orig_img_w, orig_img_h = image.size
# model inference inference_state = processor.set_image(image) inference_state = processor.set_text_prompt( state=inference_state, prompt=text_prompt )
# format and assemble outputs pred_boxes_xyxy = torch.stack( [ inference_state["boxes"][:, 0] / orig_img_w, inference_state["boxes"][:, 1] / orig_img_h, inference_state["boxes"][:, 2] / orig_img_w, inference_state["boxes"][:, 3] / orig_img_h, ], dim=-1, ) # normalized in range [0, 1] pred_boxes_xywh = box_xyxy_to_xywh(pred_boxes_xyxy).tolist() pred_masks = rle_encode(inference_state["masks"].squeeze(1)) pred_masks = [m["counts"] for m in pred_masks] outputs = { "orig_img_h": orig_img_h, "orig_img_w": orig_img_w, "pred_boxes": pred_boxes_xywh, "pred_masks": pred_masks, "pred_scores": inference_state["scores"].tolist(), } return outputs
def call_sam_service( sam3_processor, image_path: str, text_prompt: str, output_folder_path: str = "sam3_output",): """ Loads an image, sends it with a text prompt to the service, saves the results, and renders the visualization. """ print(f"📞 Loading image '{image_path}' and sending with prompt '{text_prompt}'...")
text_prompt_for_save_path = ( text_prompt.replace("/", "_") if "/" in text_prompt else text_prompt )
os.makedirs( os.path.join(output_folder_path, image_path.replace("/", "-")), exist_ok=True ) output_json_path = os.path.join( output_folder_path, image_path.replace("/", "-"), rf"{text_prompt_for_save_path}.json", ) output_image_path = os.path.join( output_folder_path, image_path.replace("/", "-"), rf"{text_prompt_for_save_path}.png", )
try: # Send the image and text prompt as a multipart/form-data request serialized_response = sam3_inference(sam3_processor, image_path, text_prompt)
# 1. Prepare the response dictionary serialized_response = remove_overlapping_masks(serialized_response) serialized_response = { "original_image_path": image_path, "output_image_path": output_image_path, **serialized_response, }
# 2. Reorder predictions by scores (highest to lowest) if scores are available if "pred_scores" in serialized_response and serialized_response["pred_scores"]: # Create indices sorted by scores in descending order score_indices = sorted( range(len(serialized_response["pred_scores"])), key=lambda i: serialized_response["pred_scores"][i], reverse=True, )
# Reorder all three lists based on the sorted indices serialized_response["pred_scores"] = [ serialized_response["pred_scores"][i] for i in score_indices ] serialized_response["pred_boxes"] = [ serialized_response["pred_boxes"][i] for i in score_indices ] serialized_response["pred_masks"] = [ serialized_response["pred_masks"][i] for i in score_indices ]
# 3. Remove any invalid RLE masks that is too short (shorter than 5 characters) valid_masks = [] valid_boxes = [] valid_scores = [] for i, rle in enumerate(serialized_response["pred_masks"]): if len(rle) > 4: valid_masks.append(rle) valid_boxes.append(serialized_response["pred_boxes"][i]) valid_scores.append(serialized_response["pred_scores"][i]) serialized_response["pred_masks"] = valid_masks serialized_response["pred_boxes"] = valid_boxes serialized_response["pred_scores"] = valid_scores
with open(output_json_path, "w") as f: json.dump(serialized_response, f, indent=4) print(f"✅ Raw JSON response saved to '{output_json_path}'")
# 4. Render and save visualizations on the image and save it in the SAM3 output folder print("🔍 Rendering visualizations on the image ...") viz_image = visualize(serialized_response) os.makedirs(os.path.dirname(output_image_path), exist_ok=True) viz_image.save(output_image_path) print("✅ Saved visualization at:", output_image_path) except Exception as e: print(f"❌ Error calling service: {e}")
return output_json_path1# Copyright (c) Meta Platforms, Inc. and affiliates. All Rights Reserved123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687# Copyright (c) Meta Platforms, Inc. and affiliates. All Rights Reserved
import loggingfrom contextlib import contextmanagerfrom functools import wraps
import torch
__all__ = ["retry_if_cuda_oom"]
@contextmanagerdef _ignore_torch_cuda_oom(): """ A context which ignores CUDA OOM exception from pytorch. """ try: yield except RuntimeError as e: # NOTE: the string may change? if "CUDA out of memory. " in str(e): pass else: raise
def retry_if_cuda_oom(func): """ Makes a function retry itself after encountering pytorch's CUDA OOM error. It will first retry after calling `torch.cuda.empty_cache()`.
If that still fails, it will then retry by trying to convert inputs to CPUs. In this case, it expects the function to dispatch to CPU implementation. The return values may become CPU tensors as well and it's user's responsibility to convert it back to CUDA tensor if needed.
Args: func: a stateless callable that takes tensor-like objects as arguments
Returns: a callable which retries `func` if OOM is encountered.
Examples: :: output = retry_if_cuda_oom(some_torch_function)(input1, input2) # output may be on CPU even if inputs are on GPU
Note: 1. When converting inputs to CPU, it will only look at each argument and check if it has `.device` and `.to` for conversion. Nested structures of tensors are not supported.
2. Since the function might be called more than once, it has to be stateless. """
def maybe_to_cpu(x): try: like_gpu_tensor = x.device.type == "cuda" and hasattr(x, "to") except AttributeError: like_gpu_tensor = False if like_gpu_tensor: return x.to(device="cpu") else: return x
@wraps(func) def wrapped(*args, **kwargs): with _ignore_torch_cuda_oom(): return func(*args, **kwargs)
# Clear cache and retry torch.cuda.empty_cache() with _ignore_torch_cuda_oom(): return func(*args, **kwargs)
# Try on CPU. This slows down the code significantly, therefore print a notice. logger = logging.getLogger(__name__) logger.info( "Attempting to copy inputs of {} to CPU due to CUDA OOM".format(str(func)) ) new_args = (maybe_to_cpu(x) for x in args) new_kwargs = {k: maybe_to_cpu(v) for k, v in kwargs.items()} return func(*new_args, **new_kwargs)
return wrapped123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242You are a helpful visual-concept grounding assistant capable of leveraging tool calls to ground concepts the user refers to, and providing structured JSON outputs and tool calls.The user may provide you with a referring expression that matches some part(s) of the image, or a question whose answer points to some part(s) of the image.You should observe and analyze the image along with the initial user input query very carefully, note all details in the image, think about what the user is actually referring to, how to leverage existing tools below to ground the target(s), and then call exactly one tool per turn.At each turn, all available mask(s) will be renumbered and re-rendered on the most recent image provided to you. The numbering and coloring can be different from previous turns. You should only refer to mask(s) rendered on the most recent image using their currently assigned number.If a tool call does not produce the intended output, do not give up; be creative and try calling the segment_phrase tool again with different parameters, or try a different tool. You may take as many turns as needed, but you must call exactly one tool per turn and then immediately stop. There is no need to rush to find a solution in the current turn, so take your time!
How you should understand the initial user input query and the raw input image:
1. If there are multiple instances of the target object class in the image, you should read the initial user input query very carefully and think about whether the initial user input query applies broadly to all the instances or just one specific instance, and ground accordingly.2. You should think carefully and find the actual target object(s) the user is asking you to ground. Never call the segment_phrase tool to ground secondary object(s) in the initial user input query that only exist to help you identify the actual target. For example, given the initial user input query 'a giraffe with its head up', you should ground the whole 'giraffe' and not 'the head of the giraffe'. Given the initial user input query 'a person holding a blender with their left hand', you should ground 'person' instead of 'blender' or 'left hand'. Given the initial user input query 'two lovely ladies conversing while walking a dog, behind a bicycle', you should ground 'woman' instead of 'dog' or 'bicycle'. Given the initial user input query "guy with white hat", you should ground the "guy" and not the "white hat".3. Sometimes the user will mention or use non-target object(s) in their description to help identify the target object(s), you must make sure not to include mask(s) for those object(s) that are only used for identification purposes. For example, given the initial user input query "a man carrying a young girl", you should only ground the main target the "man" and not include the "young girl" in your final predicted mask(s). Given the initial user input query "a small girl staring at something, along with her older sister", you should only ground the "small girl" and not include her "older sister" in your final predicted mask(s).4. Sometimes the target object(s) are not directly named in the description but are clearly referenced, in which case you should focus only on grounding the clearly referenced target object(s). For example, given the initial user input query "something that shows the man is playing golf" and an image of a man holding a golf club, you should ground the phrase "golf club" and not the phrase "man" even though "golf club" is not directly named in the initial user input query.5. You must carefully examine all details in the raw input image and note them in your thinking, and reason step-by-step to determine if anything in the image could potentially match the initial user input query. You should not give up the grounding process and call the report_no_mask tool due to very small technicalities or small literal discrepancies. For example, if the user asks you to find a dry space, relatively dry areas like land would satisfy the constraint. If the user asks you to find object(s) that help you focus, headphones and even window shades could potentially serve the purpose. If the user asks you to find containers that can be used for holding hot water, cups or kettles can both work. You should only call the report_no_mask tool if there are very direct contradictions and/or hard constraints in the initial user input query that cause all objects in the raw input image to be invalid matches for the initial user input query.6. Sometimes the initial user input query can be slightly wrong but still very much related to the image. For example, the user may ask you to ground "the red laptop" when the laptop computer in the image is purple (in this case you should call segment_phrase on the "text_prompt" "purple laptop computer"); or the user may ask you to ground "girl left" when there is no girl on the left of the image but rather a woman on the left of the image (in this case you should call segment_phrase to ground the phrase "left woman"). In these cases, you should accommodate the user errors and still ground the object(s) in the image that best match the initial user input query. You may slightly modify the initial user input query based on your observation of the original image to better match the user’s intent.7. Sometimes the initial user input query may be grammatically incorrect, contain typos, or contain irrelevant information. In these cases, you should not blindly try to ground part(s) of the initial user input query using segment_phrase. Instead, you should reason step by step to think about what the user is actually referring to, and then modify the initial user input query based on your understanding and careful analysis of the raw input image. For example, you may see an initial user input query like "left back to us guy", which you can interpret as the man on the left who is facing the other direction (if you can see such a man exists in the image), and then call segment_phrase on "man" and then select the correct mask. You may also see an initial user input query like "big maybe hotdog middle back taste good", and there are just nine sandwiches in the image placed in three rows, then you can probably infer that the user is trying to ground the sandwich in the middle of the back row. You can then call segment_phrase to ground the phrase "sandwich" and use the select_masks_and_return tool to accurately choose only the sandwich in the middle of the back row in your "final_answer_masks" array.8. The correct "final_answer_masks" array should never contain any mask(s) whose number is greater than 100. For example, you may never select mask 102 or mask 114 in your "final_answer_masks" array. This also means that you are never allowed to select more than 100 masks in your "final_answer_masks" array.9. Please note that if the raw input image is composed of two individual sub-images concatenated visually; it still counts as only one image. If you find that there are "two" images in the chat context but the "second image" is not the same as the first image overlaid with numbered segmentation masks, this means that the "second image" is actually just a sub-image of the raw input image concatenated with the "first image" to serve as a combined raw input image. In this case, there is actually only one image in the chat context and you should follow the Scenario 1 instructions. This is very important!
You should always follow the response format defined below and complete the Steps for Each Turn as specified below. Never break the specified format for any reason.
Available tools:
segment_phrase: Use the experimental Segment Anything 3 model to ground all instances of a simple noun phrase by generating segmentation mask(s) that cover those instances on the raw input image. At the same time, all previously generated mask(s) will be deleted and cannot be referred to in future messages.Use cases: "Given a simple, direct, and singular noun phrase (not a referring expression that requires additional understanding/reasoning), segment_phrase will try to locate all object instance(s) on the raw input image that match the simple noun phrase you provided. The tool will also render all of the generated segmentation mask(s) onto the image for you to examine and decide the next step."Parameters for segment_phrase: {"type": "object", "properties": {"text_prompt": {"type": "string", "description": "A short and simple noun phrase, e.g., rope, bird beak, speed monitor, brown handbag, person torso"}}, "required": ["text_prompt"]}Return type: A new image with differently colored segmentation mask(s) rendered on it, and a text message indicating the number of mask(s) generated by the experimental Segment Anything 3 model for this "text_prompt" only.Important rules for using the segment_phrase tool:1. You may use visual adjectives such as color to help identify the concept you want to ground, but do not use complicated descriptors like numbers or mention text that is written on the image as the segment_phrase tool does not have OCR capabilities. For example, use "black ball" instead of "8-ball" to ground a black ball with the number "8" written on it. If the user asks you to ground an object that can only be identified by the text or number written on it, you should generate mask(s) for all object(s) of that category and then cross-examine the original image against the masked image carefully to locate the exact mask(s) that match or answer the initial user input query and select only those mask(s).2. Do not try to directly ground words, letters, or numbers in written text on the image. For example, if there is text on a sign to ground, you should use "sign" as your "text_prompt" instead of using the actual text itself as your "text_prompt".3. If your call to segment_phrase does not generate any useful mask(s) or if the mask(s) are incomplete, you may want to try calling the segment_phrase tool again using a more general noun phrase. For example, if the "text_prompt" "elementary school teacher" does not give you any mask(s), you can call segment_phrase again with the "text_prompt": "person".4. You should avoid identifying concepts using actions, relationships, or comparatives; instead, call segment_phrase on a more general phrase and let the segment_phrase tool generate more mask(s) than you need. Then, in the next turn, you can use the select_masks_and_return tool to remove some mask(s). For example, use "vase" instead of "the bigger vase", use "dog" instead of "the dog lying down", and use "brown pillow" instead of "the pillow on the chair".5. If the results of segment_phrase are not what you expected, you can always call segment_phrase again using a different "text_prompt". For example, when grounding a dog's nose, you can try "dog nose" and "black marking" after "nose" does not work.6. Sometimes when the target object(s) are too niche and the segment_phrase tool does not provide any mask(s), you may want to try grounding a more general version of the object. For example, when "sundial" does not produce any mask(s), you can try grounding "statue".7. Be concise and get the right keywords; don't make your "text_prompt" long.8. Do not ever use the exact same "text_prompt" more than once. This is very important!9. Sometimes you may find that the user is referring to a person or some people as the main grounding target. In this case, you should absolutely avoid grounding identifying part(s) or attribute(s) of the person or people, even if these part(s) or component(s) are explicitly mentioned in the initial user input query. Instead, you should only call segment_phrase with general "text_prompt"s like "person", "man", "girl", "firefighter", etc. that refer to the person as a whole. Later you can refer back to these identifying part(s) or attribute(s) and look closely at the original image to help you select the correct mask(s).10. If a previously used "text_prompt" does not work, avoid using it again and think of a new, creative "text_prompt" that may be indirect but can achieve the target result. For example, when grounding the center of the cake with text written on it, try grounding "birthday greeting" instead.11. You should always call segment_phrase with a "text_prompt" that represents the entire grounding target to generate mask(s) that you can choose from (sometimes along with other entities of the same category if it is hard to avoid). Do not call segment_phrase with a "text_prompt" that refers to subpart(s) of the grounding target to narrow down your search, because your "final_answer_masks" array can only be composed of of mask(s) generated by segment_phrase. For example, when the grounding target is an adult, use the "text_prompt" "adult person" instead of "adult hand".12. If the initial user input query refers only to one specific object instance of a category, while there are other object instance(s) of the same category in the image that are not being referred to, you should call segment_phrase with a "text_prompt" that is the singular form of the category of object(s), and then use the select_masks_and_return and/or examine_each_mask tool to narrow down your "final_answer_masks".13. Every time you call the segment_phrase tool, all previously generated mask(s) will be deleted. You are forbidden from referring to mask(s) that exist only in previous images in the message history but have been deleted in the most recent turn (not rendered on the most recent image).14. You should only ground object(s) that fully match or answer the initial user input query, and ignore object(s) that only partially match the initial user input query. For example, if the user is asking for object(s) used for inputting data and controlling the computer, you should only ground the keyboard and not the mouse, since the mouse is only used for controlling the computer but not for inputting data.15. You should never propose a "text_prompt" that covers more area than the initial user input query, for example, if the initial user input query asks specifically for areas of the jeans that are broken, you should never propose the "text_prompt" "jeans" because it will definitely cover more area than the ground truth target.16. You should never propose a "text_prompt" that covers less area than the initial user input query, for example, if the initial user input query asks for the person holding a microphone, you should never propose the "text_prompt" "microphone" because it will definitely cover less area than the ground truth target.17. You should first try your best to propose a "text_prompt" that covers the exact same object(s) as referred to by the initial user input query, no more, no less. You may not propose a "text_prompt" that covers more object(s) than what is referred to by the initial user input query unless you have tried every creative "text_prompt" you can think of to cover exactly the correct object(s) and none of them worked.18. Be creative in your "text_prompt" choice; you may use synonyms and use visual common sense to think of different "text_prompt" choices. You have unlimited turns to call each tool, so take your time!
examine_each_mask: Use this tool when the segment_phrase tool generates multiple small or overlapping mask(s), making it difficult to distinguish the correct mask(s). examine_each_mask allows you to render and examine each mask independently to see small mask(s) clearly and avoid confusing overlapping mask(s). (examine_each_mask can only be called after segment_phrase has been called at least once.)Use cases: "Sometimes there are multiple small mask(s) or overlapping mask(s) rendered on an image, making it difficult to distinguish each mask from others. In this case, you should call the examine_each_mask tool to individually verify each mask and filter out incorrect mask(s)."Parameters for examine_each_mask: NoneReturn type: A new image with colored segmentation mask(s) accepted by the examine_each_mask tool, and a text message indicating how many masks were accepted.Important rules for using the examine_each_mask tool:1. You may only call the examine_each_mask tool when you have re-examined the raw input image and the most recent output image, and you are absolutely sure that all the correct mask(s) that match the initial user input query have been rendered on the most recent image, and there are no missing correct mask(s). You must state this explicitly before you call the examine_each_mask tool.2. Do not call the examine_each_mask tool if there is only one mask and the mask is not very small.3. Do not call the examine_each_mask tool when there are many masks in the image but they are neither very small nor overlapping.4. The purpose of calling examine_each_mask is to distinguish overlapping mask(s), to examine whether very small mask(s) are correct, or both.5. After you have carefully compared the generated mask(s) against the initial user input query and the original image, and stated that you are absolutely sure that all the correct mask(s) that match the initial user input query have been rendered on the most recent image, you may consider calling the examine_each_mask tool if there are multiple overlapping mask(s) generated and it is not easy for you to name the correct mask(s). For example, if the question is to ground "the cookie behind the other cookie", segment_phrase generates two mask(s) for the two cookies in the image, but they are overlapping. You can also call the examine_each_mask tool if there are one or more very small mask(s) that are generated and you are sure that some of them are correct, and it is not easy for you to directly decide the correct mask(s). For example, if the question is to ground "sharp teeth" and there are multiple small mask(s) generated but it is not easy for you to tell which ones are correct without zooming in on each mask.6. Do not call the examine_each_mask tool if there are many masks in the image but you can clearly tell each mask apart from all other mask(s), and there is no significant challenge in identifying the correct mask(s). For example, if the question is asking "where people can sit" and there are many masks for chairs, and you just need to list all the mask numbers for chairs.7. You may not call the examine_each_mask tool unless there are two images in the chat context and you can see explicitly numbered masks in the second image.
select_masks_and_return: Call this tool to select a subset of or all of the mask(s) rendered on the most recent image as your final output. When calling select_masks_and_return, you cannot select any mask(s) generated by previous rounds other than the most recent round in your "final_answer_masks". You can only use mask(s) from the most recent image in your message history. (select_masks_and_return can only be called after segment_phrase has been called at least once.)Use cases: "Given an image with one or more segmentation mask(s) already rendered on it, select_masks_and_return returns the set of mask(s) you select as the final output."Parameters for select_masks_and_return: {"type": "object", "properties": {"final_answer_masks": {"type": "array", "description": "An array of integers representing the selected mask(s) you want to choose as your final output, e.g., [1, 4, 5]"}}, "required": ["final_answer_masks"]}Return type: None (End of Conversation)Important rules for using the select_masks_and_return tool:1. Do not call select_masks_and_return unless you are absolutely sure that the set of mask(s) you are about to return is the correct set of mask(s) that match or answer the initial user input query.2. If at any point in your reasoning you indicated that there exist any target(s) in the image that match or answer the initial user input query, your final tool call must be select_masks_and_return; you cannot just give up grounding and call the report_no_mask tool. This is very important.3. The mask(s) are numbered from 1 to N (N being the total number of mask(s) rendered on the most recent image). When you call select_masks_and_return, the integers in your "final_answer_masks" array must be within this range, no exceptions! Make sure of this!4. There must never be any repeated integers in your "final_answer_masks" array; each integer must be unique. A "final_answer_masks" such as [1, 2, 3, 2, 1] is not acceptable and will trigger an error. You should avoid this format error at all costs.5. You may only call select_masks_and_return on mask(s) rendered in the most recent image. You must ignore any mask(s) from earlier images as they have already been deleted.6. The select_masks_and_return tool is what you would use for reporting your "final_answer_masks". If the currently available mask(s) in the most recent image (you cannot use mask(s) from earlier images) are not 100% complete, do not call the select_masks_and_return tool and continue updating them by calling other tools (possibly on more general noun phrases).7. Every time you call the segment_phrase tool, you will delete all previously generated mask(s). You are forbidden from selecting mask(s) in previous images in the message history other than the most recent image.8. Since you cannot refer to mask(s) generated in earlier calls to segment_phrase, you should plan out your tool calls carefully, and make sure that the most recent tool call to segment_phrase covers all the target object(s) you want to ground.9. You may not call the select_masks_and_return tool if there are no mask(s) rendered on the most recent image returned by your most recent tool call.10. The mask(s) you choose in your "final_answer_masks" should accurately capture the target object(s) and only the target object(s). It should not contain any other regions that do not belong to the target object(s). Nor should it contain only a part of the target object(s). If this criterion is not met, you must not call the select_masks_and_return tool. Instead, please continue using other tools to generate better mask(s).11. Sometimes in the image you might see a mask with a two-digit number that is larger than N (the total number of available mask(s) rendered on the most recent image). For example, if the user tells you there are only 3 masks generated on the most recent image, but you see a mask with the number "12" on it. This is a visual illusion caused by mask "1" and mask "2" being too close to each other. In this case, you should never refer to mask "12" as it does not exist. Instead, you can only refer to masks "1", "2", and "3" as specified in the user input.12. If there are a large number of masks you need to select in your "final_answer_masks" array, you are required to explicitly list all of them one by one. You may not use any form of abbreviation or code. For example, if there are 94 correct masks you need to return, you must generate a long response with the "final_answer_masks" being a long array of 94 integers. You must never use abbreviated code outputs such as {"final_answer_masks": [i for i in range(1, 94)]}.13. If the initial user input query involves colors, you must carefully double-check the raw input image and explicitly compare it against the most recent image with available mask(s) rendered on it before selecting your "final_answer_masks". This is because the available mask(s) rendered on the most recent image are colored and will change the original color of the object(s) on the raw input image.14. Before you are allowed to call the select_masks_and_return tool, you are required to carefully re-examine the raw input image, the initial user input query, and compare them against every single available segmentation mask on the most recent rendered image. You must explicitly restate the initial user input query, and verify the following three things:a. You must verify you are able to accurately locate all the correct mask(s) that match the initial user input query in the most recent rendered image.b. You must also verify that you have carefully checked each of the mask(s) you plan to select, and made sure that they best match the initial user input query. (list your reasoning for each mask)c. You have also verified that the other available mask(s) you do not plan to select are definitely wrong and do not match the initial user input query. (list your reasoning for each mask)15. The intermediate "text_prompt" used to call the segment_phrase tool should never be used or considered when you select the "final_answer_masks". Instead, you should only assess the available mask(s) by checking the initial user input query. For example, if the initial user input query was "The plane-shaped cake on the right" and the "text_prompt" you used for the segment_phrase tool was "green cake", you should select the available mask(s) that match "The plane-shaped cake on the right".16. If the initial user input query involves relative positions, then you must explicitly state in your thinking process the spatial positions of each mask relative to other available mask(s) before you call the select_masks_and_return tool.17. You may not select any mask(s) whose number is greater than 100. For example, you may not select mask 102 or mask 114 in your "final_answer_masks" array. This also means that you are not allowed to select more than 100 masks in your "final_answer_masks" array.18. You may not call the select_masks_and_return tool unless there are two images in the chat context and you can see explicitly numbered masks in the second image.
report_no_mask: Call this tool when you are absolutely sure that there are no object(s) in the image that match or answer the initial user input query.Use cases: "Reporting that the given image does not contain any target object(s) that match or answer the initial user input query."Parameters for report_no_mask: NoneReturn type: None (End of Conversation)Important rules for using the report_no_mask tool:1. If at any point in your reasoning you indicated that there are target object(s) in the image that exactly match or answer the initial user input query without ambiguity, then you should never call the report_no_mask tool. Instead, you should keep trying other tools with different parameters until you get the correct mask(s).2. If you have checked the image carefully and made sure that there are no concepts in the image that can possibly match or answer the initial user input query, you should call the report_no_mask tool.3. If the image is completely unrelated to the initial user input query and it seems like the user has provided an incorrect image, you should call the report_no_mask tool. You should never break the standard response format by asking if the user provided the wrong image.4. Before you are allowed to call the report_no_mask tool, you are required to carefully re-examine the raw input image and the initial user input query. You must explicitly restate the initial user input query, and analyze the image in detail to verify that there is indeed no object in the image that can possibly match the initial user input query.5. Sometimes the initial user input query is slightly wrong but still very much related to the image. For example, the user may ask you to ground "the red computer" when the computer in the image is purple; or the user may ask you to ground "girl on the left" when there is no girl on the left of the image but rather a woman on the left of the image. In these cases, you should accommodate the user errors and still ground the object(s) in the image that best match the initial user input query.6. You should seldom call the report_no_mask tool and only reserve it for cases where the initial user input query is completely unrelated to the raw input image.7. You must carefully examine all details in the raw input image and note them in your thinking, and reason step-by-step to determine if anything in the image could potentially match the initial user input query. You should not give up the grounding process and call the report_no_mask tool due to very small technicalities or small literal discrepancies. For example, if the user asks you to find a dry space, relatively dry areas like land would satisfy the constraint. If the user asks you to find object(s) that help you focus, headphones and even window shades could potentially serve the purpose. If the user asks you to find containers that can be used for holding hot water, cups or kettles can both work. You should only call the report_no_mask tool if there are very direct contradictions and/or hard constraints in the initial user input query that cause all objects in the raw input image to be invalid matches for the initial user input query.
Steps for Each Turn:
First, state the number of images there are in the chat context (There is at least one image and at most two images at any time.) Please note that if the raw input image is composed of two individual images concatenated visually; it still counts as only one image. This is very important!
Scenario 1: If there is only one image in the context (it must be the raw input image with no mask on it), you must perform the following steps. Steps 1-5 are mandatory thinking steps and therefore must be generated within <think> ..... </think> HTML tags. Step 6 is the mandatory tool calling step and must be generated within <tool> ..... </tool> HTML tags. You must make sure to generate the opening and closing HTML tags correctly.Your thinking steps:1. Analyze: Carefully describe and analyze the raw input image provided to you in the context of the initial user input query.2. Think: Based on your understanding of the image and the previously stated rules for how you should understand the initial user input query, think about precisely what target object(s) need to be grounded to accurately answer the initial user input query.3. Remind: Remind yourself that each call to the segment_phrase tool will cause all previously generated mask(s) to be deleted (and can never be referred to again). So you should never design a plan that requires combining output mask(s) from two separate calls to the segment_phrase tool. You must also remind yourself that you should only call the segment_phrase tool on the whole primary grounding target(s), and never call the segment_phrase tool on a uniquely identifying part or attribute of the primary grounding target(s).4. Plan: Design a step-by-step tool call plan for how you will use the existing tools to generate mask(s) that accurately ground the object(s) that match or answer the initial user input query.5. Decide: Based on your reasoning, determine a simple noun phrase you think is suitable for calling the segment_phrase tool. The phrase should be a simple, direct, singular noun phrase. In some cases, it may include adjectives, but it should never contain articles, possessives, or numbers.You mandatory tool call:After you finish all 5 thinking steps and have decided the simple noun phrase you think is suitable for calling the segment_phrase tool, you must generate a mandatory tool call to the "segment_phrase" tool with the simple noun phrase you have selected as the "text_prompt". Make sure you closely follow the rules for calling the "segment_phrase" tool, and enclose the tool call within <tool> ..... </tool> HTML tags.
Scenario 2: If there are exactly two images in the context, the first image must be the raw input image, and the second and most recent image must be the image with all available mask(s) rendered on it. In Scenario 2, you must perform the following steps. Steps 1-5 are mandatory thinking steps and therefore must be generated within <think> ..... </think> HTML tags. Step 6 is the mandatory tool calling step and must be generated within <tool> ..... </tool> HTML tags. You must make sure to generate the opening and closing HTML tags correctly.Your steps:1. Analyze: Carefully describe and analyze both the first image (the raw input image) and the second and most recent image (the image with all available mask(s) rendered on it) in the context of the initial user input query. If there are fewer than twenty available mask(s) in the second (most recent) image, you are required to analyze each available mask individually on the second and most recent image and state why they are correct, or why they are incorrect. The specific analysis you generate for each mask should be determined based on the initial user input query and the raw input image. If the initial user input query mentions the relation of the target object(s) to other object(s) in the image, you must also explain each mask's relation to other available mask(s). For example, if the initial user input query is "the second man from the right", then your analysis for each available mask must include a direct response to the query, like: "Mask N covers the m-th man from the right".2. Think: Determine whether any, some, or all of the target object(s) referred to by the initial user input query have been covered by available mask(s) in the second and most recent image. Re-examine the raw input image carefully to determine whether there are still missing target object(s) in the image that match or answer the initial user input query but are not yet covered by any segmentation mask. After carefully examining the raw input image, if you find that all of the target object(s) referred to by the initial user input query have been covered and that there are no more missing target(s), you must write: "After carefully examining the raw input image, I am certain that all the target(s) referred to by the initial user input query have been covered by available mask(s)."3. Remind: If you need to update your step-by-step tool call plan, you must remind yourself that each call to the segment_phrase tool will cause all previously generated mask(s) to be deleted (and can never be referred to again). So you should never design a plan that requires combining output mask(s) from two separate calls to the segment_phrase tool. You must also remind yourself that you should only call the segment_phrase tool on the whole primary grounding target(s), and never call the segment_phrase tool on a uniquely identifying part or attribute of the primary grounding target(s). You must also remind yourself to look closely at both the first raw input image and the second and most recent image with all available mask(s) rendered on it. You must analyze all the available mask(s) one by one and discuss the relative position of each mask to the other mask(s) (if there are multiple masks).4. Plan: State whether you need to update your plan based on the tool execution results and user feedback from the previous round. If so, update your step-by-step plan to use the existing tools to generate mask(s) that accurately ground the object(s) that match or answer the initial user input query if necessary.5. Decide: Based on your reasoning, decide exactly which tool you should use next and what parameters (if any) you should call the tool with.You mandatory tool call:After you finish all 5 thinking steps, generate the tool call with the exact tool name and exact parameters you have just selected. You may only call one of the four available tools within: "segment_phrase", "examine_each_mask", "select_masks_and_return", and "report_no_mask". Make sure you closely follow the respective rules for calling each of these tools and enclose the tool call within <tool> ..... </tool> HTML tags.
Output Format for Scenario 1:<think> State that there is only one image in the message history (the raw input image). Since there is only one image, you will follow the Scenario 1 instructions:1. Analyze: Carefully describe and analyze the raw input image provided to you in the context of the initial user input query.2. Think: Based on your understanding of the image and the previously stated rules for how you should understand the initial user input query, think about precisely what target object(s) need to be grounded to accurately answer the initial user input query.3. Remind: Remind yourself that each call to the segment_phrase tool will cause all previously generated mask(s) to be deleted (and can never be referred to again). So you should never design a plan that requires combining output mask(s) from two separate calls to the segment_phrase tool. You must also remind yourself that you should only call the segment_phrase tool on the whole primary grounding target(s), and never call the segment_phrase tool on a uniquely identifying part or attribute of the primary grounding target(s).4. Plan: Design a step-by-step tool call plan for how you will use the existing tools to generate mask(s) that accurately ground the object(s) that match or answer the initial user input query.5. Decide: Based on your reasoning, determine a simple noun phrase you think is suitable for calling the segment_phrase tool. The phrase should be a simple, direct, singular noun phrase. In some cases, it may include adjectives, but it should never contain articles, possessives, or numbers. </think><tool> {"name": "tool name", "parameters": {"Parameter name": "Parameter content", "... ...": "... ..."}} </tool>Stop your response and wait for user feedback.
Output Format for Scenario 2:<think> State exactly how many images there are in the context (there are exactly two). Since there are exactly two images, you will follow the Scenario 2 instructions:1. Analyze: Carefully describe and analyze both the first image (the raw input image) and the second and most recent image (the image with all available mask(s) rendered on it) in the context of the initial user input query. If there are fewer than twenty available mask(s) in the second (most recent) image, you are required to analyze each available mask individually on the second and most recent image and state why they are correct, or why they are incorrect. The specific analysis you generate for each mask should be directly related to the initial user input query and the raw input image. If the initial user input query mentions the spatial relation of the target object(s) to other object(s) in the image, you must explain each mask's spatial relation to other available mask(s). For example, if the initial user input query is "the second man from the right", then your analysis for each available mask must include a direct response to the query stating the spatial position of the mask, for example: "Mask 2 covers the third man from the right, the mask is to the left of mask 1 and mask 4, but to the right of mask 3 and mask 5".2. Think: Determine whether any, some, or all of the target object(s) referred to by the initial user input query have been covered by available mask(s) in the second and most recent image. Re-examine the raw input image carefully to determine whether there are still missing target object(s) in the image that match or answer the initial user input query but are not yet covered by any segmentation mask. After carefully examining the raw input image, if you find that all of the target object(s) referred to by the initial user input query have been covered and that there are no more missing target(s), you must write: "After carefully examining the raw input image, I am certain that all the target(s) referred to by the initial user input query have been covered by available mask(s)."3. Remind: If you need to update your step-by-step tool call plan, you must remind yourself that each call to the segment_phrase tool will cause all previously generated mask(s) to be deleted (and can never be referred to again). So you should never design a plan that requires combining output mask(s) from two separate calls to the segment_phrase tool. You must also remind yourself that you should only call the segment_phrase tool on the whole primary grounding target(s), and never call the segment_phrase tool on a uniquely identifying part or attribute of the primary grounding target(s). You must also remind yourself to look closely at both the first raw input image and the second and most recent image with all available mask(s) rendered on it. You must analyze all the available mask(s) one by one and discuss the relative position of each mask to the other mask(s) (if there are multiple masks).4. Plan: State whether you need to update your plan based on the tool execution results and user feedback from the previous round. If so, update your step-by-step plan to use the existing tools to generate mask(s) that accurately ground the object(s) that match or answer the initial user input query if necessary.5. Decide: Based on your reasoning, decide exactly which tool you should use next and what parameters (if any) you should call the tool with. </think><tool> {"name": "tool name", "parameters": {"Parameter name": "Parameter content", "... ...": "... ..."}} </tool>
Important response formatting rules:1. You must always include the <think> ..... </think> field to outline your reasoning and the <tool> ..... </tool> field to specify the action you choose to take before you end a turn.2. Each tool call should be a JSON object with a "name" field and a "parameters" field containing a dictionary of parameters. If no parameters are needed, leave the "parameters" field as an empty dictionary.3. Refer to the previous dialogue history, including the initial user input query, previous reasoning, previous tool calls, and user feedback from previous tool calls.4. Do not wrap your entire output in a single large JSON object.5. Do not try to output multiple rounds of tool calls in a single turn. Stop immediately after you call one tool.6. If your initial attempts do not work out, do not give up; try more tool calls with different parameters. Take as long as you need!
Please be reminded of the important tool calling rules:
Important rules for using the segment_phrase tool:1. You may use visual adjectives such as color to help identify the concept you want to ground, but do not use complicated descriptors like numbers or mention text that is written on the image as the segment_phrase tool does not have OCR capabilities. For example, use "black ball" instead of "8-ball" to ground a black ball with the number "8" written on it. If the user asks you to ground an object that can only be identified by the text or number written on it, you should generate mask(s) for all object(s) of that category and then cross-examine the original image against the masked image carefully to locate the exact mask(s) that match or answer the initial user input query and select only those mask(s).2. Do not try to directly ground words, letters, or numbers in written text on the image. For example, if there is text on a sign to ground, you should use "sign" as your "text_prompt" instead of using the actual text itself as your "text_prompt".3. If your call to segment_phrase does not generate any useful mask(s) or if the mask(s) are incomplete, you may want to try calling the segment_phrase tool again using a more general noun phrase. For example, if the "text_prompt" "elementary school teacher" does not give you any mask(s), you can call segment_phrase again with the "text_prompt": "person".4. You should avoid identifying concepts using actions, relationships, or comparatives; instead, call segment_phrase on a more general phrase and let the segment_phrase tool generate more mask(s) than you need. Then, in the next turn, you can use the select_masks_and_return tool to remove some mask(s). For example, use "vase" instead of "the bigger vase", use "dog" instead of "the dog lying down", and use "brown pillow" instead of "the pillow on the chair".5. If the results of segment_phrase are not what you expected, you can always call segment_phrase again using a different "text_prompt". For example, when grounding a dog's nose, you can try "dog nose" and "black marking" after "nose" does not work.6. Sometimes when the target object(s) are too niche and the segment_phrase tool does not provide any mask(s), you may want to try grounding a more general version of the object. For example, when "sundial" does not produce any mask(s), you can try grounding "statue".7. Be concise and get the right keywords; don't make your "text_prompt" long.8. Do not ever use the exact same "text_prompt" more than once. This is very important!9. Sometimes you may find that the user is referring to a person or some people as the main grounding target. In this case, you should absolutely avoid grounding identifying part(s) or attribute(s) of the person or people, even if these part(s) or component(s) are explicitly mentioned in the initial user input query. Instead, you should only call segment_phrase with general "text_prompt"s like "person", "man", "girl", "firefighter", etc. that refer to the person as a whole. Later you can refer back to these identifying part(s) or attribute(s) and look closely at the original image to help you select the correct mask(s).10. If a previously used "text_prompt" does not work, avoid using it again and think of a new, creative "text_prompt" that may be indirect but can achieve the target result. For example, when grounding the center of the cake with text written on it, try grounding "birthday greeting" instead.11. You should always call segment_phrase with a "text_prompt" that represents the entire grounding target to generate mask(s) that you can choose from (sometimes along with other entities of the same category if it is hard to avoid). Do not call segment_phrase with a "text_prompt" that refers to subpart(s) of the grounding target to narrow down your search, because your "final_answer_masks" array can only be composed of mask(s) generated by segment_phrase. For example, when the grounding target is an adult, use the "text_prompt" "adult person" instead of "adult hand".12. If the initial user input query refers only to one specific object instance of a category, while there are other object instance(s) of the same category in the image that are not being referred to, you should call segment_phrase with a "text_prompt" that is the singular form of the category of object(s), and then use the select_masks_and_return and/or examine_each_mask tool to narrow down your "final_answer_masks".13. Every time you call the segment_phrase tool, all previously generated mask(s) will be deleted. You are forbidden from referring to mask(s) that exist only in previous images in the message history but have been deleted in the most recent turn (not rendered on the most recent image).14. You should only ground object(s) that fully match or answer the initial user input query, and ignore object(s) that only partially match the initial user input query. For example, if the user is asking for object(s) used for inputting data and controlling the computer, you should only ground the keyboard and not the mouse, since the mouse is only used for controlling the computer but not for inputting data.15. You should never propose a "text_prompt" that covers more area than the initial user input query, for example, if the initial user input query asks specifically for areas of the jeans that are broken, you should never propose the "text_prompt" "jeans" because it will definitely cover more area than the ground truth target.16. You should never propose a "text_prompt" that covers less area than the initial user input query, for example, if the initial user input query asks for the person holding a microphone, you should never propose the "text_prompt" "microphone" because it will definitely cover less area than the ground truth target.17. You should first try your best to propose a "text_prompt" that covers the exact same object(s) as referred to by the initial user input query, no more, no less. You may not propose a "text_prompt" that covers more object(s) than what is referred to by the initial user input query unless you have tried every creative "text_prompt" you can think of to cover exactly the correct object(s) and none of them worked.18. Be creative in your "text_prompt" choice; you may use synonyms and use visual common sense to think of different "text_prompt" choices. You have unlimited turns to call each tool, so take your time!
Important rules for using the examine_each_mask tool:1. You may only call the examine_each_mask tool when you have re-examined the raw input image and the most recent output image, and you are absolutely sure that all the correct mask(s) that match the initial user input query have been rendered on the most recent image, and there are no missing correct mask(s). You must state this explicitly before you call the examine_each_mask tool.2. Do not call the examine_each_mask tool if there is only one mask and the mask is not very small.3. Do not call the examine_each_mask tool when there are many masks in the image but they are neither very small nor overlapping.4. The purpose of calling examine_each_mask is to distinguish overlapping mask(s), to examine whether very small mask(s) are correct, or both.5. After you have carefully compared the generated mask(s) against the initial user input query and the original image, and stated that you are absolutely sure that all the correct mask(s) that match the initial user input query have been rendered on the most recent image, you may consider calling the examine_each_mask tool if there are multiple overlapping mask(s) generated and it is not easy for you to name the correct mask(s). For example, if the question is to ground "the cookie behind the other cookie", segment_phrase generates two mask(s) for the two cookies in the image, but they are overlapping. You can also call the examine_each_mask tool if there are one or more very small mask(s) that are generated and you are sure that some of them are correct, and it is not easy for you to directly decide the correct mask(s). For example, if the question is to ground "sharp teeth" and there are multiple small mask(s) generated but it is not easy for you to tell which ones are correct without zooming in on each mask.6. Do not call the examine_each_mask tool if there are many masks in the image but you can clearly tell each mask apart from all other mask(s), and there is no significant challenge in identifying the correct mask(s). For example, if the question is asking "where people can sit" and there are many masks for chairs, and you just need to list all the mask numbers for chairs.7. You may not call the examine_each_mask tool unless there are two images in the chat context and you can see explicitly numbered masks in the second image.
Important rules for using the select_masks_and_return tool:1. Do not call select_masks_and_return unless you are absolutely sure that the set of mask(s) you are about to return is the correct set of mask(s) that match or answer the initial user input query.2. If at any point in your reasoning you indicated that there exist any target(s) in the image that match or answer the initial user input query, your final tool call must be select_masks_and_return; you cannot just give up grounding and call the report_no_mask tool. This is very important.3. The mask(s) are numbered from 1 to N (N being the total number of mask(s) rendered on the most recent image). When you call select_masks_and_return, the integers in your "final_answer_masks" array must be within this range, no exceptions! Make sure of this!4. There must never be any repeated integers in your "final_answer_masks" array; each integer must be unique. A "final_answer_masks" such as [1, 2, 3, 2, 1] is not acceptable and will trigger an error. You should avoid this format error at all costs.5. You may only call select_masks_and_return on mask(s) rendered in the most recent image. You must ignore any mask(s) from earlier images as they have already been deleted.6. The select_masks_and_return tool is what you would use for reporting your "final_answer_masks". If the currently available mask(s) in the most recent image (you cannot use mask(s) from earlier images) are not 100% complete, do not call the select_masks_and_return tool and continue updating them by calling other tools (possibly on more general noun phrases).7. Every time you call the segment_phrase tool, you will delete all previously generated mask(s). You are forbidden from selecting mask(s) in previous images in the message history other than the most recent image.8. Since you cannot refer to mask(s) generated in earlier calls to segment_phrase, you should plan out your tool calls carefully, and make sure that the most recent tool call to segment_phrase covers all the target object(s) you want to ground.9. You may not call the select_masks_and_return tool if there are no mask(s) rendered on the most recent image returned by your most recent tool call.10. The mask(s) you choose in your "final_answer_masks" should accurately capture the target object(s) and only the target object(s). It should not contain any other regions that do not belong to the target object(s). Nor should it contain only a part of the target object(s). If this criterion is not met, you must not call the select_masks_and_return tool. Instead, please continue using other tools to generate better mask(s).11. Sometimes in the image you might see a mask with a two-digit number that is larger than N (the total number of available mask(s) rendered on the most recent image). For example, if the user tells you there are only 3 masks generated on the most recent image, but you see a mask with the number "12" on it. This is a visual illusion caused by mask "1" and mask "2" being too close to each other. In this case, you should never refer to mask "12" as it does not exist. Instead, you can only refer to masks "1", "2", and "3" as specified in the user input.12. If there are a large number of masks you need to select in your "final_answer_masks" array, you are required to explicitly list all of them one by one. You may not use any form of abbreviation or code. For example, if there are 94 correct masks you need to return, you must generate a long response with the "final_answer_masks" being a long array of 94 integers. You must never use abbreviated code outputs such as {"final_answer_masks": [i for i in range(1, 94)]}.13. If the initial user input query involves colors, you must carefully double-check the raw input image and explicitly compare it against the most recent image with available mask(s) rendered on it before selecting your "final_answer_masks". This is because the available mask(s) rendered on the most recent image are colored and will change the original color of the object(s) on the raw input image.14. Before you are allowed to call the select_masks_and_return tool, you are required to carefully re-examine the raw input image, the initial user input query, and compare them against every single available segmentation mask on the most recent rendered image. You must explicitly restate the initial user input query, and verify the following three things:a. You must verify you are able to accurately locate all the correct mask(s) that match the initial user input query in the most recent rendered image.b. You must also verify that you have carefully checked each of the mask(s) you plan to select, and made sure that they best match the initial user input query. (list your reasoning for each mask)c. You have also verified that the other available mask(s) you do not plan to select are definitely wrong and do not match the initial user input query. (list your reasoning for each mask)15. The intermediate "text_prompt" used to call the segment_phrase tool should never be used or considered when you select the "final_answer_masks". Instead, you should only assess the available mask(s) by checking the initial user input query. For example, if the initial user input query was "The plane-shaped cake on the right" and the "text_prompt" you used for the segment_phrase tool was "green cake", you should select the available mask(s) that match "The plane-shaped cake on the right".16. If the initial user input query involves relative positions, then you must explicitly state in your thinking process the spatial positions of each mask relative to other available mask(s) before you call the select_masks_and_return tool.17. You may not select any mask(s) whose number is greater than 100. For example, you may not select mask 102 or mask 114 in your "final_answer_masks" array. This also means that you are not allowed to select more than 100 masks in your "final_answer_masks" array.18. You may not call the select_masks_and_return tool unless there are two images in the chat context and you can see explicitly numbered masks in the second image.
Important rules for using the report_no_mask tool:1. If at any point in your reasoning you indicated that there are target object(s) in the image that exactly match or answer the initial user input query without ambiguity, then you should never call the report_no_mask tool. Instead, you should keep trying other tools with different parameters until you get the correct mask(s).2. If you have checked the image carefully and made sure that there are no concepts in the image that can possibly match or answer the initial user input query, you should call the report_no_mask tool.3. If the image is completely unrelated to the initial user input query and it seems like the user has provided an incorrect image, you should call the report_no_mask tool. You should never break the standard response format by asking if the user provided the wrong image.4. Before you are allowed to call the report_no_mask tool, you are required to carefully re-examine the raw input image and the initial user input query. You must explicitly restate the initial user input query, and analyze the image in detail to verify that there is indeed no object in the image that can possibly match the initial user input query.5. Sometimes the initial user input query is slightly wrong but still very much related to the image. For example, the user may ask you to ground "the red computer" when the computer in the image is purple; or the user may ask you to ground "girl on the left" when there is no girl on the left of the image but rather a woman on the left of the image. In these cases, you should accommodate the user errors and still ground the object(s) in the image that best match the initial user input query.6. You should seldom call the report_no_mask tool and only reserve it for cases where the initial user input query is completely unrelated to the raw input image.7. You must carefully examine all details in the raw input image and note them in your thinking, and reason step-by-step to determine if anything in the image could potentially match the initial user input query. You should not give up the grounding process and call the report_no_mask tool due to very small technicalities or small literal discrepancies. For example, if the user asks you to find a dry space, relatively dry areas like land would satisfy the constraint. If the user asks you to find object(s) that help you focus, headphones and even window shades could potentially serve the purpose. If the user asks you to find containers that can be used for holding hot water, cups or kettles can both work. You should only call the report_no_mask tool if there are very direct contradictions and/or hard constraints in the initial user input query that cause all objects in the raw input image to be invalid matches for the initial user input query.
Please also be reminded of the following important rules for how you should understand the initial user input query and the raw input image:
1. If there are multiple instances of the target object class in the image, you should read the initial user input query very carefully and think about whether the initial user input query applies broadly to all the instances or just one specific instance, and ground accordingly.2. You should think carefully and find the actual target object(s) the user is asking you to ground. Never call the segment_phrase tool to ground secondary object(s) in the initial user input query that only exist to help you identify the actual target. For example, given the initial user input query 'a giraffe with its head up', you should ground the whole 'giraffe' and not 'the head of the giraffe'. Given the initial user input query 'a person holding a blender with their left hand', you should ground 'person' instead of 'blender' or 'left hand'. Given the initial user input query 'two lovely ladies conversing while walking a dog, behind a bicycle', you should ground 'woman' instead of 'dog' or 'bicycle'. Given the initial user input query "guy with white hat", you should ground the "guy" and not the "white hat".3. Sometimes the user will mention or use non-target object(s) in their description to help identify the target object(s), you must make sure not to include mask(s) for those object(s) that are only used for identification purposes. For example, given the initial user input query "a man carrying a young girl", you should only ground the main target the "man" and not include the "young girl" in your final predicted mask(s). Given the initial user input query "a small girl staring at something, along with her older sister", you should only ground the "small girl" and not include her "older sister" in your final predicted mask(s).4. Sometimes the target object(s) are not directly named in the description but are clearly referenced, in which case you should focus only on grounding the clearly referenced target object(s). For example, given the initial user input query "something that shows the man is playing golf" and an image of a man holding a golf club, you should ground the phrase "golf club" and not the phrase "man" even though "golf club" is not directly named in the initial user input query.5. You must carefully examine all details in the raw input image and note them in your thinking, and reason step-by-step to determine if anything in the image could potentially match the initial user input query. You should not give up the grounding process and call the report_no_mask tool due to very small technicalities or small literal discrepancies. For example, if the user asks you to find a dry space, relatively dry areas like land would satisfy the constraint. If the user asks you to find object(s) that help you focus, headphones and even window shades could potentially serve the purpose. If the user asks you to find containers that can be used for holding hot water, cups or kettles can both work. You should only call the report_no_mask tool if there are very direct contradictions and/or hard constraints in the initial user input query that cause all objects in the raw input image to be invalid matches for the initial user input query.6. Sometimes the initial user input query can be slightly wrong but still very much related to the image. For example, the user may ask you to ground "the red laptop" when the laptop computer in the image is purple (in this case you should call segment_phrase on the "text_prompt" "purple laptop computer"); or the user may ask you to ground "girl left" when there is no girl on the left of the image but rather a woman on the left of the image (in this case you should call segment_phrase to ground the phrase "left woman"). In these cases, you should accommodate the user errors and still ground the object(s) in the image that best match the initial user input query. You may slightly modify the initial user input query based on your observation of the original image to better match the user’s intent.7. Sometimes the initial user input query may be grammatically incorrect, contain typos, or contain irrelevant information. In these cases, you should not blindly try to ground part(s) of the initial user input query using segment_phrase. Instead, you should reason step by step to think about what the user is actually referring to, and then modify the initial user input query based on your understanding and careful analysis of the raw input image. For example, you may see an initial user input query like "left back to us guy", which you can interpret as the man on the left who is facing the other direction (if you can see such a man exists in the image), and then call segment_phrase on "man" and then select the correct mask. You may also see an initial user input query like "big maybe hotdog middle back taste good", and there are just nine sandwiches in the image placed in three rows, then you can probably infer that the user is trying to ground the sandwich in the middle of the back row. You can then call segment_phrase to ground the phrase "sandwich" and use the select_masks_and_return tool to accurately choose only the sandwich in the middle of the back row in your "final_answer_masks" array.8. The correct "final_answer_masks" array should never contain any mask(s) whose number is greater than 100. For example, you may never select mask 102 or mask 114 in your "final_answer_masks" array. This also means that you are never allowed to select more than 100 masks in your "final_answer_masks" array.9. Please note that if the raw input image is composed of two individual sub-images concatenated visually; it still counts as only one image. If you find that there are "two" images in the chat context but the "second image" is not the same as the first image overlaid with numbered segmentation masks, this means that the "second image" is actually just a sub-image of the raw input image concatenated with the "first image" to serve as a combined raw input image. In this case, there is actually only one image in the chat context and you should follow the Scenario 1 instructions. This is very important!
Begin!
Below are the raw input image and the initial user input query:1234567891011121314151617181920212223242526You are a helpful assistant specializing in detail-oriented visual understanding, reasoning, and classification, capable of carefully analyzing a predicted segmentation mask on an image along with zoomed-in views of the area around the predicted segmentation mask to determine whether the object covered by the predicted segmentation mask is one of the correct masks that match the user query.
The user will provide you with four pieces of information for you to jointly analyze before constructing your final prediction:1. A text message that can be either: a referring expression that may match some part(s) of the image, or a question whose answer points to some part(s) of the image.2. The raw original image, so you may examine the original image without any distractions from the colored segmentation mask.3. The whole original image with the predicted segmentation mask in question rendered on it, so you may examine the segmentation mask in the context of the whole image. This image is particularly useful for cases where the user query requires knowledge of global information. For example, for queries like "the second man from the right" or "the cupcake on the top left corner".4. A zoomed-in version of the predicted segmentation mask in question. This image consists of two sub-images connected together, one of the sub-images is the zoomed-in version of the predicted segmentation mask itself, the other sub-image is a slightly zoomed-in view of the bounding-box area around the predicted segmentation mask.
You should observe and analyze each of the images very carefully, notice all the details in every part and corner of each image, think about what the user is actually referring to, and finally determine whether the predicted segmentation mask is indeed a part of the ground truth or not.
Here are some more detailed instructions for how you should precisely understand the user query:
1. If there are multiple instances of the target object class in the image, you should read the user query very carefully and think about whether the user query applies broadly to all the instances or just one specific instance, and whether the predicted segmentation mask is one of the correct instances or not.2. You should think carefully and find the actual target object the user is asking you to ground. Do not ever accept masks that cover secondary objects in the user query that only exist to help you identify the actual target. For example, given the query 'a giraffe with its head up', you should only accept a mask that covers the whole 'giraffe' and reject masks that only cover 'the head of the giraffe'. Given the query 'a person holding blender with left hand', you should only accept a mask that covers the whole 'person' instead of a mask that covers 'blender' or 'left hand'. Given the query 'two lovely ladies conversing while walking a dog, behind a bicycle', you should only accept a mask that covers the 'woman' instead of a mask that covers the 'dog' or the 'bicycle'. Given the query "guy with white hat", you should only accept a mask that covers the "guy" and not a mask that covers the "white hat".3. Sometimes the user will mention or use non-target objects in their description to help identify the target objects, you must make sure not to accept masks for those objects that are only used for identification purposes. For example, given the query "a man carrying a young girl", you should only accept a mask covering the main target: the "man", and reject any masks that cover the "young girl". Given the query "a small girl staring at something, along with her older sister", you should only accept a mask covering the "small girl" and reject any masks covering her "older sister" in your final predicted masks.4. Sometimes the target object is not directly named in the description but clearly referred to, in which case you should only accept masks that clearly cover the referred to target object. For example, given the query "something that shows the man is playing golf" and an image of a man holding a golf club, you should only accept a mask that covers the "golf club" and not a mask that covers the "man" even though "golf club" is not directly named in the query.5. You should carefully examine both the input image and the user text query, and reason step-by-step to jointly determine which grounding target actually best matches the user query. For example, if given a picture of a handbag with a soft leather handle and a hard metal chain, and the user query is "the part of bag that is comfortable to carry on the shoulder", you should think carefully about what parts can be used for carrying the bag and also importantly: which part would actually be comfortable to carry on the shoulder. You should perform very careful reasoning on both the image and the user query before determining what is the correct final grounding target.
Now, please analyze the image and think about whether the predicted segmentation mask is a part of the correct masks that matches with or answers the user query or not. First output your detailed analysis of each input image, and then output your step-by-step reasoning explaining why the predicted segmentation mask is correct or incorrect, and then finally respond with either <verdict>Accept</verdict> or <verdict>Reject</verdict>.
Please only respond in the following format and never break format for any reason:
<think>Analyze the user query and the three images: the raw input image, the image with the predicted segmentation mask rendered on it, and the image containing the zoomed-in version of the predicted segmentation mask. Then, think step-by-step about whether the predicted segmentation mask is a correct mask that matches the user query, given your prior analysis.</think><verdict>Accept</verdict> or <verdict>Reject</verdict>123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703# Copyright (c) Meta Platforms, Inc. and affiliates. All Rights Reserved
import contextlibimport copyimport jsonimport osimport timefrom collections import defaultdictfrom dataclasses import dataclassfrom typing import List, Union
import numpy as npimport pycocotools.mask as maskUtilsfrom pycocotools.coco import COCOfrom pycocotools.cocoeval import COCOevalfrom scipy.optimize import linear_sum_assignmentfrom tqdm import tqdm
@dataclassclass Metric: name: str
# whether the metric is computed at the image level or the box level image_level: bool
# iou threshold (None is used for image level metrics or to indicate averaging over all thresholds in [0.5:0.95]) iou_threshold: Union[float, None]
CGF1_METRICS = [ Metric(name="cgF1", image_level=False, iou_threshold=None), Metric(name="precision", image_level=False, iou_threshold=None), Metric(name="recall", image_level=False, iou_threshold=None), Metric(name="F1", image_level=False, iou_threshold=None), Metric(name="positive_macro_F1", image_level=False, iou_threshold=None), Metric(name="positive_micro_F1", image_level=False, iou_threshold=None), Metric(name="positive_micro_precision", image_level=False, iou_threshold=None), Metric(name="IL_precision", image_level=True, iou_threshold=None), Metric(name="IL_recall", image_level=True, iou_threshold=None), Metric(name="IL_F1", image_level=True, iou_threshold=None), Metric(name="IL_FPR", image_level=True, iou_threshold=None), Metric(name="IL_MCC", image_level=True, iou_threshold=None), Metric(name="cgF1", image_level=False, iou_threshold=0.5), Metric(name="precision", image_level=False, iou_threshold=0.5), Metric(name="recall", image_level=False, iou_threshold=0.5), Metric(name="F1", image_level=False, iou_threshold=0.5), Metric(name="positive_macro_F1", image_level=False, iou_threshold=0.5), Metric(name="positive_micro_F1", image_level=False, iou_threshold=0.5), Metric(name="positive_micro_precision", image_level=False, iou_threshold=0.5), Metric(name="cgF1", image_level=False, iou_threshold=0.75), Metric(name="precision", image_level=False, iou_threshold=0.75), Metric(name="recall", image_level=False, iou_threshold=0.75), Metric(name="F1", image_level=False, iou_threshold=0.75), Metric(name="positive_macro_F1", image_level=False, iou_threshold=0.75), Metric(name="positive_micro_F1", image_level=False, iou_threshold=0.75), Metric(name="positive_micro_precision", image_level=False, iou_threshold=0.75),]
class COCOCustom(COCO): """COCO class from pycocotools with tiny modifications for speed"""
def createIndex(self): # create index print("creating index...") anns, cats, imgs = {}, {}, {} imgToAnns, catToImgs = defaultdict(list), defaultdict(list) if "annotations" in self.dataset: for ann in self.dataset["annotations"]: imgToAnns[ann["image_id"]].append(ann) anns[ann["id"]] = ann
if "images" in self.dataset: # MODIFICATION: do not reload imgs if they are already there if self.imgs: imgs = self.imgs else: for img in self.dataset["images"]: imgs[img["id"]] = img # END MODIFICATION
if "categories" in self.dataset: for cat in self.dataset["categories"]: cats[cat["id"]] = cat
if "annotations" in self.dataset and "categories" in self.dataset: for ann in self.dataset["annotations"]: catToImgs[ann["category_id"]].append(ann["image_id"])
print("index created!")
# create class members self.anns = anns self.imgToAnns = imgToAnns self.catToImgs = catToImgs self.imgs = imgs self.cats = cats
def loadRes(self, resFile): """ Load result file and return a result api object. :param resFile (str) : file name of result file :return: res (obj) : result api object """ res = COCOCustom() res.dataset["info"] = copy.deepcopy(self.dataset.get("info", {})) # MODIFICATION: no copy # res.dataset['images'] = [img for img in self.dataset['images']] res.dataset["images"] = self.dataset["images"] # END MODIFICATION
print("Loading and preparing results...") tic = time.time() if type(resFile) == str: with open(resFile) as f: anns = json.load(f) elif type(resFile) == np.ndarray: anns = self.loadNumpyAnnotations(resFile) else: anns = resFile assert type(anns) == list, "results in not an array of objects" annsImgIds = [ann["image_id"] for ann in anns] # MODIFICATION: faster and cached subset check if not hasattr(self, "img_id_set"): self.img_id_set = set(self.getImgIds()) assert set(annsImgIds).issubset( self.img_id_set ), "Results do not correspond to current coco set" # END MODIFICATION if "caption" in anns[0]: imgIds = set([img["id"] for img in res.dataset["images"]]) & set( [ann["image_id"] for ann in anns] ) res.dataset["images"] = [ img for img in res.dataset["images"] if img["id"] in imgIds ] for id, ann in enumerate(anns): ann["id"] = id + 1 elif "bbox" in anns[0] and not anns[0]["bbox"] == []: res.dataset["categories"] = copy.deepcopy(self.dataset["categories"]) for id, ann in enumerate(anns): bb = ann["bbox"] x1, x2, y1, y2 = [bb[0], bb[0] + bb[2], bb[1], bb[1] + bb[3]] if not "segmentation" in ann: ann["segmentation"] = [[x1, y1, x1, y2, x2, y2, x2, y1]] ann["area"] = bb[2] * bb[3] ann["id"] = id + 1 ann["iscrowd"] = 0 elif "segmentation" in anns[0]: res.dataset["categories"] = copy.deepcopy(self.dataset["categories"]) for id, ann in enumerate(anns): # now only support compressed RLE format as segmentation results ann["area"] = maskUtils.area(ann["segmentation"]) if not "bbox" in ann: ann["bbox"] = maskUtils.toBbox(ann["segmentation"]) ann["id"] = id + 1 ann["iscrowd"] = 0 elif "keypoints" in anns[0]: res.dataset["categories"] = copy.deepcopy(self.dataset["categories"]) for id, ann in enumerate(anns): s = ann["keypoints"] x = s[0::3] y = s[1::3] x0, x1, y0, y1 = np.min(x), np.max(x), np.min(y), np.max(y) ann["area"] = (x1 - x0) * (y1 - y0) ann["id"] = id + 1 ann["bbox"] = [x0, y0, x1 - x0, y1 - y0] print("DONE (t={:0.2f}s)".format(time.time() - tic))
res.dataset["annotations"] = anns # MODIFICATION: inherit images res.imgs = self.imgs # END MODIFICATION res.createIndex() return res
class CGF1Eval(COCOeval): """ This evaluator is based upon COCO evaluation, but evaluates the model in a more realistic setting for downstream applications. See SAM3 paper for the details on the CGF1 metric.
Do not use this evaluator directly. Prefer the CGF1Evaluator wrapper.
Notes: - This evaluator does not support per-category evaluation (in the way defined by pyCocotools) - In open vocabulary settings, we have different noun-phrases for each image. What we call an "image_id" here is actually an (image, noun-phrase) pair. So in every "image_id" there is only one category, implied by the noun-phrase. Thus we can ignore the usual coco "category" field of the predictions """
def __init__( self, coco_gt=None, coco_dt=None, iouType="segm", threshold=0.5, ): """ Args: coco_gt (COCO): ground truth COCO API coco_dt (COCO): detections COCO API iou_type (str): type of IoU to evaluate threshold (float): threshold for predictions """ super().__init__(coco_gt, coco_dt, iouType) self.threshold = threshold
self.params.useCats = False self.params.areaRng = [[0**2, 1e5**2]] self.params.areaRngLbl = ["all"] self.params.maxDets = [1000000]
def computeIoU(self, imgId, catId): # Same as the original COCOeval.computeIoU, but without sorting p = self.params if p.useCats: gt = self._gts[imgId, catId] dt = self._dts[imgId, catId] else: gt = [_ for cId in p.catIds for _ in self._gts[imgId, cId]] dt = [_ for cId in p.catIds for _ in self._dts[imgId, cId]] if len(gt) == 0 and len(dt) == 0: return []
if p.iouType == "segm": g = [g["segmentation"] for g in gt] d = [d["segmentation"] for d in dt] elif p.iouType == "bbox": g = [g["bbox"] for g in gt] d = [d["bbox"] for d in dt] else: raise Exception("unknown iouType for iou computation")
# compute iou between each dt and gt region iscrowd = [int(o["iscrowd"]) for o in gt] ious = maskUtils.iou(d, g, iscrowd) return ious
def evaluateImg(self, imgId, catId, aRng, maxDet): """ perform evaluation for single category and image :return: dict (single image results) """ p = self.params assert not p.useCats, "This evaluator does not support per-category evaluation." assert catId == -1 all_gts = [_ for cId in p.catIds for _ in self._gts[imgId, cId]] keep_gt = np.array([not g["ignore"] for g in all_gts], dtype=bool) gt = [g for g in all_gts if not g["ignore"]] all_dts = [_ for cId in p.catIds for _ in self._dts[imgId, cId]] keep_dt = np.array([d["score"] >= self.threshold for d in all_dts], dtype=bool) dt = [d for d in all_dts if d["score"] >= self.threshold] if len(gt) == 0 and len(dt) == 0: # This is a "true negative" case, where there are no GTs and no predictions # The box-level metrics are ill-defined, so we don't add them to this dict return { "image_id": imgId, "IL_TP": 0, "IL_TN": 1, "IL_FP": 0, "IL_FN": 0, "num_dt": len(dt), }
if len(gt) > 0 and len(dt) == 0: # This is a "false negative" case, where there are GTs but no predictions return { "image_id": imgId, "IL_TP": 0, "IL_TN": 0, "IL_FP": 0, "IL_FN": 1, "TPs": np.zeros((len(p.iouThrs),), dtype=np.int64), "FPs": np.zeros((len(p.iouThrs),), dtype=np.int64), "FNs": np.ones((len(p.iouThrs),), dtype=np.int64) * len(gt), "local_F1s": np.zeros((len(p.iouThrs),), dtype=np.int64), "local_positive_F1s": np.zeros((len(p.iouThrs),), dtype=np.int64), "num_dt": len(dt), }
# Load pre-computed ious ious = self.ious[(imgId, catId)]
# compute matching if len(ious) == 0: ious = np.zeros((len(dt), len(gt))) else: ious = ious[keep_dt, :][:, keep_gt] assert ious.shape == (len(dt), len(gt))
matched_dt, matched_gt = linear_sum_assignment(-ious)
match_scores = ious[matched_dt, matched_gt]
TPs, FPs, FNs = [], [], [] IL_perfect = [] for thresh in p.iouThrs: TP = (match_scores >= thresh).sum() FP = len(dt) - TP FN = len(gt) - TP assert ( FP >= 0 and FN >= 0 ), f"FP: {FP}, FN: {FN}, TP: {TP}, match_scores: {match_scores}, len(dt): {len(dt)}, len(gt): {len(gt)}, ious: {ious}" TPs.append(TP) FPs.append(FP) FNs.append(FN)
if FP == FN and FP == 0: IL_perfect.append(1) else: IL_perfect.append(0)
TPs = np.array(TPs, dtype=np.int64) FPs = np.array(FPs, dtype=np.int64) FNs = np.array(FNs, dtype=np.int64) IL_perfect = np.array(IL_perfect, dtype=np.int64)
# compute precision recall and F1 precision = TPs / (TPs + FPs + 1e-4) assert np.all(precision <= 1) recall = TPs / (TPs + FNs + 1e-4) assert np.all(recall <= 1) F1 = 2 * precision * recall / (precision + recall + 1e-4)
result = { "image_id": imgId, "TPs": TPs, "FPs": FPs, "FNs": FNs, "local_F1s": F1, "IL_TP": (len(gt) > 0) and (len(dt) > 0), "IL_FP": (len(gt) == 0) and (len(dt) > 0), "IL_TN": (len(gt) == 0) and (len(dt) == 0), "IL_FN": (len(gt) > 0) and (len(dt) == 0), "num_dt": len(dt), } if len(gt) > 0 and len(dt) > 0: result["local_positive_F1s"] = F1 return result
def accumulate(self, p=None): """ Accumulate per image evaluation results and store the result in self.eval :param p: input params for evaluation :return: None """ if self.evalImgs is None or len(self.evalImgs) == 0: print("Please run evaluate() first") # allows input customized parameters if p is None: p = self.params
setImgIds = set(p.imgIds)
# TPs, FPs, FNs TPs = np.zeros((len(p.iouThrs),), dtype=np.int64) FPs = np.zeros((len(p.iouThrs),), dtype=np.int64) pmFPs = np.zeros((len(p.iouThrs),), dtype=np.int64) FNs = np.zeros((len(p.iouThrs),), dtype=np.int64) local_F1s = np.zeros((len(p.iouThrs),), dtype=np.float64)
# Image level metrics IL_TPs = 0 IL_FPs = 0 IL_TNs = 0 IL_FNs = 0
valid_img_count = 0 valid_F1_count = 0 evaledImgIds = set() for res in self.evalImgs: if res["image_id"] not in setImgIds: continue evaledImgIds.add(res["image_id"]) IL_TPs += res["IL_TP"] IL_FPs += res["IL_FP"] IL_TNs += res["IL_TN"] IL_FNs += res["IL_FN"]
if "TPs" not in res: continue
TPs += res["TPs"] FPs += res["FPs"] FNs += res["FNs"] valid_img_count += 1
if "local_positive_F1s" in res: local_F1s += res["local_positive_F1s"] pmFPs += res["FPs"] if res["num_dt"] > 0: valid_F1_count += 1
assert len(setImgIds - evaledImgIds) == 0, ( f"{len(setImgIds - evaledImgIds)} images not evaluated. " f"Here are the IDs of the first 3: {list(setImgIds - evaledImgIds)[:3]}" )
# compute precision recall and F1 precision = TPs / (TPs + FPs + 1e-4) positive_micro_precision = TPs / (TPs + pmFPs + 1e-4) assert np.all(precision <= 1) recall = TPs / (TPs + FNs + 1e-4) assert np.all(recall <= 1) F1 = 2 * precision * recall / (precision + recall + 1e-4) positive_micro_F1 = ( 2 * positive_micro_precision * recall / (positive_micro_precision + recall + 1e-4) )
IL_rec = IL_TPs / (IL_TPs + IL_FNs + 1e-6) IL_prec = IL_TPs / (IL_TPs + IL_FPs + 1e-6) IL_F1 = 2 * IL_prec * IL_rec / (IL_prec + IL_rec + 1e-6) IL_FPR = IL_FPs / (IL_FPs + IL_TNs + 1e-6) IL_MCC = float(IL_TPs * IL_TNs - IL_FPs * IL_FNs) / ( ( float(IL_TPs + IL_FPs) * float(IL_TPs + IL_FNs) * float(IL_TNs + IL_FPs) * float(IL_TNs + IL_FNs) ) ** 0.5 + 1e-6 )
self.eval = { "params": p, "TPs": TPs, "FPs": FPs, "positive_micro_FPs": pmFPs, "FNs": FNs, "precision": precision, "positive_micro_precision": positive_micro_precision, "recall": recall, "F1": F1, "positive_micro_F1": positive_micro_F1, "positive_macro_F1": local_F1s / valid_F1_count, "IL_recall": IL_rec, "IL_precision": IL_prec, "IL_F1": IL_F1, "IL_FPR": IL_FPR, "IL_MCC": IL_MCC, } self.eval["cgF1"] = self.eval["positive_micro_F1"] * self.eval["IL_MCC"]
def summarize(self): """ Compute and display summary metrics for evaluation results. """ if not self.eval: raise Exception("Please run accumulate() first")
def _summarize(iouThr=None, metric=""): p = self.params iStr = " {:<18} @[ IoU={:<9}] = {:0.3f}" titleStr = "Average " + metric iouStr = ( "{:0.2f}:{:0.2f}".format(p.iouThrs[0], p.iouThrs[-1]) if iouThr is None else "{:0.2f}".format(iouThr) )
s = self.eval[metric] # IoU if iouThr is not None: t = np.where(iouThr == p.iouThrs)[0] s = s[t]
if len(s[s > -1]) == 0: mean_s = -1 else: mean_s = np.mean(s[s > -1]) print(iStr.format(titleStr, iouStr, mean_s)) return mean_s
def _summarize_single(metric=""): titleStr = "Average " + metric iStr = " {:<35} = {:0.3f}" s = self.eval[metric] print(iStr.format(titleStr, s)) return s
def _summarizeDets(): stats = []
for metric in CGF1_METRICS: if metric.image_level: stats.append(_summarize_single(metric=metric.name)) else: stats.append( _summarize(iouThr=metric.iou_threshold, metric=metric.name) ) return np.asarray(stats)
summarize = _summarizeDets self.stats = summarize()
def _evaluate(self): """ Run per image evaluation on given images and store results (a list of dict) in self.evalImgs """ p = self.params # add backward compatibility if useSegm is specified in params p.imgIds = list(np.unique(p.imgIds)) p.useCats = False p.maxDets = sorted(p.maxDets) self.params = p
self._prepare() # loop through images, area range, max detection number catIds = [-1]
if p.iouType == "segm" or p.iouType == "bbox": computeIoU = self.computeIoU else: raise RuntimeError(f"Unsupported iou {p.iouType}") self.ious = { (imgId, catId): computeIoU(imgId, catId) for imgId in p.imgIds for catId in catIds }
maxDet = p.maxDets[-1] evalImgs = [ self.evaluateImg(imgId, catId, areaRng, maxDet) for catId in catIds for areaRng in p.areaRng for imgId in p.imgIds ] # this is NOT in the pycocotools code, but could be done outside evalImgs = np.asarray(evalImgs).reshape(len(catIds), len(p.areaRng), len(p.imgIds)) return p.imgIds, evalImgs
class CGF1Evaluator: """ Wrapper class for cgF1 evaluation. This supports the oracle setting (when several ground-truths are available per image) """
def __init__( self, gt_path: Union[str, List[str]], iou_type="segm", verbose=False, ): """ Args: gt_path (str or list of str): path(s) to ground truth COCO json file(s) iou_type (str): type of IoU to evaluate threshold (float): threshold for predictions """ self.gt_paths = gt_path if isinstance(gt_path, list) else [gt_path] self.iou_type = iou_type
self.coco_gts = [COCOCustom(gt) for gt in self.gt_paths]
self.verbose = verbose
self.coco_evals = [] for i, coco_gt in enumerate(self.coco_gts): self.coco_evals.append( CGF1Eval( coco_gt=coco_gt, iouType=iou_type, ) ) self.coco_evals[i].useCats = False
exclude_img_ids = set() # exclude_img_ids are the ids that are not exhaustively annotated in any of the other gts for coco_gt in self.coco_gts[1:]: exclude_img_ids = exclude_img_ids.union( { img["id"] for img in coco_gt.dataset["images"] if not img["is_instance_exhaustive"] } ) # we only eval on instance exhaustive queries self.eval_img_ids = [ img["id"] for img in self.coco_gts[0].dataset["images"] if (img["is_instance_exhaustive"] and img["id"] not in exclude_img_ids) ]
def evaluate(self, pred_file: str): """ Evaluate the detections using cgF1 metric.
Args: pred_file: path to the predictions COCO json file
""" assert len(self.coco_gts) > 0, "No ground truth provided for evaluation." assert len(self.coco_gts) == len( self.coco_evals ), "Mismatch in number of ground truths and evaluators."
if self.verbose: print(f"Loading predictions from {pred_file}")
with open(pred_file, "r") as f: preds = json.load(f)
if self.verbose: print(f"Loaded {len(preds)} predictions")
img2preds = defaultdict(list) for pred in preds: img2preds[pred["image_id"]].append(pred)
all_eval_imgs = [] for img_id in tqdm(self.eval_img_ids, disable=not self.verbose): results = img2preds[img_id] all_scorings = [] for cur_coco_gt, coco_eval in zip(self.coco_gts, self.coco_evals): # suppress pycocotools prints with open(os.devnull, "w") as devnull: with contextlib.redirect_stdout(devnull): coco_dt = ( cur_coco_gt.loadRes(results) if results else COCOCustom() )
coco_eval.cocoDt = coco_dt coco_eval.params.imgIds = [img_id] coco_eval.params.useCats = False img_ids, eval_imgs = _evaluate(coco_eval) all_scorings.append(eval_imgs) selected = self._select_best_scoring(all_scorings) all_eval_imgs.append(selected)
# After this point, we have selected the best scoring per image among several ground truths # we can now accumulate and summarize, using only the first coco_eval
self.coco_evals[0].evalImgs = list( np.concatenate(all_eval_imgs, axis=2).flatten() ) self.coco_evals[0].params.imgIds = self.eval_img_ids self.coco_evals[0]._paramsEval = copy.deepcopy(self.coco_evals[0].params)
if self.verbose: print(f"Accumulating results") self.coco_evals[0].accumulate() print("cgF1 metric, IoU type={}".format(self.iou_type)) self.coco_evals[0].summarize() print()
out = {} for i, value in enumerate(self.coco_evals[0].stats): name = CGF1_METRICS[i].name if CGF1_METRICS[i].iou_threshold is not None: name = f"{name}@{CGF1_METRICS[i].iou_threshold}" out[f"cgF1_eval_{self.iou_type}_{name}"] = float(value)
return out
@staticmethod def _select_best_scoring(scorings): # This function is used for "oracle" type evaluation. # It accepts the evaluation results with respect to several ground truths, and picks the best if len(scorings) == 1: return scorings[0]
assert ( scorings[0].ndim == 3 ), f"Expecting results in [numCats, numAreas, numImgs] format, got {scorings[0].shape}" assert ( scorings[0].shape[0] == 1 ), f"Expecting a single category, got {scorings[0].shape[0]}"
for scoring in scorings: assert ( scoring.shape == scorings[0].shape ), f"Shape mismatch: {scoring.shape}, {scorings[0].shape}"
selected_imgs = [] for img_id in range(scorings[0].shape[-1]): best = scorings[0][:, :, img_id]
for scoring in scorings[1:]: current = scoring[:, :, img_id] if "local_F1s" in best[0, 0] and "local_F1s" in current[0, 0]: # we were able to compute a F1 score for this particular image in both evaluations # best["local_F1s"] contains the results at various IoU thresholds. We simply take the average for comparision best_score = best[0, 0]["local_F1s"].mean() current_score = current[0, 0]["local_F1s"].mean() if current_score > best_score: best = current
else: # If we're here, it means that in that in some evaluation we were not able to get a valid local F1 # This happens when both the predictions and targets are empty. In that case, we can assume it's a perfect prediction if "local_F1s" not in current[0, 0]: best = current selected_imgs.append(best) result = np.stack(selected_imgs, axis=-1) assert result.shape == scorings[0].shape return result123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211# Copyright (c) Meta Platforms, Inc. and affiliates. All Rights Reservedimport jsonimport osfrom collections import defaultdict
from tqdm import tqdm
def convert_ytbvis_to_cocovid_gt(ann_json, save_path=None): """Convert YouTube VIS dataset to COCO-style video instance segmentation format.
Args: ann_json (str): Path to YouTube VIS annotation JSON file save_path (str): path to save converted COCO-style JSON """ # Initialize COCO structure VIS = { "info": {}, "images": [], "videos": [], "tracks": [], "annotations": [], "categories": [], "licenses": [], }
# Load original annotations official_anns = json.load(open(ann_json)) VIS["categories"] = official_anns["categories"] # Direct copy categories
# Initialize counters records = dict(img_id=1, ann_id=1)
# Create video-to-annotations mapping vid_to_anns = defaultdict(list) for ann in official_anns["annotations"]: vid_to_anns[ann["video_id"]].append(ann)
# Create tracks directly VIS["tracks"] = [ { "id": ann["id"], "category_id": ann["category_id"], "video_id": ann["video_id"], } for ann in official_anns["annotations"] ]
# Process videos for video_info in tqdm(official_anns["videos"]): # Create video entry video = { "id": video_info["id"], "name": os.path.dirname(video_info["file_names"][0]), "width": video_info["width"], "height": video_info["height"], "length": video_info["length"], "neg_category_ids": [], "not_exhaustive_category_ids": [], } VIS["videos"].append(video)
# Process frames num_frames = len(video_info["file_names"]) for frame_idx in range(num_frames): # Create image entry image = { "id": records["img_id"], "video_id": video_info["id"], "file_name": video_info["file_names"][frame_idx], "width": video_info["width"], "height": video_info["height"], "frame_index": frame_idx, "frame_id": frame_idx, } VIS["images"].append(image)
# Process annotations for this frame if video_info["id"] in vid_to_anns: for ann in vid_to_anns[video_info["id"]]: bbox = ann["bboxes"][frame_idx] if bbox is None: continue
# Create annotation entry annotation = { "id": records["ann_id"], "video_id": video_info["id"], "image_id": records["img_id"], "track_id": ann["id"], "category_id": ann["category_id"], "bbox": bbox, "area": ann["areas"][frame_idx], "segmentation": ann["segmentations"][frame_idx], "iscrowd": ann["iscrowd"], } VIS["annotations"].append(annotation) records["ann_id"] += 1
records["img_id"] += 1
# Print summary print(f"Converted {len(VIS['videos'])} videos") print(f"Converted {len(VIS['images'])} images") print(f"Created {len(VIS['tracks'])} tracks") print(f"Created {len(VIS['annotations'])} annotations")
if save_path is None: return VIS
# Save output save_dir = os.path.dirname(save_path) os.makedirs(save_dir, exist_ok=True) json.dump(VIS, open(save_path, "w"))
return VIS
def convert_ytbvis_to_cocovid_pred( youtubevis_pred_path: str, converted_dataset_path: str, output_path: str) -> None: """ Convert YouTubeVIS predictions to COCO format with video_id preservation
Args: youtubevis_pred_path: Path to YouTubeVIS prediction JSON converted_dataset_path: Path to converted COCO dataset JSON output_path: Path to save COCO format predictions """
# Load YouTubeVIS predictions with open(youtubevis_pred_path) as f: ytv_predictions = json.load(f)
# Load converted dataset for image ID mapping with open(converted_dataset_path) as f: coco_dataset = json.load(f)
# Create (video_id, frame_idx) -> image_id mapping image_id_map = { (img["video_id"], img["frame_index"]): img["id"] for img in coco_dataset["images"] }
coco_annotations = [] track_id_counter = 1 # Unique track ID generator
for pred in tqdm(ytv_predictions): video_id = pred["video_id"] category_id = pred["category_id"] bboxes = pred["bboxes"] segmentations = pred.get("segmentations", []) # Get segmentations if available areas = pred.get("areas", []) # Get areas if available score = pred["score"]
# Assign unique track ID for this prediction track_id = track_id_counter track_id_counter += 1
# Ensure segmentations and areas have the same length as bboxes if len(segmentations) == 0: segmentations = [None] * len(bboxes) if len(areas) == 0: areas = [None] * len(bboxes)
for frame_idx, (bbox, segmentation, area_from_pred) in enumerate( zip(bboxes, segmentations, areas) ): # Skip frames with missing objects (None or zero bbox) if bbox is None or all(x == 0 for x in bbox): continue
# Get corresponding image ID from mapping image_id = image_id_map.get((video_id, frame_idx)) if image_id is None: raise RuntimeError( f"prediction {video_id=}, {frame_idx=} does not match any images in the converted COCO format" )
# Extract bbox coordinates x, y, w, h = bbox
# Calculate area - use area from prediction if available, otherwise from bbox if area_from_pred is not None and area_from_pred > 0: area = area_from_pred else: area = w * h
# Create COCO annotation with video_id coco_annotation = { "image_id": int(image_id), "video_id": video_id, # Added video_id field "track_id": track_id, "category_id": category_id, "bbox": [float(x), float(y), float(w), float(h)], "area": float(area), "iscrowd": 0, "score": float(score), }
# Add segmentation if available if segmentation is not None: coco_annotation["segmentation"] = segmentation
coco_annotations.append(coco_annotation)
# Save output with open(output_path, "w") as f: json.dump(coco_annotations, f)
print(f"Converted {len(coco_annotations)} predictions to COCO format with video_id")123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114# flake8: noqa
"""run_youtube_vis.pyRun example:run_youtube_vis.py --USE_PARALLEL False --METRICS HOTA --TRACKERS_TO_EVAL STEm_SegCommand Line Arguments: Defaults, # Comments Eval arguments: 'USE_PARALLEL': False, 'NUM_PARALLEL_CORES': 8, 'BREAK_ON_ERROR': True, # Raises exception and exits with error 'RETURN_ON_ERROR': False, # if not BREAK_ON_ERROR, then returns from function on error 'LOG_ON_ERROR': os.path.join(code_path, 'error_log.txt'), # if not None, save any errors into a log file. 'PRINT_RESULTS': True, 'PRINT_ONLY_COMBINED': False, 'PRINT_CONFIG': True, 'TIME_PROGRESS': True, 'DISPLAY_LESS_PROGRESS': True, 'OUTPUT_SUMMARY': True, 'OUTPUT_EMPTY_CLASSES': True, # If False, summary files are not output for classes with no detections 'OUTPUT_DETAILED': True, 'PLOT_CURVES': True, Dataset arguments: 'GT_FOLDER': os.path.join(code_path, 'data/gt/youtube_vis/youtube_vis_training'), # Location of GT data 'TRACKERS_FOLDER': os.path.join(code_path, 'data/trackers/youtube_vis/youtube_vis_training'), # Trackers location 'OUTPUT_FOLDER': None, # Where to save eval results (if None, same as TRACKERS_FOLDER) 'TRACKERS_TO_EVAL': None, # Filenames of trackers to eval (if None, all in folder) 'CLASSES_TO_EVAL': None, # Classes to eval (if None, all classes) 'SPLIT_TO_EVAL': 'training', # Valid: 'training', 'val' 'PRINT_CONFIG': True, # Whether to print current config 'OUTPUT_SUB_FOLDER': '', # Output files are saved in OUTPUT_FOLDER/tracker_name/OUTPUT_SUB_FOLDER 'TRACKER_SUB_FOLDER': 'data', # Tracker files are in TRACKER_FOLDER/tracker_name/TRACKER_SUB_FOLDER 'TRACKER_DISPLAY_NAMES': None, # Names of trackers to display, if None: TRACKERS_TO_EVAL Metric arguments: 'METRICS': ['TrackMAP', 'HOTA', 'CLEAR', 'Identity']"""
import argparseimport osimport sysfrom multiprocessing import freeze_support
from . import trackeval
def run_ytvis_eval(args=None, gt_json=None, dt_json=None): # Command line interface: default_eval_config = trackeval.Evaluator.get_default_eval_config() # print only combined since TrackMAP is undefined for per sequence breakdowns default_eval_config["PRINT_ONLY_COMBINED"] = True default_dataset_config = trackeval.datasets.YouTubeVIS.get_default_dataset_config() default_metrics_config = {"METRICS": ["HOTA"]} config = { **default_eval_config, **default_dataset_config, **default_metrics_config, } # Merge default configs parser = argparse.ArgumentParser() for setting in config.keys(): if type(config[setting]) == list or type(config[setting]) == type(None): parser.add_argument("--" + setting, nargs="+") else: parser.add_argument("--" + setting) args = parser.parse_args(args).__dict__ for setting in args.keys(): if args[setting] is not None: if type(config[setting]) == type(True): if args[setting] == "True": x = True elif args[setting] == "False": x = False else: raise Exception( "Command line parameter " + setting + "must be True or False" ) elif type(config[setting]) == type(1): x = int(args[setting]) elif type(args[setting]) == type(None): x = None else: x = args[setting] config[setting] = x eval_config = {k: v for k, v in config.items() if k in default_eval_config.keys()} dataset_config = { k: v for k, v in config.items() if k in default_dataset_config.keys() } metrics_config = { k: v for k, v in config.items() if k in default_metrics_config.keys() }
# Run code evaluator = trackeval.Evaluator(eval_config) # allow directly specifying the GT JSON data and Tracker (result) # JSON data as Python objects, without reading from files. dataset_config["GT_JSON_OBJECT"] = gt_json dataset_config["TRACKER_JSON_OBJECT"] = dt_json dataset_list = [trackeval.datasets.YouTubeVIS(dataset_config)] metrics_list = [] # for metric in [trackeval.metrics.TrackMAP, trackeval.metrics.HOTA, trackeval.metrics.CLEAR, # trackeval.metrics.Identity]: for metric in [trackeval.metrics.HOTA]: if metric.get_name() in metrics_config["METRICS"]: metrics_list.append(metric()) if len(metrics_list) == 0: raise Exception("No metrics selected for evaluation") output_res, output_msg = evaluator.evaluate(dataset_list, metrics_list) return output_res, output_msg
if __name__ == "__main__": import sys
freeze_support() run_ytvis_eval(sys.argv[1:])123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379# flake8: noqa
import csvimport ioimport osimport tracebackimport zipfilefrom abc import ABC, abstractmethodfrom copy import deepcopy
import numpy as np
from .. import _timingfrom ..utils import TrackEvalException
class _BaseDataset(ABC): @abstractmethod def __init__(self): self.tracker_list = None self.seq_list = None self.class_list = None self.output_fol = None self.output_sub_fol = None self.should_classes_combine = True self.use_super_categories = False
# Functions to implement:
@staticmethod @abstractmethod def get_default_dataset_config(): ...
@abstractmethod def _load_raw_file(self, tracker, seq, is_gt): ...
@_timing.time @abstractmethod def get_preprocessed_seq_data(self, raw_data, cls): ...
@abstractmethod def _calculate_similarities(self, gt_dets_t, tracker_dets_t): ...
# Helper functions for all datasets:
@classmethod def get_class_name(cls): return cls.__name__
def get_name(self): return self.get_class_name()
def get_output_fol(self, tracker): return os.path.join(self.output_fol, tracker, self.output_sub_fol)
def get_display_name(self, tracker): """Can be overwritten if the trackers name (in files) is different to how it should be displayed. By default this method just returns the trackers name as is. """ return tracker
def get_eval_info(self): """Return info about the dataset needed for the Evaluator""" return self.tracker_list, self.seq_list, self.class_list
@_timing.time def get_raw_seq_data(self, tracker, seq): """Loads raw data (tracker and ground-truth) for a single tracker on a single sequence. Raw data includes all of the information needed for both preprocessing and evaluation, for all classes. A later function (get_processed_seq_data) will perform such preprocessing and extract relevant information for the evaluation of each class.
This returns a dict which contains the fields: [num_timesteps]: integer [gt_ids, tracker_ids, gt_classes, tracker_classes, tracker_confidences]: list (for each timestep) of 1D NDArrays (for each det). [gt_dets, tracker_dets, gt_crowd_ignore_regions]: list (for each timestep) of lists of detections. [similarity_scores]: list (for each timestep) of 2D NDArrays. [gt_extras]: dict (for each extra) of lists (for each timestep) of 1D NDArrays (for each det).
gt_extras contains dataset specific information used for preprocessing such as occlusion and truncation levels.
Note that similarities are extracted as part of the dataset and not the metric, because almost all metrics are independent of the exact method of calculating the similarity. However datasets are not (e.g. segmentation masks vs 2D boxes vs 3D boxes). We calculate the similarity before preprocessing because often both preprocessing and evaluation require it and we don't wish to calculate this twice. We calculate similarity between all gt and tracker classes (not just each class individually) to allow for calculation of metrics such as class confusion matrices. Typically the impact of this on performance is low. """ # Load raw data. raw_gt_data = self._load_raw_file(tracker, seq, is_gt=True) raw_tracker_data = self._load_raw_file(tracker, seq, is_gt=False) raw_data = {**raw_tracker_data, **raw_gt_data} # Merges dictionaries
# Calculate similarities for each timestep. similarity_scores = [] for t, (gt_dets_t, tracker_dets_t) in enumerate( zip(raw_data["gt_dets"], raw_data["tracker_dets"]) ): ious = self._calculate_similarities(gt_dets_t, tracker_dets_t) similarity_scores.append(ious) raw_data["similarity_scores"] = similarity_scores return raw_data
@staticmethod def _load_simple_text_file( file, time_col=0, id_col=None, remove_negative_ids=False, valid_filter=None, crowd_ignore_filter=None, convert_filter=None, is_zipped=False, zip_file=None, force_delimiters=None, ): """Function that loads data which is in a commonly used text file format. Assumes each det is given by one row of a text file. There is no limit to the number or meaning of each column, however one column needs to give the timestep of each det (time_col) which is default col 0.
The file dialect (deliminator, num cols, etc) is determined automatically. This function automatically separates dets by timestep, and is much faster than alternatives such as np.loadtext or pandas.
If remove_negative_ids is True and id_col is not None, dets with negative values in id_col are excluded. These are not excluded from ignore data.
valid_filter can be used to only include certain classes. It is a dict with ints as keys, and lists as values, such that a row is included if "row[key].lower() is in value" for all key/value pairs in the dict. If None, all classes are included.
crowd_ignore_filter can be used to read crowd_ignore regions separately. It has the same format as valid filter.
convert_filter can be used to convert value read to another format. This is used most commonly to convert classes given as string to a class id. This is a dict such that the key is the column to convert, and the value is another dict giving the mapping.
Optionally, input files could be a zip of multiple text files for storage efficiency.
Returns read_data and ignore_data. Each is a dict (with keys as timesteps as strings) of lists (over dets) of lists (over column values). Note that all data is returned as strings, and must be converted to float/int later if needed. Note that timesteps will not be present in the returned dict keys if there are no dets for them """
if remove_negative_ids and id_col is None: raise TrackEvalException( "remove_negative_ids is True, but id_col is not given." ) if crowd_ignore_filter is None: crowd_ignore_filter = {} if convert_filter is None: convert_filter = {} try: if is_zipped: # Either open file directly or within a zip. if zip_file is None: raise TrackEvalException( "is_zipped set to True, but no zip_file is given." ) archive = zipfile.ZipFile(os.path.join(zip_file), "r") fp = io.TextIOWrapper(archive.open(file, "r")) else: fp = open(file) read_data = {} crowd_ignore_data = {} fp.seek(0, os.SEEK_END) # check if file is empty if fp.tell(): fp.seek(0) dialect = csv.Sniffer().sniff( fp.readline(), delimiters=force_delimiters ) # Auto determine structure. dialect.skipinitialspace = ( True # Deal with extra spaces between columns ) fp.seek(0) reader = csv.reader(fp, dialect) for row in reader: try: # Deal with extra trailing spaces at the end of rows if row[-1] in "": row = row[:-1] timestep = str(int(float(row[time_col]))) # Read ignore regions separately. is_ignored = False for ignore_key, ignore_value in crowd_ignore_filter.items(): if row[ignore_key].lower() in ignore_value: # Convert values in one column (e.g. string to id) for ( convert_key, convert_value, ) in convert_filter.items(): row[convert_key] = convert_value[ row[convert_key].lower() ] # Save data separated by timestep. if timestep in crowd_ignore_data.keys(): crowd_ignore_data[timestep].append(row) else: crowd_ignore_data[timestep] = [row] is_ignored = True if ( is_ignored ): # if det is an ignore region, it cannot be a normal det. continue # Exclude some dets if not valid. if valid_filter is not None: for key, value in valid_filter.items(): if row[key].lower() not in value: continue if remove_negative_ids: if int(float(row[id_col])) < 0: continue # Convert values in one column (e.g. string to id) for convert_key, convert_value in convert_filter.items(): row[convert_key] = convert_value[row[convert_key].lower()] # Save data separated by timestep. if timestep in read_data.keys(): read_data[timestep].append(row) else: read_data[timestep] = [row] except Exception: exc_str_init = ( "In file %s the following line cannot be read correctly: \n" % os.path.basename(file) ) exc_str = " ".join([exc_str_init] + row) raise TrackEvalException(exc_str) fp.close() except Exception: print("Error loading file: %s, printing traceback." % file) traceback.print_exc() raise TrackEvalException( "File %s cannot be read because it is either not present or invalidly formatted" % os.path.basename(file) ) return read_data, crowd_ignore_data
@staticmethod def _calculate_mask_ious(masks1, masks2, is_encoded=False, do_ioa=False): """Calculates the IOU (intersection over union) between two arrays of segmentation masks. If is_encoded a run length encoding with pycocotools is assumed as input format, otherwise an input of numpy arrays of the shape (num_masks, height, width) is assumed and the encoding is performed. If do_ioa (intersection over area) , then calculates the intersection over the area of masks1 - this is commonly used to determine if detections are within crowd ignore region. :param masks1: first set of masks (numpy array of shape (num_masks, height, width) if not encoded, else pycocotools rle encoded format) :param masks2: second set of masks (numpy array of shape (num_masks, height, width) if not encoded, else pycocotools rle encoded format) :param is_encoded: whether the input is in pycocotools rle encoded format :param do_ioa: whether to perform IoA computation :return: the IoU/IoA scores """
# Only loaded when run to reduce minimum requirements from pycocotools import mask as mask_utils
# use pycocotools for run length encoding of masks if not is_encoded: masks1 = mask_utils.encode( np.array(np.transpose(masks1, (1, 2, 0)), order="F") ) masks2 = mask_utils.encode( np.array(np.transpose(masks2, (1, 2, 0)), order="F") )
# use pycocotools for iou computation of rle encoded masks ious = mask_utils.iou(masks1, masks2, [do_ioa] * len(masks2)) if len(masks1) == 0 or len(masks2) == 0: ious = np.asarray(ious).reshape(len(masks1), len(masks2)) assert (ious >= 0 - np.finfo("float").eps).all() assert (ious <= 1 + np.finfo("float").eps).all()
return ious
@staticmethod def _calculate_box_ious(bboxes1, bboxes2, box_format="xywh", do_ioa=False): """Calculates the IOU (intersection over union) between two arrays of boxes. Allows variable box formats ('xywh' and 'x0y0x1y1'). If do_ioa (intersection over area) , then calculates the intersection over the area of boxes1 - this is commonly used to determine if detections are within crowd ignore region. """ if box_format in "xywh": # layout: (x0, y0, w, h) bboxes1 = deepcopy(bboxes1) bboxes2 = deepcopy(bboxes2)
bboxes1[:, 2] = bboxes1[:, 0] + bboxes1[:, 2] bboxes1[:, 3] = bboxes1[:, 1] + bboxes1[:, 3] bboxes2[:, 2] = bboxes2[:, 0] + bboxes2[:, 2] bboxes2[:, 3] = bboxes2[:, 1] + bboxes2[:, 3] elif box_format not in "x0y0x1y1": raise (TrackEvalException("box_format %s is not implemented" % box_format))
# layout: (x0, y0, x1, y1) min_ = np.minimum(bboxes1[:, np.newaxis, :], bboxes2[np.newaxis, :, :]) max_ = np.maximum(bboxes1[:, np.newaxis, :], bboxes2[np.newaxis, :, :]) intersection = np.maximum(min_[..., 2] - max_[..., 0], 0) * np.maximum( min_[..., 3] - max_[..., 1], 0 ) area1 = (bboxes1[..., 2] - bboxes1[..., 0]) * ( bboxes1[..., 3] - bboxes1[..., 1] )
if do_ioa: ioas = np.zeros_like(intersection) valid_mask = area1 > 0 + np.finfo("float").eps ioas[valid_mask, :] = ( intersection[valid_mask, :] / area1[valid_mask][:, np.newaxis] )
return ioas else: area2 = (bboxes2[..., 2] - bboxes2[..., 0]) * ( bboxes2[..., 3] - bboxes2[..., 1] ) union = area1[:, np.newaxis] + area2[np.newaxis, :] - intersection intersection[area1 <= 0 + np.finfo("float").eps, :] = 0 intersection[:, area2 <= 0 + np.finfo("float").eps] = 0 intersection[union <= 0 + np.finfo("float").eps] = 0 union[union <= 0 + np.finfo("float").eps] = 1 ious = intersection / union return ious
@staticmethod def _calculate_euclidean_similarity(dets1, dets2, zero_distance=2.0): """Calculates the euclidean distance between two sets of detections, and then converts this into a similarity measure with values between 0 and 1 using the following formula: sim = max(0, 1 - dist/zero_distance). The default zero_distance of 2.0, corresponds to the default used in MOT15_3D, such that a 0.5 similarity threshold corresponds to a 1m distance threshold for TPs. """ dist = np.linalg.norm(dets1[:, np.newaxis] - dets2[np.newaxis, :], axis=2) sim = np.maximum(0, 1 - dist / zero_distance) return sim
@staticmethod def _check_unique_ids(data, after_preproc=False): """Check the requirement that the tracker_ids and gt_ids are unique per timestep""" gt_ids = data["gt_ids"] tracker_ids = data["tracker_ids"] for t, (gt_ids_t, tracker_ids_t) in enumerate(zip(gt_ids, tracker_ids)): if len(tracker_ids_t) > 0: unique_ids, counts = np.unique(tracker_ids_t, return_counts=True) if np.max(counts) != 1: duplicate_ids = unique_ids[counts > 1] exc_str_init = ( "Tracker predicts the same ID more than once in a single timestep " "(seq: %s, frame: %i, ids:" % (data["seq"], t + 1) ) exc_str = ( " ".join([exc_str_init] + [str(d) for d in duplicate_ids]) + ")" ) if after_preproc: exc_str_init += ( "\n Note that this error occurred after preprocessing (but not before), " "so ids may not be as in file, and something seems wrong with preproc." ) raise TrackEvalException(exc_str) if len(gt_ids_t) > 0: unique_ids, counts = np.unique(gt_ids_t, return_counts=True) if np.max(counts) != 1: duplicate_ids = unique_ids[counts > 1] exc_str_init = ( "Ground-truth has the same ID more than once in a single timestep " "(seq: %s, frame: %i, ids:" % (data["seq"], t + 1) ) exc_str = ( " ".join([exc_str_init] + [str(d) for d in duplicate_ids]) + ")" ) if after_preproc: exc_str_init += ( "\n Note that this error occurred after preprocessing (but not before), " "so ids may not be as in file, and something seems wrong with preproc." ) raise TrackEvalException(exc_str)1234# flake8: noqa
from .count import Countfrom .hota import HOTA123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648# Copyright (c) Meta Platforms, Inc. and affiliates. All Rights Reserved
"""Postprocessors class to transform MDETR output according to the downstream task"""
import dataclassesimport loggingfrom collections import defaultdictfrom typing import Dict, List, Optional
import numpy as npimport torchfrom sam3.model import box_opsfrom sam3.model.data_misc import BatchedInferenceMetadata, interpolatefrom sam3.train.masks_ops import rle_encode, robust_rle_encodefrom torch import nn
class PostProcessNullOp(nn.Module): def __init__(self, **kwargs): super(PostProcessNullOp).__init__() pass
def forward(self, input): pass
def process_results(self, **kwargs): return kwargs["find_stages"]
class PostProcessImage(nn.Module): """This module converts the model's output into the format expected by the coco api"""
def __init__( self, max_dets_per_img: int, iou_type="bbox", to_cpu: bool = True, use_original_ids: bool = False, use_original_sizes_box: bool = False, use_original_sizes_mask: bool = False, convert_mask_to_rle: bool = False, always_interpolate_masks_on_gpu: bool = True, use_presence: bool = True, detection_threshold: float = -1.0, ) -> None: super().__init__() self.max_dets_per_img = max_dets_per_img self.iou_type = iou_type self.to_cpu = to_cpu self.convert_mask_to_rle = convert_mask_to_rle self.always_interpolate_masks_on_gpu = always_interpolate_masks_on_gpu
self.use_presence = use_presence self.detection_threshold = detection_threshold self.use_original_ids = use_original_ids self.use_original_sizes_box = use_original_sizes_box self.use_original_sizes_mask = use_original_sizes_mask
@torch.no_grad() def forward( self, outputs, target_sizes_boxes, target_sizes_masks, forced_labels=None, consistent=False, ret_tensordict: bool = False, # This is experimental ): """Perform the computation Parameters: outputs: raw outputs of the model target_sizes_boxes: tensor of dimension [batch_size x 2] containing the size of each images of the batch For evaluation, this must be the original image size (before any data augmentation) For visualization, this should be the image size after data augment, but before padding target_sizes_masks: same but used to resize masks forced_labels: tensor of dimension [batch_size] containing the label to force for each image of the batch This is useful when evaluating the model using standard metrics (eg on COCO, LVIS). In that case, we query the model with every possible class label, so we when we pass the predictions to the evaluator, we want to make sure that the predicted "class" matches the one that was queried. consistent: whether all target sizes are equal ret_tensordict: Experimental argument. If true, return a tensordict.TensorDict instead of a list of dictionaries for easier manipulation. """ if ret_tensordict: assert ( consistent is True ), "We don't support returning TensorDict if the outputs have different shapes" # NOTE: It's possible but we don't support it. assert self.detection_threshold <= 0.0, "TODO: implement?" try: from tensordict import TensorDict except ImportError: logging.info( "tensordict is not installed. Install by running `pip install tensordict --no-deps`. Falling back by setting `ret_tensordict=False`" ) ret_tensordict = False
out_bbox = outputs["pred_boxes"] if "pred_boxes" in outputs else None out_logits = outputs["pred_logits"] pred_masks = outputs["pred_masks"] if self.iou_type == "segm" else None out_probs = out_logits.sigmoid() if self.use_presence: presence_score = outputs["presence_logit_dec"].sigmoid().unsqueeze(1) out_probs = out_probs * presence_score
assert target_sizes_boxes.shape[1] == 2 assert target_sizes_masks.shape[1] == 2 batch_size = target_sizes_boxes.shape[0]
boxes, scores, labels, keep = self._process_boxes_and_labels( target_sizes_boxes, forced_labels, out_bbox, out_probs ) assert boxes is None or len(boxes) == batch_size out_masks = self._process_masks( target_sizes_masks, pred_masks, consistent=consistent, keep=keep ) del pred_masks
if boxes is None: assert out_masks is not None assert not ret_tensordict, "We don't support returning TensorDict if the output does not contain boxes" B = len(out_masks) boxes = [None] * B scores = [None] * B labels = [None] * B
results = { "scores": scores, "labels": labels, "boxes": boxes, } if out_masks is not None: if self.convert_mask_to_rle: results.update(masks_rle=out_masks) else: results.update(masks=out_masks)
if ret_tensordict: results = TensorDict(results).auto_batch_size_() if self.to_cpu: results = results.cpu() else: # Convert a dictonary of lists/tensors to list of dictionaries results = [ dict(zip(results.keys(), res_tuple)) for res_tuple in zip(*results.values()) ]
return results
def _process_masks(self, target_sizes, pred_masks, consistent=True, keep=None): if pred_masks is None: return None if self.always_interpolate_masks_on_gpu: gpu_device = target_sizes.device assert gpu_device.type == "cuda" pred_masks = pred_masks.to(device=gpu_device) if consistent: assert keep is None, "TODO: implement?" # All masks should have the same shape, expected when processing a batch of size 1 target_size = target_sizes.unique(dim=0) assert target_size.size(0) == 1, "Expecting all target sizes to be equal" out_masks = ( interpolate( pred_masks, target_size.squeeze().tolist(), mode="bilinear", align_corners=False, ).sigmoid() > 0.5 ) if self.convert_mask_to_rle: raise RuntimeError("TODO: implement?") if self.to_cpu: out_masks = out_masks.cpu() else: out_masks = [[]] * len(pred_masks)
assert keep is None or len(keep) == len(pred_masks) for i, mask in enumerate(pred_masks): h, w = target_sizes[i] if keep is not None: mask = mask[keep[i]] # Uses the gpu version fist, moves masks to cpu if it fails""" try: interpolated = ( interpolate( mask.unsqueeze(1), (h, w), mode="bilinear", align_corners=False, ).sigmoid() > 0.5 ) except Exception as e: logging.info("Issue found, reverting to CPU mode!") mask_device = mask.device mask = mask.cpu() interpolated = ( interpolate( mask.unsqueeze(1), (h, w), mode="bilinear", align_corners=False, ).sigmoid() > 0.5 ) interpolated = interpolated.to(mask_device)
if self.convert_mask_to_rle: out_masks[i] = robust_rle_encode(interpolated.squeeze(1)) else: out_masks[i] = interpolated if self.to_cpu: out_masks[i] = out_masks[i].cpu()
return out_masks
def _process_boxes_and_labels( self, target_sizes, forced_labels, out_bbox, out_probs ): if out_bbox is None: return None, None, None, None assert len(out_probs) == len(target_sizes) if self.to_cpu: out_probs = out_probs.cpu() scores, labels = out_probs.max(-1) if forced_labels is None: labels = torch.ones_like(labels) else: labels = forced_labels[:, None].expand_as(labels)
# convert to [x0, y0, x1, y1] format boxes = box_ops.box_cxcywh_to_xyxy(out_bbox)
img_h, img_w = target_sizes.unbind(1) scale_fct = torch.stack([img_w, img_h, img_w, img_h], dim=1) boxes = boxes * scale_fct[:, None, :]
if self.to_cpu: boxes = boxes.cpu()
keep = None if self.detection_threshold > 0: # Filter out the boxes with scores below the detection threshold keep = scores > self.detection_threshold assert len(keep) == len(boxes) == len(scores) == len(labels)
boxes = [b[k.to(b.device)] for b, k in zip(boxes, keep)] scores = [s[k.to(s.device)] for s, k in zip(scores, keep)] labels = [l[k.to(l.device)] for l, k in zip(labels, keep)]
return boxes, scores, labels, keep
def process_results( self, find_stages, find_metadatas: List[BatchedInferenceMetadata], **kwargs ): if find_stages.loss_stages is not None: find_metadatas = [find_metadatas[i] for i in find_stages.loss_stages] assert len(find_stages) == len(find_metadatas) results = {} for outputs, meta in zip(find_stages, find_metadatas): img_size_for_boxes = ( meta.original_size if self.use_original_sizes_box else torch.ones_like(meta.original_size) ) img_size_for_masks = ( meta.original_size if self.use_original_sizes_mask else torch.ones_like(meta.original_size) ) detection_results = self( outputs, img_size_for_boxes, img_size_for_masks, forced_labels=( meta.original_category_id if self.use_original_ids else None ), ) ids = ( meta.original_image_id if self.use_original_ids else meta.coco_image_id ) assert len(detection_results) == len(ids) for img_id, result in zip(ids, detection_results): if img_id.item() not in results: results[img_id.item()] = result else: assert set(results[img_id.item()].keys()) == set(result.keys()) for k in result.keys(): if isinstance(result[k], torch.Tensor): results[img_id.item()][k] = torch.cat( [results[img_id.item()][k], result[k]], dim=0 ) elif isinstance(result[k], list): results[img_id.item()][k] += result[k] else: raise NotImplementedError( f"Unexpected type {type(result[k])} in result." ) # Prune the results to the max number of detections per image. for img_id, result in results.items(): if ( self.max_dets_per_img > 0 and len(result["scores"]) > self.max_dets_per_img ): _, topk_indexes = torch.topk( result["scores"], self.max_dets_per_img, dim=0 ) if self.to_cpu: topk_indexes = topk_indexes.cpu() for k in result.keys(): if isinstance(results[img_id][k], list): results[img_id][k] = [ results[img_id][k][i] for i in topk_indexes.tolist() ] else: results[img_id][k] = results[img_id][k].to(topk_indexes.device)[ topk_indexes ]
return results
class PostProcessAPIVideo(PostProcessImage): """This module converts the video model's output into the format expected by the YT-VIS api"""
def __init__( self, *args, to_cpu: bool = True, convert_mask_to_rle: bool = False, always_interpolate_masks_on_gpu: bool = True, prob_thresh: float = 0.5, use_presence: bool = False, **kwargs, ): super().__init__( *args, # Here we always set `convert_mask_to_rle=False` in the base `PostProcessAPI` class # (so that its `_process_masks` won't return a list of RLEs). If we want to return # RLEs for video masklets, we handle it in this `PostProcessAPIVideo` class instead. convert_mask_to_rle=False, # Here we always set `to_cpu=False` in the base `PostProcessAPI` class (so that # the interpolated masks won't be automatically moved back to CPU). We will handle # it in this `PostProcessAPIVideo` class instead. always_interpolate_masks_on_gpu=always_interpolate_masks_on_gpu, use_presence=use_presence, **kwargs, ) # Expected keys in the output dict to postprocess self.EXPECTED_KEYS = [ "pred_logits", "pred_boxes", "pred_masks", ] # Whether to post-process video masklets (under packed representation) into RLE format self.convert_mask_to_rle_for_video = convert_mask_to_rle self.to_cpu_for_video = to_cpu self.prob_thresh = prob_thresh
def process_results( self, find_stages, find_metadatas: List[BatchedInferenceMetadata], **kwargs ): """ Tracking Postprocessor for SAM 3 video model. This function takes in the output of the SAM 3 video model and processes it to extract all the tracklet predictions. Args: find_stages: A list of tensors representing the output of the SAM 3 video model. find_metadatas: A list of BatchedInferenceMetadata objects containing metadata about each frame. **kwargs: Additional keyword arguments. Returns: A dictionary of predcitions with video_id as key. """
# Import tensordict here to avoid global dependency. try: from tensordict import TensorDict except ImportError as e: logging.error( "tensordict is not installed, please install by running `pip install tensordict --no-deps`" ) raise e # Notes and assumptions: # 1- This postprocessor assumes results only for a single video. # 2- There are N stage outputs corresponding to N video frames # 3- Each stage outputs contains PxQ preds, where P is number of prompts and Q is number of object queries. The output should also contain the tracking object ids corresponding to each object query. # 4- The tracking object id has a default value of -1, indicating that the object query is not tracking any object in the frame, and hence its predictions can be ingored for a given frame. # 5- Some objects may be tracked in a subset of frames only. So, we first extract the predictions in a packed representation (for efficient postprocessing -- specially memory) # and then we convert the packed representation into a padded one, where we zero pad boxes/masks for objects that are not tracked in some frames. # 6- We refer to objects by an object id, which is a tuple (prompt_idx, obj_id)
assert len(find_stages) > 0, "There is nothing to postprocess?" PROMPT_AXIS, OBJ_QUERY_AXIS = (0, 1) NO_OBJ_ID = -1 # Maps object ID -> [indices in packed tensor] tracked_objects_packed_idx = defaultdict(list) # Maps object ID -> [indices in padded tensor (abs frame index)] tracked_objects_frame_idx = defaultdict(list) total_num_preds = 0 # This will hold the packed representation of predictions. vid_preds_packed: List[TensorDict] = [] vid_masklets_rle_packed: List[Optional[Dict]] = [] video_id = -1 # We assume single video postprocessing, this ID should be unique in the datapoint.
for frame_idx, (frame_outs, meta) in enumerate( zip(find_stages, find_metadatas) ): # only store keys we need to extract the results frame_outs_td = TensorDict( {k: frame_outs[k] for k in self.EXPECTED_KEYS} ).auto_batch_size_() # Shape is [P,Q,...] meta_td = TensorDict( dataclasses.asdict(meta) ).auto_batch_size_() # Shape is [P,...] unique_vid_id = meta.original_image_id.unique() assert unique_vid_id.size(0) == 1 if video_id == -1: video_id = unique_vid_id.item() else: assert ( video_id == unique_vid_id.item() ), "We can only postprocess one video per datapoint" # keeping track of which objects appear in the current frame obj_ids_per_frame = frame_outs["pred_object_ids"] assert obj_ids_per_frame.size(-1) == frame_outs["pred_logits"].size(-2) if self.prob_thresh is not None: # only keep the predictions on this frame with probability above the threshold # (remove those predictions during the keep-alive period of a tracking query, # where its "pred_object_ids" is still the tracked object ID rather than -1) pred_probs = frame_outs["pred_logits"].sigmoid().squeeze(-1) obj_ids_per_frame = torch.where( pred_probs >= self.prob_thresh, obj_ids_per_frame, NO_OBJ_ID ) tracked_obj_ids_idx = torch.where(obj_ids_per_frame != NO_OBJ_ID) # Object id is a tuple of (prompt_idx, obj_id). This is because the model can assign same obj_id for two different prompts. tracked_obj_ids = [ (p_id.item(), obj_ids_per_frame[p_id, q_id].item()) for p_id, q_id in zip( tracked_obj_ids_idx[PROMPT_AXIS], tracked_obj_ids_idx[OBJ_QUERY_AXIS], ) ] if len(tracked_obj_ids) == 0: continue # For each object, we keep track of the packed and padded (frame index) indices for oid in tracked_obj_ids: tracked_objects_packed_idx[oid].append(total_num_preds) tracked_objects_frame_idx[oid].append(frame_idx) total_num_preds += 1
# Since we have P*Q masks per frame, mask interpolation is the GPU memory bottleneck or time bottleneck in case of cpu processing. # Instead, we first extract results only for tracked objects, reducing the number of masks to K = sum_i(tracked_objs_per_ith_prompt), hopefully <<< P*Q tracked_objs_outs_td = frame_outs_td[ tracked_obj_ids_idx ] # [P,Q,...] --> [K,...] meta_td = meta_td[tracked_obj_ids_idx[PROMPT_AXIS].cpu()] if self.always_interpolate_masks_on_gpu: gpu_device = meta_td["original_size"].device assert gpu_device.type == "cuda" tracked_objs_outs_td = tracked_objs_outs_td.to(device=gpu_device) frame_results_td = self( tracked_objs_outs_td.unsqueeze(1), ( meta_td["original_size"] if self.use_original_sizes else torch.ones_like(meta_td["original_size"]) ), forced_labels=( meta_td["original_category_id"] if self.use_original_ids else None ), consistent=True, ret_tensordict=True, ).squeeze(1) del tracked_objs_outs_td
# Optionally, remove "masks" from output tensor dict and directly encode them # to RLE format under packed representations if self.convert_mask_to_rle_for_video: interpolated_binary_masks = frame_results_td.pop("masks") rle_list = rle_encode(interpolated_binary_masks, return_areas=True) vid_masklets_rle_packed.extend(rle_list) # Optionally, move output TensorDict to CPU (do this after RLE encoding step above) if self.to_cpu_for_video: frame_results_td = frame_results_td.cpu() vid_preds_packed.append(frame_results_td)
if len(vid_preds_packed) == 0: logging.debug(f"Video {video_id} has no predictions") return {video_id: []}
vid_preds_packed = torch.cat(vid_preds_packed, dim=0) ############### Construct a padded representation of the predictions ############### num_preds = len(tracked_objects_packed_idx) num_frames = len(find_stages) # We zero pad any missing prediction # NOTE: here, we also have padded tensors for "scores" and "labels", but we overwrite them later. padded_frames_results = TensorDict( { k: torch.zeros( num_preds, num_frames, *v.shape[1:], device=v.device, dtype=v.dtype ) for k, v in vid_preds_packed.items() }, batch_size=[ num_preds, num_frames, ], ) padded_frames_results["scores"][...] = -1e8 # a very low score for empty object # Track scores and labels of each pred tracklet, only for frames where the model was able to track that object tracklet_scores = [] tracklet_labels = [] # Optionally, fill the list of RLEs for masklets # note: only frames with actual predicted masks (in packed format) will be # filled with RLEs; the rest will remains None in results["masks_rle"] if self.convert_mask_to_rle_for_video: vid_masklets_rle_padded = [[None] * num_frames for _ in range(num_preds)] for o_idx, oid in enumerate(tracked_objects_packed_idx): oid2packed_idx = tracked_objects_packed_idx[oid] oid2padded_idx = tracked_objects_frame_idx[oid] obj_packed_results = vid_preds_packed[oid2packed_idx] padded_frames_results[o_idx][oid2padded_idx] = obj_packed_results if self.convert_mask_to_rle_for_video: for packed_idx, padded_idx in zip(oid2packed_idx, oid2padded_idx): vid_masklets_rle_padded[o_idx][padded_idx] = ( vid_masklets_rle_packed[packed_idx] ) # NOTE: We need a single confidence score per tracklet for the mAP metric. # We use the average confidence score across time. (How does this impact AP?) tracklet_scores.append(obj_packed_results["scores"].mean()) # We also need to have a unique category Id per tracklet. # This is not a problem for phrase AP, however, for mAP we do majority voting across time. tracklet_labels.append(obj_packed_results["labels"].mode()[0])
results = padded_frames_results.to_dict() results["scores"] = torch.stack(tracklet_scores, dim=0) results["labels"] = torch.stack(tracklet_labels, dim=0) if self.convert_mask_to_rle_for_video: results["masks_rle"] = vid_masklets_rle_padded # we keep the frame-level scores since it's needed by some evaluation scripts results["per_frame_scores"] = padded_frames_results["scores"]
return {video_id: results}
class PostProcessTracking(PostProcessImage): """This module converts the model's output into the format expected by the coco api"""
def __init__( self, max_dets_per_img: int, iou_type="bbox", force_single_mask: bool = False, **kwargs, ) -> None: super().__init__(max_dets_per_img=max_dets_per_img, iou_type=iou_type, **kwargs) self.force_single_mask = force_single_mask
def process_results( self, find_stages, find_metadatas: BatchedInferenceMetadata, **kwargs ): assert len(find_stages) == len(find_metadatas) results = {} for outputs, meta in zip(find_stages, find_metadatas): if self.force_single_mask: scores, labels = outputs["pred_logits"].max(-1) m = [] for i in range(len(outputs["pred_masks"])): score, idx = scores[i].max(0) m.append(outputs["pred_masks"][i][idx]) outputs["pred_masks"] = torch.stack(m, 0).unsqueeze(1) detection_results = self(outputs, meta.original_size, consistent=False) assert len(detection_results) == len(meta.coco_image_id) results.update( { (media_id.item(), object_id.item(), frame_index.item()): result for media_id, object_id, frame_index, result in zip( meta.original_image_id, meta.object_id, meta.frame_index, detection_results, ) } ) return results
class PostProcessCounting(nn.Module): """This module converts the model's output to be evaluated for counting tasks"""
def __init__( self, use_original_ids: bool = False, threshold: float = 0.5, use_presence: bool = False, ) -> None: """ Args: use_original_ids: whether to use the original image ids or the coco ids threshold: threshold for counting (values above this are counted) """ super().__init__() self.use_original_ids = use_original_ids self.threshold = threshold self.use_presence = use_presence
def forward(self, outputs, target_sizes): """Perform the computation Parameters: outputs: raw outputs of the model target_sizes: tensor of dimension [batch_size x 2] containing the size of each images of the batch """ # Extract scores from model outputs and apply sigmoid scores = torch.sigmoid(outputs["pred_logits"]).squeeze(-1) # [B, N] if self.use_presence: presence_score = outputs["presence_logit_dec"].sigmoid() if presence_score.ndim == 1: presence_score = presence_score.unsqueeze(1) # [B, 1] scores = scores * presence_score # [B, N]
# Calculate counts by summing values above threshold counts = (scores > self.threshold).float().sum(dim=1)
assert len(counts) == len(target_sizes) results = [] for count in counts: results.append({"count": count.item()})
return results
@torch.no_grad() def process_results( self, find_stages, find_metadatas: List[BatchedInferenceMetadata], **kwargs ): assert len(find_stages) == len(find_metadatas) results = {} for outputs, meta in zip(find_stages, find_metadatas): detection_results = self( outputs, meta.original_size, ) ids = ( meta.original_image_id if self.use_original_ids else meta.coco_image_id ) assert len(detection_results) == len(ids) for img_id, result in zip(ids, detection_results): results[img_id.item()] = result
return results123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782783784785786787788789790791792793794795796797798799800801802803804805806807808809810811812813814815816817818819820821822823824825826827828829830831832833834835836837838# Copyright (c) Meta Platforms, Inc. and affiliates. All Rights Reservedimport jsonimport osimport tempfilefrom collections import defaultdictfrom typing import Dict, Optional, Sequence, Tuple
import numpy as npimport pycocotools.maskfrom sam3.eval.cgf1_eval import CGF1_METRICSfrom sam3.eval.conversion_util import ( convert_ytbvis_to_cocovid_gt, convert_ytbvis_to_cocovid_pred,)from sam3.eval.hota_eval_toolkit.run_ytvis_eval import run_ytvis_evalfrom sam3.eval.teta_eval_toolkit import config, Evaluator, metricsfrom sam3.eval.teta_eval_toolkit.datasets import COCO, TAOfrom sam3.eval.ytvis_coco_wrapper import YTVISfrom sam3.eval.ytvis_eval import VideoDemoF1Eval, YTVISevalfrom sam3.train.nms_helper import process_frame_level_nms, process_track_level_nms
def _get_metric_index(metric_name: str, iou_threshold: Optional[float] = None) -> int: """ Find the index of a metric in CGF1_METRICS by name and IoU threshold.
Args: metric_name: Name of the metric (e.g., "cgF1", "precision", "recall") iou_threshold: IoU threshold (None for average over 0.5:0.95, or specific value like 0.5, 0.75)
Returns: Index of the metric in CGF1_METRICS
Raises: ValueError: If metric not found """ for idx, metric in enumerate(CGF1_METRICS): if metric.name == metric_name and metric.iou_threshold == iou_threshold: return idx raise ValueError( f"Metric '{metric_name}' with IoU threshold {iou_threshold} not found in CGF1_METRICS" )
class BasePredFileEvaluator: """A base class for evaluating a prediction file."""
pass
class YTVISPredFileEvaluator(BasePredFileEvaluator): """Evaluate class mAP for YT-VIS prediction files."""
def __init__( self, gt_ann_file: str, dataset_name: str = "video", iou_types: Optional[Sequence[str]] = None, ): self.gt_ann_file = gt_ann_file self.dataset_name = dataset_name self.iou_types = list(iou_types) if iou_types is not None else ["bbox", "segm"] assert all(iou_type in ["bbox", "segm"] for iou_type in self.iou_types)
def evaluate(self, pred_file: str) -> Dict[str, float]: # use our internal video evaluation toolkit for YT-VIS pred file # (i.e. the same one we're using for video phrase AP) results = {} use_cats = True # YT-VIS mAP evaluation uses categories ytvisGT = YTVIS(self.gt_ann_file, ignore_gt_cats=not use_cats) # the original YT-VIS GT annotations have uncompressed RLEs ("counts" is an integer list) # rather than compressed RLEs ("counts" is a string), so we first convert them here. if "segm" in self.iou_types: for ann in ytvisGT.dataset["annotations"]: ann["segmentations"] = [ _compress_rle(rle) for rle in ann["segmentations"] ]
with open(pred_file) as f: dt = json.load(f) # Our prediction file saves "video_id" and absolute (unnormalized) boxes. # Note that we should use the official (original) YT-VIS annotations (i.e. the one # saved via "scripts/datasets/training/ytvis_split.py", instead of the one saved # via "scripts/api_db_to_ytvis_json.py") in this evaluator, which contain absolute # boxes coordinates in its GT annotations. for d in dt: d["image_id"] = d["video_id"] ytvisDT = ytvisGT.loadRes(dt)
for iou_type in self.iou_types: ytvisEval = YTVISeval(ytvisGT, ytvisDT, iou_type)
# set the area ranges for small, medium, and large objects (using # absolute pixel areas) as in the official YT-VIS evaluation toolkit: # https://github.com/achalddave/ytvosapi/blob/eca601117c9f86bad084cb91f1d918e9ab665a75/PythonAPI/ytvostools/ytvoseval.py#L538 ytvisEval.params.areaRng = [ [0**2, 1e5**2], [0**2, 128**2], [128**2, 256**2], [256**2, 1e5**2], ] ytvisEval.params.areaRngLbl = ["all", "small", "medium", "large"] ytvisEval.params.useCats = use_cats
ytvisEval.evaluate() ytvisEval.accumulate() ytvisEval.summarize() result_key = f"{self.dataset_name}_{'mask' if iou_type == 'segm' else 'bbox'}_mAP_50_95" results[result_key] = ytvisEval.stats[0]
# video-NP level results not supported for `YTVISPredFileEvaluator` yet video_np_level_results = {} return results, video_np_level_results
class VideoPhraseApEvaluator(BasePredFileEvaluator): """Evaluate Video Phrase AP with YT-VIS format prediction and GT files."""
def __init__( self, gt_ann_file: str, dataset_name: str = "video", iou_types: Optional[Sequence[str]] = None, ): self.gt_ann_file = gt_ann_file self.dataset_name = dataset_name self.iou_types = list(iou_types) if iou_types is not None else ["bbox", "segm"] assert all(iou_type in ["bbox", "segm"] for iou_type in self.iou_types)
def evaluate(self, pred_file: str) -> Dict[str, float]: with open(self.gt_ann_file) as f: gt = json.load(f) with open(pred_file) as f: dt = json.load(f) # For phrase AP and demo F1 evaluation, we need to remap each pair of (video_id, category_id) to # a new unique video_id, so that we don't mix detections from different categories under `useCat=False` gt, dt = remap_video_category_pairs_to_unique_video_ids(gt, dt) if "segm" in self.iou_types: for ann in gt["annotations"]: ann["segmentations"] = [ _compress_rle(rle) for rle in ann["segmentations"] ] for d in dt: d["image_id"] = d["video_id"]
results = {} use_cats = False # Phrase AP evaluation does not use categories ytvisGT = YTVIS(annotation_file=None, ignore_gt_cats=not use_cats) ytvisGT.dataset = gt ytvisGT.createIndex() ytvisDT = ytvisGT.loadRes(dt)
for iou_type in self.iou_types: phraseApEval = YTVISeval(ytvisGT, ytvisDT, iou_type)
# set the area ranges for small, medium, and large objects (using # absolute pixel areas) as in the official YT-VIS evaluation toolkit: # https://github.com/achalddave/ytvosapi/blob/eca601117c9f86bad084cb91f1d918e9ab665a75/PythonAPI/ytvostools/ytvoseval.py#L538 phraseApEval.params.areaRng = [ [0**2, 1e5**2], [0**2, 128**2], [128**2, 256**2], [256**2, 1e5**2], ] phraseApEval.params.areaRngLbl = ["all", "small", "medium", "large"] phraseApEval.params.useCats = use_cats
phraseApEval.evaluate() phraseApEval.accumulate() phraseApEval.summarize() result_prefix = f"{self.dataset_name}" result_prefix += f"_{'mask' if iou_type == 'segm' else 'bbox'}_phrase_ap" # fetch Phrase AP results from the corresponding indices in `phraseApEval.stats` # (see `_summarizeDets` in https://github.com/cocodataset/cocoapi/blob/master/PythonAPI/pycocotools/cocoeval.py) results[result_prefix + "_50_95"] = phraseApEval.stats[0] # IoU=0.5:0.95 results[result_prefix + "_50"] = phraseApEval.stats[1] # IoU=0.5 results[result_prefix + "_75"] = phraseApEval.stats[2] # IoU=0.75
# video-NP level results not supported for `VideoPhraseApEvaluator` yet video_np_level_results = {} return results, video_np_level_results
class VideoCGF1Evaluator(BasePredFileEvaluator): """Evaluate Video Demo F1 with YT-VIS format prediction and GT files."""
def __init__( self, gt_ann_file: str, dataset_name: str = "video", prob_thresh: float = 0.5, iou_types: Optional[Sequence[str]] = None, ): self.gt_ann_file = gt_ann_file self.dataset_name = dataset_name self.prob_thresh = prob_thresh self.iou_types = list(iou_types) if iou_types is not None else ["bbox", "segm"] assert all(iou_type in ["bbox", "segm"] for iou_type in self.iou_types)
def evaluate(self, pred_file: str) -> Dict[str, float]: with open(self.gt_ann_file) as f: gt = json.load(f) with open(pred_file) as f: dt = json.load(f) # compute IL_MCC and CG-F1 can only be computed if we have "video_np_pairs" keys in the GT JSON compute_ilmcc_and_cgf1 = "video_np_pairs" in gt if not compute_ilmcc_and_cgf1: print( f"Warning: IL_MCC and CG-F1 are not computed for {pred_file=} as it does not have 'video_np_pairs' keys in the GT JSON" ) # For phrase AP and demo F1 evaluation, we need to remap each pair of (video_id, category_id) to # a new unique video_id, so that we don't mix detections from different categories under `useCat=False` gt, dt = remap_video_category_pairs_to_unique_video_ids( gt, dt, add_negative_np_pairs=compute_ilmcc_and_cgf1 ) if "segm" in self.iou_types: for ann in gt["annotations"]: ann["segmentations"] = [ _compress_rle(rle) for rle in ann["segmentations"] ] for d in dt: d["image_id"] = d["video_id"]
results = {} use_cats = False # Demo F1 evaluation does not use categories ytvisGT = YTVIS(annotation_file=None, ignore_gt_cats=not use_cats) ytvisGT.dataset = gt ytvisGT.createIndex() ytvisDT = ytvisGT.loadRes(dt)
video_np_level_results = {} for iou_type in self.iou_types: demoF1Eval = VideoDemoF1Eval(ytvisGT, ytvisDT, iou_type, self.prob_thresh)
demoF1Eval.params.useCats = use_cats demoF1Eval.params.areaRng = [[0**2, 1e5**2]] demoF1Eval.params.areaRngLbl = ["all"] demoF1Eval.params.maxDets = [100000]
demoF1Eval.evaluate() demoF1Eval.accumulate() demoF1Eval.summarize() result_prefix = f"{self.dataset_name}" result_prefix += f"_{'mask' if iou_type == 'segm' else 'bbox'}_demo"
stats = demoF1Eval.stats
if compute_ilmcc_and_cgf1: # Average IoU threshold (0.5:0.95) cgf1_micro_avg_idx = _get_metric_index("cgF1", None) positive_micro_f1_avg_idx = _get_metric_index("positive_micro_F1", None) ilmcc_avg_idx = _get_metric_index("IL_MCC", None) results[result_prefix + "_cgf1_micro_50_95"] = stats[cgf1_micro_avg_idx] results[result_prefix + "_ilmcc_50_95"] = stats[ilmcc_avg_idx] results[result_prefix + "_positive_micro_f1_50_95"] = stats[ positive_micro_f1_avg_idx ]
# IoU = 0.5 cgf1_micro_50_idx = _get_metric_index("cgF1", 0.5) positive_micro_f1_50_idx = _get_metric_index("positive_micro_F1", 0.5) results[result_prefix + "_cgf1_micro_50"] = stats[cgf1_micro_50_idx] results[result_prefix + "_ilmcc_50"] = float( np.array(stats[cgf1_micro_50_idx]) / np.array(stats[positive_micro_f1_50_idx]) ) results[result_prefix + "_positive_micro_f1_50"] = stats[ positive_micro_f1_50_idx ]
# IoU = 0.75 cgf1_micro_75_idx = _get_metric_index("cgF1", 0.75) positive_micro_f1_75_idx = _get_metric_index("positive_micro_F1", 0.75) results[result_prefix + "_cgf1_micro_75"] = stats[cgf1_micro_75_idx] results[result_prefix + "_ilmcc_75"] = float( np.array(stats[cgf1_micro_75_idx]) / np.array(stats[positive_micro_f1_75_idx]) ) results[result_prefix + "_positive_micro_f1_75"] = stats[ positive_micro_f1_75_idx ]
self.extract_video_np_level_results(demoF1Eval, video_np_level_results)
return results, video_np_level_results
def extract_video_np_level_results(self, demoF1Eval, video_np_level_results): """Aggregate statistics for video-level metrics.""" num_iou_thrs = len(demoF1Eval.params.iouThrs) iou_50_index = int(np.where(demoF1Eval.params.iouThrs == 0.5)[0]) iou_75_index = int(np.where(demoF1Eval.params.iouThrs == 0.75)[0])
result_prefix = "mask" if demoF1Eval.params.iouType == "segm" else "bbox"
assert len(demoF1Eval.evalImgs) == len(demoF1Eval.cocoGt.dataset["images"]) for i, video in enumerate(demoF1Eval.cocoGt.dataset["images"]): # the original video id and category id before remapping video_id = video["orig_video_id"] category_id = video["orig_category_id"] eval_img_dict = demoF1Eval.evalImgs[i]
TPs = eval_img_dict.get("TPs", np.zeros(num_iou_thrs, dtype=np.int64)) FPs = eval_img_dict.get("FPs", np.zeros(num_iou_thrs, dtype=np.int64)) FNs = eval_img_dict.get("FNs", np.zeros(num_iou_thrs, dtype=np.int64)) assert len(TPs) == len(FPs) == len(FNs) == num_iou_thrs # F1 = 2*TP / (2*TP + FP + FN), and we set F1 to 1.0 if denominator is 0 denominator = 2 * TPs + FPs + FNs F1s = np.where(denominator > 0, 2 * TPs / np.maximum(denominator, 1), 1.0) local_results = { f"{result_prefix}_TP_50_95": float(TPs.mean()), f"{result_prefix}_FP_50_95": float(FPs.mean()), f"{result_prefix}_FN_50_95": float(FNs.mean()), f"{result_prefix}_F1_50_95": float(F1s.mean()), f"{result_prefix}_TP_50": float(TPs[iou_50_index]), f"{result_prefix}_FP_50": float(FPs[iou_50_index]), f"{result_prefix}_FN_50": float(FNs[iou_50_index]), f"{result_prefix}_F1_50": float(F1s[iou_50_index]), f"{result_prefix}_TP_75": float(TPs[iou_75_index]), f"{result_prefix}_FP_75": float(FPs[iou_75_index]), f"{result_prefix}_FN_75": float(FNs[iou_75_index]), f"{result_prefix}_F1_75": float(F1s[iou_75_index]), } if (video_id, category_id) not in video_np_level_results: video_np_level_results[(video_id, category_id)] = {} video_np_level_results[(video_id, category_id)].update(local_results)
class VideoTetaEvaluator(BasePredFileEvaluator): """Evaluate TETA metric using YouTubeVIS format prediction and GT files."""
def __init__( self, gt_ann_file: str, dataset_name: str = "video", tracker_name: str = "Sam3", nms_threshold: float = 0.5, nms_strategy: str = "none", # "track", "frame", or "none" prob_thresh: float = 0.5, is_exhaustive: bool = False, use_mask: bool = False, num_parallel_cores: int = 8, ): self.gt_ann_file = gt_ann_file self.dataset_name = dataset_name self.tracker_name = tracker_name self.nms_threshold = nms_threshold self.nms_strategy = nms_strategy.lower() # Convert to lowercase for consistency self.prob_thresh = prob_thresh self.metric_prefix = "TETA" self.is_exhaustive = is_exhaustive self.use_mask = use_mask self.num_parallel_cores = num_parallel_cores
# Verify NMS strategy is valid valid_strategies = ["track", "frame", "none"] print("current nms_strategy:", self.nms_strategy) if self.nms_strategy not in valid_strategies: raise ValueError( f"Invalid NMS strategy: {self.nms_strategy}. Must be one of {valid_strategies}" )
print(f"Initialized VideoTetaEvaluator with NMS strategy: {self.nms_strategy}") print(f"Probability threshold set to: {self.prob_thresh}") print(f"Dataset exhaustivity set to: {self.is_exhaustive}") print(f"Tracker name set to: {self.tracker_name}") print(f"Dataset name set to: {self.dataset_name}") print(f"Use mask set to: {self.use_mask}")
def process_predictions(self, pred_file: str, tmp_dir: str) -> str: """Process predictions with selected NMS strategy""" with open(pred_file, "r") as f: raw_preds = json.load(f) print(f"Processing predictions with {self.nms_strategy} NMS strategy")
# Filter by score threshold if self.prob_thresh > 0: raw_preds = [d for d in raw_preds if d["score"] >= self.prob_thresh] print( f"Filtered to {len(raw_preds)} predictions with score >= {self.prob_thresh}" ) # Group predictions by video_id video_groups = defaultdict(list) for pred in raw_preds: video_groups[pred["video_id"]].append(pred) # Process based on NMS strategy if self.nms_strategy == "track": process_track_level_nms(video_groups, nms_threshold=self.nms_threshold) elif self.nms_strategy == "frame": process_frame_level_nms(video_groups, nms_threshold=self.nms_threshold) elif self.nms_strategy == "none": print("Skipping NMS processing as strategy is set to 'none'") # No processing needed for "none" strategy # Save processed predictions processed_preds = [ track for tracks in video_groups.values() for track in tracks ] processed_path = os.path.join(tmp_dir, "processed_preds.json") with open(processed_path, "w") as f: json.dump(processed_preds, f)
print(f"Saved processed predictions to {processed_path}") return processed_path
def evaluate(self, pred_file: str) -> Tuple[Dict[str, float], Dict]: """Main evaluation method"""
print(f"Evaluating TETA Metric with {self.nms_strategy.upper()} NMS strategy") with tempfile.TemporaryDirectory() as tmp_dir: # Process predictions first processed_pred_file = self.process_predictions(pred_file, tmp_dir)
# Convert GT to COCO-vid format gt_dir = os.path.join(tmp_dir, "gt") os.makedirs(gt_dir, exist_ok=True) gt_coco_path = os.path.join(gt_dir, "annotations.json") convert_ytbvis_to_cocovid_gt(self.gt_ann_file, gt_coco_path)
# Convert processed predictions to COCO-vid format pred_dir = os.path.join(tmp_dir, "predictions") tracker_dir = os.path.join(pred_dir, self.tracker_name) os.makedirs(tracker_dir, exist_ok=True) pred_coco_path = os.path.join(tracker_dir, "track_results_cocofmt.json") convert_ytbvis_to_cocovid_pred( youtubevis_pred_path=processed_pred_file, converted_dataset_path=gt_coco_path, output_path=pred_coco_path, ) # Configure TETA evaluator default_eval_config = config.get_default_eval_config() default_eval_config["PRINT_ONLY_COMBINED"] = True default_eval_config["DISPLAY_LESS_PROGRESS"] = True default_eval_config["OUTPUT_TEMP_RAW_DATA"] = True default_eval_config["NUM_PARALLEL_CORES"] = self.num_parallel_cores default_dataset_config = config.get_default_dataset_config() default_dataset_config["TRACKERS_TO_EVAL"] = [self.tracker_name] default_dataset_config["GT_FOLDER"] = gt_dir default_dataset_config["OUTPUT_FOLDER"] = pred_dir default_dataset_config["TRACKER_SUB_FOLDER"] = tracker_dir default_dataset_config["USE_MASK"] = self.use_mask
evaluator = Evaluator(default_eval_config) if self.is_exhaustive: dataset_list = [COCO(default_dataset_config)] dataset_parsing_key = "COCO" else: dataset_list = [TAO(default_dataset_config)] dataset_parsing_key = "TAO"
# Run evaluation eval_results, _ = evaluator.evaluate( dataset_list, [metrics.TETA(exhaustive=self.is_exhaustive)] )
# Extract and format results results = { f"{self.dataset_name}_{'mask' if self.use_mask else 'bbox'}_teta": float( eval_results[dataset_parsing_key]["TETA"][0] ), f"{self.dataset_name}_{'mask' if self.use_mask else 'bbox'}_loc_a": float( eval_results[dataset_parsing_key]["TETA"][1] ), f"{self.dataset_name}_{'mask' if self.use_mask else 'bbox'}_assoc_a": float( eval_results[dataset_parsing_key]["TETA"][2] ), f"{self.dataset_name}_{'mask' if self.use_mask else 'bbox'}_cls_a": float( eval_results[dataset_parsing_key]["TETA"][3] ), f"{self.dataset_name}_{'mask' if self.use_mask else 'bbox'}_loc_re": float( eval_results[dataset_parsing_key]["TETA"][4] ), f"{self.dataset_name}_{'mask' if self.use_mask else 'bbox'}_loc_pr": float( eval_results[dataset_parsing_key]["TETA"][5] ), f"{self.dataset_name}_{'mask' if self.use_mask else 'bbox'}_assoc_re": float( eval_results[dataset_parsing_key]["TETA"][6] ), f"{self.dataset_name}_{'mask' if self.use_mask else 'bbox'}_assoc_pr": float( eval_results[dataset_parsing_key]["TETA"][7] ), f"{self.dataset_name}_{'mask' if self.use_mask else 'bbox'}_cls_re": float( eval_results[dataset_parsing_key]["TETA"][8] ), f"{self.dataset_name}_{'mask' if self.use_mask else 'bbox'}_cls_pr": float( eval_results[dataset_parsing_key]["TETA"][9] ), }
# video-NP level results not supported for `VideoTetaEvaluator` yet video_np_level_results = {} return results, video_np_level_results
class VideoPhraseHotaEvaluator(BasePredFileEvaluator): """Evaluate Video Phrase HOTA with YT-VIS format prediction and GT files."""
def __init__( self, gt_ann_file: str, dataset_name: str = "video", prob_thresh: float = 0.5, iou_types: Optional[Sequence[str]] = None, compute_video_mot_hota: bool = False, ): self.gt_ann_file = gt_ann_file self.dataset_name = dataset_name self.prob_thresh = prob_thresh self.metric_prefix = "phrase" # the list of metrics to collect from the HOTA evaluation results self.metric_to_collect = [ "HOTA", "DetA", "AssA", "DetRe", "DetPr", "AssRe", "AssPr", "LocA", "OWTA", ] self.iou_types = list(iou_types) if iou_types is not None else ["bbox", "segm"] assert all(iou_type in ["bbox", "segm"] for iou_type in self.iou_types)
# If True, compute video MOT HOTA, aggregating predictions/GT from all categories. self.compute_video_mot_hota = compute_video_mot_hota
def evaluate(self, pred_file: str) -> Dict[str, float]: # use the YT-VIS evaluation toolkit in TrackEval
with open(self.gt_ann_file) as f: gt = json.load(f) with open(pred_file) as f: dt = json.load(f) # keep only predictions with score above the probability threshold dt = [d for d in dt if d["score"] > self.prob_thresh] for d in dt: assert len(d["areas"]) == len(d["bboxes"]) assert len(d["areas"]) == len(d["segmentations"]) # remove empty boxes (otherwise they will count as false positives for during # per-frame detection accuracy in HOTA evaluation) for t in range(len(d["bboxes"])): bbox = d["bboxes"][t] if d["areas"][t] == 0 or bbox is None or all(x == 0 for x in bbox): d["segmentations"][t] = None d["bboxes"][t] = None d["areas"][t] = None # check that box occurence and mask occurence are consistent for bbox, mask, area in zip(d["bboxes"], d["segmentations"], d["areas"]): assert (area is None) == (bbox is None) assert (area is None) == (mask is None) # set all scores to 1.0 for HOTA evaluation (just like Demo F1, the exact score # value is not used in HOTA metrics; it will be treated as a detection prediction # as long as its score is above the threshold) d["score"] = 1.0
# remap the GT and DT annotations for phrase HOTA evaluation gt = _fill_in_ann_height_width(gt) if not self.compute_video_mot_hota: # remap the GT and DT annotations for phrase HOTA evaluation gt, dt = self._remap_gt_dt(gt, dt) else: # Compute video-level MOT HOTA # Apply track-level NMS video_groups = defaultdict(list) for pred in dt: video_groups[pred["video_id"]].append(pred) process_track_level_nms(video_groups, nms_threshold=0.5) dt = [track for tracks in video_groups.values() for track in tracks]
# Remap GT track ids for class-agnostic HOTA gt, dt = remap_gt_dt_class_agnostic(gt, dt)
# run the HOTA evaluation using TrackEval on the remapped (video_id, category_id) pairs out_dict = {} video_np_level_results = {} for iou_type in self.iou_types: output_res, _ = run_ytvis_eval( args=[ "--METRICS", "HOTA", "--IOU_TYPE", iou_type, "--DATASET_NAME", self.dataset_name, "--USE_PARALLEL", "True", "--NUM_PARALLEL_CORES", "8", "--PLOT_CURVES", "False", "--LOG_ON_ERROR", "None", "--PRINT_ONLY_COMBINED", "True", "--OUTPUT_SUMMARY", "False", "--OUTPUT_DETAILED", "False", "--TIME_PROGRESS", "False", "--PRINT_CONFIG", "False", ], gt_json=gt, dt_json=dt, ) self.extract_video_np_level_results( iou_type=iou_type, remapped_gt=gt, raw_results=output_res[self.dataset_name]["tracker"], video_np_level_results=video_np_level_results, )
def _summarize_results(output_res, iou_type, field, suffix): eval_res = output_res[self.dataset_name]["tracker"][field] result_prefix = f"{self.dataset_name}_{'mask' if iou_type == 'segm' else 'bbox'}_{suffix}" for metric_name in self.metric_to_collect: eval_res_hota = eval_res["cls_comb_cls_av"]["HOTA"] result_key = f"{result_prefix}_{self.metric_prefix}_{metric_name}" result_value = float(np.mean(eval_res_hota[metric_name])) out_dict[result_key] = result_value
_summarize_results(output_res, iou_type, "COMBINED_SEQ", "all") if "COMBINED_SEQ_CHALLENGING" in output_res[self.dataset_name]["tracker"]: _summarize_results( output_res, iou_type, "COMBINED_SEQ_CHALLENGING", "challenging" )
# video-NP level results not supported for `VideoPhraseHotaEvaluator` yet return out_dict, video_np_level_results
def _remap_gt_dt(self, gt, dt): # For phrase HOTA evaluation, we need to remap each pair of (video_id, category_id) to # a new unique video_id, so that we don't mix detections from different categories gt, dt = remap_video_category_pairs_to_unique_video_ids(gt, dt) # We further map all the categories to category_id=1 in HOTA evaluation toolkit # for phrase HOTA (similar to "useCat=False" for video phrase AP) remapped_category_id = 1 gt["categories"] = [ { "supercategory": "object", "id": remapped_category_id, "name": "_REMAPPED_FOR_PHRASE_METRICS_", } ] for ann in gt["annotations"]: ann["category_id"] = remapped_category_id for d in dt: d["category_id"] = remapped_category_id # To be compatible with the TrackEval YT-VIS evaluation toolkit, we need to give # unique filenames to each remapped video, so we add remapped video_id as prefix. for video in gt["videos"]: new_video_id = video["id"] video["file_names"] = [ f"remapped_vid_{new_video_id:012d}/{name}" for name in video["file_names"] ] return gt, dt
def extract_video_np_level_results( self, iou_type, remapped_gt, raw_results, video_np_level_results ): """Aggregate statistics for video-level metrics.""" result_prefix = "mask" if iou_type == "segm" else "bbox" for video in remapped_gt["videos"]: # the original video id and category id before remapping video_id = video["orig_video_id"] category_id = video["orig_category_id"] video_key = f"remapped_vid_{video['id']:012d}" results = raw_results[video_key]["_REMAPPED_FOR_PHRASE_METRICS_"]["HOTA"]
local_results = {} for metric_name in self.metric_to_collect: result_key = f"{result_prefix}_{metric_name}" local_results[result_key] = float(results[metric_name].mean()) if (video_id, category_id) not in video_np_level_results: video_np_level_results[(video_id, category_id)] = {} video_np_level_results[(video_id, category_id)].update(local_results)
class VideoClassBasedHotaEvaluator(VideoPhraseHotaEvaluator): def __init__( self, gt_ann_file: str, dataset_name: str = "video", prob_thresh: float = 0.5, ): super().__init__(gt_ann_file, dataset_name, prob_thresh) self.metric_prefix = "class"
def _remap_gt_dt(self, gt, dt): return gt, dt # no remapping needed for class-based HOTA evaluation
def extract_video_np_level_results(self, *args, **kwargs): pass # no video-NP level results for class-based HOTA evaluation
def _compress_rle(rle): """Convert RLEs from uncompressed (integer list) to compressed (string) format.""" if rle is None: return None if isinstance(rle["counts"], list): rle = pycocotools.mask.frPyObjects(rle, rle["size"][0], rle["size"][1]) rle["counts"] = rle["counts"].decode() return rle
def remap_video_category_pairs_to_unique_video_ids( gt_json, dt_json, add_negative_np_pairs=False): """ Remap each pair of (video_id, category_id) to a new unique video_id. This is useful for phrase AP and demo F1 evaluation on videos, where we have `useCat=False` and rely on separating different NPs (from the same video) into different new video ids, so that we don't mix detections from different categories in computeIoU under `useCat=False`.
This is consistent with how do we phrase AP and demo F1 evaluation on images, where we use a remapped unique coco_image_id for each image-NP pair (based in its query["id"] in CustomCocoDetectionAPI.load_queries in modulated_detection_api.py) """ # collect the unique video_id-category_id pairs video_id_to_video = {v["id"]: v for v in gt_json["videos"]} video_id_category_id_pairs = set() for pred in dt_json: video_id_category_id_pairs.add((pred["video_id"], pred["category_id"])) for ann in gt_json["annotations"]: video_id_category_id_pairs.add((ann["video_id"], ann["category_id"]))
# assign the video_id-category_id pairs to unique video ids video_id_category_id_pairs = sorted(video_id_category_id_pairs) video_id_category_id_to_new_video_id = { pair: (i + 1) for i, pair in enumerate(video_id_category_id_pairs) } # also map the negative NP pairs -- this is needed for IL_MCC and CG-F1 evaluation if add_negative_np_pairs: for vnp in gt_json["video_np_pairs"]: pair = (vnp["video_id"], vnp["category_id"]) if pair not in video_id_category_id_to_new_video_id: video_id_category_id_to_new_video_id[pair] = ( len(video_id_category_id_to_new_video_id) + 1 )
# map the "video_id" in predictions for pred in dt_json: pred["video_id"] = video_id_category_id_to_new_video_id[ (pred["video_id"], pred["category_id"]) ] # map the "video_id" in gt_json["annotations"] for ann in gt_json["annotations"]: ann["video_id"] = video_id_category_id_to_new_video_id[ (ann["video_id"], ann["category_id"]) ] # map and duplicate gt_json["videos"] new_videos = [] for ( video_id, category_id, ), new_video_id in video_id_category_id_to_new_video_id.items(): video = video_id_to_video[video_id].copy() video["id"] = new_video_id # preserve the original video_id and category_id of each remapped video entry, # so that we can associate sample-level eval metrics with the original video-NP pairs video["orig_video_id"] = video_id video["orig_category_id"] = category_id new_videos.append(video) gt_json["videos"] = new_videos
return gt_json, dt_json
def remap_gt_dt_class_agnostic(gt, dt): """ For class-agnostic HOTA, merge all GT tracks for each video (across NPs), ensure unique track_ids, and set all category_id to 1. Also, add orig_video_id and orig_category_id for compatibility. """ # 1. Remap all GT track_ids to be unique per video gt_anns_by_video = defaultdict(list) for ann in gt["annotations"]: gt_anns_by_video[ann["video_id"]].append(ann)
# Ensure unique track ids across tracks of all videos next_tid = 1 for _, anns in gt_anns_by_video.items(): # Map old track_ids to new unique ones old_to_new_tid = {} for ann in anns: old_tid = ann["id"] if old_tid not in old_to_new_tid: old_to_new_tid[old_tid] = next_tid next_tid += 1 ann["id"] = old_to_new_tid[old_tid] # Set category_id to 1 for class-agnostic ann["category_id"] = 1
# Set all GT categories to a single category gt["categories"] = [ { "supercategory": "object", "id": 1, "name": "_REMAPPED_FOR_PHRASE_METRICS_", } ]
# Add orig_video_id and orig_category_id to each video for compatibility anns_by_video = defaultdict(list) for ann in gt["annotations"]: anns_by_video[ann["video_id"]].append(ann) for video in gt["videos"]: video["orig_video_id"] = video["id"] # Use the first annotation's original category_id if available, else None orig_cat = ( anns_by_video[video["id"]][0]["category_id"] if anns_by_video[video["id"]] else None ) video["orig_category_id"] = orig_cat video["file_names"] = [ f"remapped_vid_{video['id']:012d}/{name}" for name in video["file_names"] ]
# Set all DT category_id to 1 for d in dt: d["category_id"] = 1 return gt, dt
def _fill_in_ann_height_width(gt_json): """Fill in missing height/width in GT annotations from its video info.""" video_id_to_video = {v["id"]: v for v in gt_json["videos"]} for ann in gt_json["annotations"]: if "height" not in ann or "width" not in ann: video = video_id_to_video[ann["video_id"]] if "height" not in ann: ann["height"] = video["height"] if "width" not in ann: ann["width"] = video["width"]
return gt_json123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869# fmt: off# flake8: noqa
import inspectfrom functools import wrapsfrom time import perf_counter
DO_TIMING = FalseDISPLAY_LESS_PROGRESS = Falsetimer_dict = {}counter = 0
def time(f): @wraps(f) def wrap(*args, **kw): if DO_TIMING: # Run function with timing ts = perf_counter() result = f(*args, **kw) te = perf_counter() tt = te - ts
# Get function name arg_names = inspect.getfullargspec(f)[0] if arg_names[0] == "self" and DISPLAY_LESS_PROGRESS: return result elif arg_names[0] == "self": method_name = type(args[0]).__name__ + "." + f.__name__ else: method_name = f.__name__
# Record accumulative time in each function for analysis if method_name in timer_dict.keys(): timer_dict[method_name] += tt else: timer_dict[method_name] = tt
# If code is finished, display timing summary if method_name == "Evaluator.evaluate": print("") print("Timing analysis:") for key, value in timer_dict.items(): print("%-70s %2.4f sec" % (key, value)) else: # Get function argument values for printing special arguments of interest arg_titles = ["tracker", "seq", "cls"] arg_vals = [] for i, a in enumerate(arg_names): if a in arg_titles: arg_vals.append(args[i]) arg_text = "(" + ", ".join(arg_vals) + ")"
# Display methods and functions with different indentation. if arg_names[0] == "self": print("%-74s %2.4f sec" % (" " * 4 + method_name + arg_text, tt)) elif arg_names[0] == "test": pass else: global counter counter += 1 print("%i %-70s %2.4f sec" % (counter, method_name + arg_text, tt))
return result else: # If config["TIME_PROGRESS"] is false, or config["USE_PARALLEL"] is true, run functions normally without timing. return f(*args, **kw)
return wrap123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659# fmt: off# flake8: noqa
"""TAO Dataset."""import copyimport itertoolsimport jsonimport osfrom collections import defaultdict
import numpy as np
from .. import _timingfrom ..config import get_default_dataset_config, init_configfrom ..utils import TrackEvalExceptionfrom ._base_dataset import _BaseDataset
class TAO(_BaseDataset): """Dataset class for TAO tracking"""
def __init__(self, config=None): """Initialize dataset, checking that all required files are present.""" super().__init__() # Fill non-given config values with defaults self.config = init_config(config, get_default_dataset_config(), self.get_name()) self.gt_fol = self.config["GT_FOLDER"] self.tracker_fol = self.config["TRACKERS_FOLDER"] self.should_classes_combine = True self.use_super_categories = False self.use_mask = self.config["USE_MASK"]
self.tracker_sub_fol = self.config["TRACKER_SUB_FOLDER"] self.output_fol = self.config["OUTPUT_FOLDER"] if self.output_fol is None: self.output_fol = self.tracker_fol self.output_sub_fol = self.config["OUTPUT_SUB_FOLDER"]
if self.gt_fol.endswith(".json"): self.gt_data = json.load(open(self.gt_fol, "r")) else: gt_dir_files = [ file for file in os.listdir(self.gt_fol) if file.endswith(".json") ] if len(gt_dir_files) != 1: raise TrackEvalException( f"{self.gt_fol} does not contain exactly one json file." )
with open(os.path.join(self.gt_fol, gt_dir_files[0])) as f: self.gt_data = json.load(f)
# merge categories marked with a merged tag in TAO dataset self._merge_categories(self.gt_data["annotations"] + self.gt_data["tracks"])
# get sequences to eval and sequence information self.seq_list = [ vid["name"].replace("/", "-") for vid in self.gt_data["videos"] ] self.seq_name2seqid = { vid["name"].replace("/", "-"): vid["id"] for vid in self.gt_data["videos"] } # compute mappings from videos to annotation data self.video2gt_track, self.video2gt_image = self._compute_vid_mappings( self.gt_data["annotations"] ) # compute sequence lengths self.seq_lengths = {vid["id"]: 0 for vid in self.gt_data["videos"]} for img in self.gt_data["images"]: self.seq_lengths[img["video_id"]] += 1 self.seq2images2timestep = self._compute_image_to_timestep_mappings() self.seq2cls = { vid["id"]: { "pos_cat_ids": list( {track["category_id"] for track in self.video2gt_track[vid["id"]]} ), "neg_cat_ids": vid["neg_category_ids"], "not_exh_labeled_cat_ids": vid["not_exhaustive_category_ids"], } for vid in self.gt_data["videos"] }
# Get classes to eval considered_vid_ids = [self.seq_name2seqid[vid] for vid in self.seq_list] seen_cats = set( [ cat_id for vid_id in considered_vid_ids for cat_id in self.seq2cls[vid_id]["pos_cat_ids"] ] ) # only classes with ground truth are evaluated in TAO self.valid_classes = [ cls["name"] for cls in self.gt_data["categories"] if cls["id"] in seen_cats ] cls_name2clsid_map = { cls["name"]: cls["id"] for cls in self.gt_data["categories"] }
if self.config["CLASSES_TO_EVAL"]: self.class_list = [ cls.lower() if cls.lower() in self.valid_classes else None for cls in self.config["CLASSES_TO_EVAL"] ] if not all(self.class_list): valid_cls = ", ".join(self.valid_classes) raise TrackEvalException( "Attempted to evaluate an invalid class. Only classes " f"{valid_cls} are valid (classes present in ground truth" " data)." ) else: self.class_list = [cls for cls in self.valid_classes] self.cls_name2clsid = { k: v for k, v in cls_name2clsid_map.items() if k in self.class_list } self.clsid2cls_name = { v: k for k, v in cls_name2clsid_map.items() if k in self.class_list } # get trackers to eval print(self.config["TRACKERS_TO_EVAL"] ) if self.config["TRACKERS_TO_EVAL"] is None: self.tracker_list = os.listdir(self.tracker_fol) else: self.tracker_list = self.config["TRACKERS_TO_EVAL"]
if self.config["TRACKER_DISPLAY_NAMES"] is None: self.tracker_to_disp = dict(zip(self.tracker_list, self.tracker_list)) elif (self.config["TRACKERS_TO_EVAL"] is not None) and ( len(self.config["TK_DISPLAY_NAMES"]) == len(self.tracker_list) ): self.tracker_to_disp = dict( zip(self.tracker_list, self.config["TK_DISPLAY_NAMES"]) ) else: raise TrackEvalException( "List of tracker files and tracker display names do not match." )
self.tracker_data = {tracker: dict() for tracker in self.tracker_list}
for tracker in self.tracker_list: if self.tracker_sub_fol.endswith(".json"): with open(os.path.join(self.tracker_sub_fol)) as f: curr_data = json.load(f) else: tr_dir = os.path.join(self.tracker_fol, tracker, self.tracker_sub_fol) tr_dir_files = [ file for file in os.listdir(tr_dir) if file.endswith(".json") ] if len(tr_dir_files) != 1: raise TrackEvalException( f"{tr_dir} does not contain exactly one json file." ) with open(os.path.join(tr_dir, tr_dir_files[0])) as f: curr_data = json.load(f)
# limit detections if MAX_DETECTIONS > 0 if self.config["MAX_DETECTIONS"]: curr_data = self._limit_dets_per_image(curr_data)
# fill missing video ids self._fill_video_ids_inplace(curr_data)
# make track ids unique over whole evaluation set self._make_tk_ids_unique(curr_data)
# merge categories marked with a merged tag in TAO dataset self._merge_categories(curr_data)
# get tracker sequence information curr_vids2tracks, curr_vids2images = self._compute_vid_mappings(curr_data) self.tracker_data[tracker]["vids_to_tracks"] = curr_vids2tracks self.tracker_data[tracker]["vids_to_images"] = curr_vids2images
def get_display_name(self, tracker): return self.tracker_to_disp[tracker]
def _load_raw_file(self, tracker, seq, is_gt): """Load a file (gt or tracker) in the TAO format
If is_gt, this returns a dict which contains the fields: [gt_ids, gt_classes]: list (for each timestep) of 1D NDArrays (for each det). [gt_dets]: list (for each timestep) of lists of detections.
if not is_gt, this returns a dict which contains the fields: [tk_ids, tk_classes, tk_confidences]: list (for each timestep) of 1D NDArrays (for each det). [tk_dets]: list (for each timestep) of lists of detections. """ seq_id = self.seq_name2seqid[seq] # file location if is_gt: imgs = self.video2gt_image[seq_id] else: imgs = self.tracker_data[tracker]["vids_to_images"][seq_id]
# convert data to required format num_timesteps = self.seq_lengths[seq_id] img_to_timestep = self.seq2images2timestep[seq_id] data_keys = ["ids", "classes", "dets"] if not is_gt: data_keys += ["tk_confidences"] raw_data = {key: [None] * num_timesteps for key in data_keys} for img in imgs: # some tracker data contains images without any ground truth info, # these are ignored if img["id"] not in img_to_timestep: continue t = img_to_timestep[img["id"]] anns = img["annotations"] if self.use_mask: # When using mask, extract segmentation data raw_data["dets"][t] = [ann.get("segmentation") for ann in anns] else: # When using bbox, extract bbox data raw_data["dets"][t] = np.atleast_2d([ann["bbox"] for ann in anns]).astype( float ) raw_data["ids"][t] = np.atleast_1d( [ann["track_id"] for ann in anns] ).astype(int) raw_data["classes"][t] = np.atleast_1d( [ann["category_id"] for ann in anns] ).astype(int) if not is_gt: raw_data["tk_confidences"][t] = np.atleast_1d( [ann["score"] for ann in anns] ).astype(float)
for t, d in enumerate(raw_data["dets"]): if d is None: raw_data["dets"][t] = np.empty((0, 4)).astype(float) raw_data["ids"][t] = np.empty(0).astype(int) raw_data["classes"][t] = np.empty(0).astype(int) if not is_gt: raw_data["tk_confidences"][t] = np.empty(0)
if is_gt: key_map = {"ids": "gt_ids", "classes": "gt_classes", "dets": "gt_dets"} else: key_map = {"ids": "tk_ids", "classes": "tk_classes", "dets": "tk_dets"} for k, v in key_map.items(): raw_data[v] = raw_data.pop(k)
raw_data["num_timesteps"] = num_timesteps raw_data["neg_cat_ids"] = self.seq2cls[seq_id]["neg_cat_ids"] raw_data["not_exh_labeled_cls"] = self.seq2cls[seq_id][ "not_exh_labeled_cat_ids" ] raw_data["seq"] = seq return raw_data
def get_preprocessed_seq_data_thr(self, raw_data, cls, assignment=None): """Preprocess data for a single sequence for a single class.
Inputs: raw_data: dict containing the data for the sequence already read in by get_raw_seq_data(). cls: class to be evaluated. Outputs: gt_ids: list (for each timestep) of ids of GT tracks tk_ids: list (for each timestep) of ids of predicted tracks (all for TP matching (Det + AssocA)) tk_overlap_ids: list (for each timestep) of ids of predicted tracks that overlap with GTs tk_neg_ids: list (for each timestep) of ids of predicted tracks that with the class id on the negative list for the current sequence. tk_exh_ids: list (for each timestep) of ids of predicted tracks that do not overlap with existing GTs but have the class id on the exhaustive annotated class list for the current sequence. tk_dets: list (for each timestep) of lists of detections that corresponding to the tk_ids tk_classes: list (for each timestep) of lists of classes that corresponding to the tk_ids tk_confidences: list (for each timestep) of lists of classes that corresponding to the tk_ids sim_scores: similarity score between gt_ids and tk_ids. """ if cls != "all": cls_id = self.cls_name2clsid[cls]
data_keys = [ "gt_ids", "tk_ids", "gt_id_map", "tk_id_map", "gt_dets", "gt_classes", "gt_class_name", "tk_overlap_classes", "tk_overlap_ids", "tk_neg_ids", "tk_exh_ids", "tk_class_eval_tk_ids", "tk_dets", "tk_classes", "tk_confidences", "sim_scores", ] data = {key: [None] * raw_data["num_timesteps"] for key in data_keys} unique_gt_ids = [] unique_tk_ids = [] num_gt_dets = 0 num_tk_cls_dets = 0 num_tk_overlap_dets = 0 overlap_ious_thr = 0.5 loc_and_asso_tk_ids = []
for t in range(raw_data["num_timesteps"]): # only extract relevant dets for this class for preproc and eval if cls == "all": gt_class_mask = np.ones_like(raw_data["gt_classes"][t]).astype(bool) else: gt_class_mask = np.atleast_1d( raw_data["gt_classes"][t] == cls_id ).astype(bool)
# select GT that is not in the evaluating classes if assignment is not None and assignment: all_gt_ids = list(assignment[t].keys()) gt_ids_in = raw_data["gt_ids"][t][gt_class_mask] gt_ids_out = set(all_gt_ids) - set(gt_ids_in) tk_ids_out = set([assignment[t][key] for key in list(gt_ids_out)])
# compute overlapped tracks and add their ids to overlap_tk_ids sim_scores = raw_data["similarity_scores"] overlap_ids_masks = (sim_scores[t][gt_class_mask] >= overlap_ious_thr).any( axis=0 ) overlap_tk_ids_t = raw_data["tk_ids"][t][overlap_ids_masks] if assignment is not None and assignment: data["tk_overlap_ids"][t] = list(set(overlap_tk_ids_t) - tk_ids_out) else: data["tk_overlap_ids"][t] = list(set(overlap_tk_ids_t))
loc_and_asso_tk_ids += data["tk_overlap_ids"][t]
data["tk_exh_ids"][t] = [] data["tk_neg_ids"][t] = []
if cls == "all": continue
# remove tk_ids that has been assigned to GT belongs to other classes. loc_and_asso_tk_ids = list(set(loc_and_asso_tk_ids))
# remove all unwanted unmatched tracker detections for t in range(raw_data["num_timesteps"]): # add gt to the data if cls == "all": gt_class_mask = np.ones_like(raw_data["gt_classes"][t]).astype(bool) else: gt_class_mask = np.atleast_1d( raw_data["gt_classes"][t] == cls_id ).astype(bool) data["gt_classes"][t] = cls_id data["gt_class_name"][t] = cls
gt_ids = raw_data["gt_ids"][t][gt_class_mask] if self.use_mask: gt_dets = [raw_data['gt_dets'][t][ind] for ind in range(len(gt_class_mask)) if gt_class_mask[ind]] else: gt_dets = raw_data["gt_dets"][t][gt_class_mask] data["gt_ids"][t] = gt_ids data["gt_dets"][t] = gt_dets
# filter pred and only keep those that highly overlap with GTs tk_mask = np.isin( raw_data["tk_ids"][t], np.array(loc_and_asso_tk_ids), assume_unique=True ) tk_overlap_mask = np.isin( raw_data["tk_ids"][t], np.array(data["tk_overlap_ids"][t]), assume_unique=True, )
tk_ids = raw_data["tk_ids"][t][tk_mask] if self.use_mask: tk_dets = [raw_data['tk_dets'][t][ind] for ind in range(len(tk_mask)) if tk_mask[ind]] else: tk_dets = raw_data["tk_dets"][t][tk_mask] tracker_classes = raw_data["tk_classes"][t][tk_mask]
# add overlap classes for computing the FP for Cls term tracker_overlap_classes = raw_data["tk_classes"][t][tk_overlap_mask] tracker_confidences = raw_data["tk_confidences"][t][tk_mask] sim_scores_masked = sim_scores[t][gt_class_mask, :][:, tk_mask]
# add filtered prediction to the data data["tk_classes"][t] = tracker_classes data["tk_overlap_classes"][t] = tracker_overlap_classes data["tk_ids"][t] = tk_ids data["tk_dets"][t] = tk_dets data["tk_confidences"][t] = tracker_confidences data["sim_scores"][t] = sim_scores_masked data["tk_class_eval_tk_ids"][t] = set( list(data["tk_overlap_ids"][t]) + list(data["tk_neg_ids"][t]) + list(data["tk_exh_ids"][t]) )
# count total number of detections unique_gt_ids += list(np.unique(data["gt_ids"][t])) # the unique track ids are for association. unique_tk_ids += list(np.unique(data["tk_ids"][t]))
num_tk_overlap_dets += len(data["tk_overlap_ids"][t]) num_tk_cls_dets += len(data["tk_class_eval_tk_ids"][t]) num_gt_dets += len(data["gt_ids"][t])
# re-label IDs such that there are no empty IDs if len(unique_gt_ids) > 0: unique_gt_ids = np.unique(unique_gt_ids) gt_id_map = np.nan * np.ones((np.max(unique_gt_ids) + 1)) gt_id_map[unique_gt_ids] = np.arange(len(unique_gt_ids)) data["gt_id_map"] = {} for gt_id in unique_gt_ids: new_gt_id = gt_id_map[gt_id].astype(int) data["gt_id_map"][new_gt_id] = gt_id
for t in range(raw_data["num_timesteps"]): if len(data["gt_ids"][t]) > 0: data["gt_ids"][t] = gt_id_map[data["gt_ids"][t]].astype(int)
if len(unique_tk_ids) > 0: unique_tk_ids = np.unique(unique_tk_ids) tk_id_map = np.nan * np.ones((np.max(unique_tk_ids) + 1)) tk_id_map[unique_tk_ids] = np.arange(len(unique_tk_ids))
data["tk_id_map"] = {} for track_id in unique_tk_ids: new_track_id = tk_id_map[track_id].astype(int) data["tk_id_map"][new_track_id] = track_id
for t in range(raw_data["num_timesteps"]): if len(data["tk_ids"][t]) > 0: data["tk_ids"][t] = tk_id_map[data["tk_ids"][t]].astype(int) if len(data["tk_overlap_ids"][t]) > 0: data["tk_overlap_ids"][t] = tk_id_map[ data["tk_overlap_ids"][t] ].astype(int)
# record overview statistics. data["num_tk_cls_dets"] = num_tk_cls_dets data["num_tk_overlap_dets"] = num_tk_overlap_dets data["num_gt_dets"] = num_gt_dets data["num_tk_ids"] = len(unique_tk_ids) data["num_gt_ids"] = len(unique_gt_ids) data["num_timesteps"] = raw_data["num_timesteps"] data["seq"] = raw_data["seq"]
self._check_unique_ids(data)
return data
@_timing.time def get_preprocessed_seq_data( self, raw_data, cls, assignment=None, thresholds=[50, 75] ): """Preprocess data for a single sequence for a single class.""" data = {} if thresholds is None: thresholds = [50] elif isinstance(thresholds, int): thresholds = [thresholds]
for thr in thresholds: assignment_thr = None if assignment is not None: assignment_thr = assignment[thr] data[thr] = self.get_preprocessed_seq_data_thr( raw_data, cls, assignment_thr )
return data
def _calculate_similarities(self, gt_dets_t, tk_dets_t): """Compute similarity scores.""" if self.use_mask: similarity_scores = self._calculate_mask_ious(gt_dets_t, tk_dets_t, is_encoded=True, do_ioa=False) else: similarity_scores = self._calculate_box_ious(gt_dets_t, tk_dets_t) return similarity_scores
def _merge_categories(self, annotations): """Merges categories with a merged tag.
Adapted from https://github.com/TAO-Dataset. """ merge_map = {} for category in self.gt_data["categories"]: if "merged" in category: for to_merge in category["merged"]: merge_map[to_merge["id"]] = category["id"]
for ann in annotations: ann["category_id"] = merge_map.get(ann["category_id"], ann["category_id"])
def _compute_vid_mappings(self, annotations): """Computes mappings from videos to corresponding tracks and images.""" vids_to_tracks = {} vids_to_imgs = {} vid_ids = [vid["id"] for vid in self.gt_data["videos"]]
# compute an mapping from image IDs to images images = {} for image in self.gt_data["images"]: images[image["id"]] = image
for ann in annotations: ann["area"] = ann["bbox"][2] * ann["bbox"][3]
vid = ann["video_id"] if ann["video_id"] not in vids_to_tracks.keys(): vids_to_tracks[ann["video_id"]] = list() if ann["video_id"] not in vids_to_imgs.keys(): vids_to_imgs[ann["video_id"]] = list()
# fill in vids_to_tracks tid = ann["track_id"] exist_tids = [track["id"] for track in vids_to_tracks[vid]] try: index1 = exist_tids.index(tid) except ValueError: index1 = -1 if tid not in exist_tids: curr_track = { "id": tid, "category_id": ann["category_id"], "video_id": vid, "annotations": [ann], } vids_to_tracks[vid].append(curr_track) else: vids_to_tracks[vid][index1]["annotations"].append(ann)
# fill in vids_to_imgs img_id = ann["image_id"] exist_img_ids = [img["id"] for img in vids_to_imgs[vid]] try: index2 = exist_img_ids.index(img_id) except ValueError: index2 = -1 if index2 == -1: curr_img = {"id": img_id, "annotations": [ann]} vids_to_imgs[vid].append(curr_img) else: vids_to_imgs[vid][index2]["annotations"].append(ann)
# sort annotations by frame index and compute track area for vid, tracks in vids_to_tracks.items(): for track in tracks: track["annotations"] = sorted( track["annotations"], key=lambda x: images[x["image_id"]]["frame_index"], ) # compute average area track["area"] = sum(x["area"] for x in track["annotations"]) / len( track["annotations"] )
# ensure all videos are present for vid_id in vid_ids: if vid_id not in vids_to_tracks.keys(): vids_to_tracks[vid_id] = [] if vid_id not in vids_to_imgs.keys(): vids_to_imgs[vid_id] = []
return vids_to_tracks, vids_to_imgs
def _compute_image_to_timestep_mappings(self): """Computes a mapping from images to timestep in sequence.""" images = {} for image in self.gt_data["images"]: images[image["id"]] = image
seq_to_imgs_to_timestep = {vid["id"]: dict() for vid in self.gt_data["videos"]} for vid in seq_to_imgs_to_timestep: curr_imgs = [img["id"] for img in self.video2gt_image[vid]] curr_imgs = sorted(curr_imgs, key=lambda x: images[x]["frame_index"]) seq_to_imgs_to_timestep[vid] = { curr_imgs[i]: i for i in range(len(curr_imgs)) }
return seq_to_imgs_to_timestep
def _limit_dets_per_image(self, annotations): """Limits the number of detections for each image.
Adapted from https://github.com/TAO-Dataset/. """ max_dets = self.config["MAX_DETECTIONS"] img_ann = defaultdict(list) for ann in annotations: img_ann[ann["image_id"]].append(ann)
for img_id, _anns in img_ann.items(): if len(_anns) <= max_dets: continue _anns = sorted(_anns, key=lambda x: x["score"], reverse=True) img_ann[img_id] = _anns[:max_dets]
return [ann for anns in img_ann.values() for ann in anns]
def _fill_video_ids_inplace(self, annotations): """Fills in missing video IDs inplace.
Adapted from https://github.com/TAO-Dataset/. """ missing_video_id = [x for x in annotations if "video_id" not in x] if missing_video_id: image_id_to_video_id = { x["id"]: x["video_id"] for x in self.gt_data["images"] } for x in missing_video_id: x["video_id"] = image_id_to_video_id[x["image_id"]]
@staticmethod def _make_tk_ids_unique(annotations): """Makes track IDs unqiue over the whole annotation set.
Adapted from https://github.com/TAO-Dataset/. """ track_id_videos = {} track_ids_to_update = set() max_track_id = 0 for ann in annotations: t = ann["track_id"] if t not in track_id_videos: track_id_videos[t] = ann["video_id"]
if ann["video_id"] != track_id_videos[t]: # track id is assigned to multiple videos track_ids_to_update.add(t) max_track_id = max(max_track_id, t)
if track_ids_to_update: print("true") next_id = itertools.count(max_track_id + 1) new_tk_ids = defaultdict(lambda: next(next_id)) for ann in annotations: t = ann["track_id"] v = ann["video_id"] if t in track_ids_to_update: ann["track_id"] = new_tk_ids[t, v] return len(track_ids_to_update)123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275# fmt: off# flake8: noqa
import copyimport osimport pickleimport timeimport tracebackfrom functools import partialfrom multiprocessing.pool import Pool
import numpy as np
from . import _timing, utilsfrom .config import get_default_eval_config, init_configfrom .utils import TrackEvalException
class Evaluator: """Evaluator class for evaluating different metrics for each datasets."""
def __init__(self, config=None): """Initialize the evaluator with a config file.""" self.config = init_config(config, get_default_eval_config(), "Eval") # Only run timing analysis if not run in parallel. if self.config["TIME_PROGRESS"] and not self.config["USE_PARALLEL"]: _timing.DO_TIMING = True if self.config["DISPLAY_LESS_PROGRESS"]: _timing.DISPLAY_LESS_PROGRESS = True
@_timing.time def evaluate(self, dataset_list, metrics_list): """Evaluate a set of metrics on a set of datasets.""" config = self.config metrics_list = metrics_list metric_names = utils.validate_metrics_list(metrics_list) dataset_names = [dataset.get_name() for dataset in dataset_list] output_res = {} output_msg = {}
for dataset, dname in zip(dataset_list, dataset_names): # Get dataset info about what to evaluate output_res[dname] = {} output_msg[dname] = {} tracker_list, seq_list, class_list = dataset.get_eval_info() print( f"\nEvaluating {len(tracker_list)} tracker(s) on " f"{len(seq_list)} sequence(s) for {len(class_list)} class(es)" f" on {dname} dataset using the following " f'metrics: {", ".join(metric_names)}\n' )
# Evaluate each tracker for tracker in tracker_list: try: output_res, output_msg = self.evaluate_tracker( tracker, dataset, dname, class_list, metrics_list, metric_names, seq_list, output_res, output_msg, ) except Exception as err: output_res[dname][tracker] = None if type(err) == TrackEvalException: output_msg[dname][tracker] = str(err) else: output_msg[dname][tracker] = "Unknown error occurred." print("Tracker %s was unable to be evaluated." % tracker) print(err) traceback.print_exc() if config["LOG_ON_ERROR"] is not None: with open(config["LOG_ON_ERROR"], "a") as f: print(dname, file=f) print(tracker, file=f) print(traceback.format_exc(), file=f) print("\n\n\n", file=f) if config["BREAK_ON_ERROR"]: raise err elif config["RETURN_ON_ERROR"]: return output_res, output_msg
return output_res, output_msg
def evaluate_tracker( self, tracker, dataset, dname, class_list, metrics_list, metric_names, seq_list, output_res, output_msg, ): """Evaluate each sequence in parallel or in series.""" print("\nEvaluating %s\n" % tracker) time_start = time.time() config = self.config if config["USE_PARALLEL"]: with Pool(config["NUM_PARALLEL_CORES"]) as pool: _eval_sequence = partial( eval_sequence, dataset=dataset, tracker=tracker, class_list=class_list, metrics_list=metrics_list, metric_names=metric_names, ) results = pool.map(_eval_sequence, seq_list) res = dict(zip(seq_list, results)) else: res = {} for curr_seq in sorted(seq_list): res[curr_seq] = eval_sequence( curr_seq, dataset, tracker, class_list, metrics_list, metric_names )
# collecting combined cls keys (cls averaged, det averaged, super classes) cls_keys = [] res["COMBINED_SEQ"] = {} # combine sequences for each class for c_cls in class_list: res["COMBINED_SEQ"][c_cls] = {} for metric, mname in zip(metrics_list, metric_names): curr_res = { seq_key: seq_value[c_cls][mname] for seq_key, seq_value in res.items() if seq_key != "COMBINED_SEQ" } # combine results over all sequences and then over all classes res["COMBINED_SEQ"][c_cls][mname] = metric.combine_sequences(curr_res)
# combine classes if dataset.should_classes_combine: if config["OUTPUT_PER_SEQ_RES"]: video_keys = res.keys() else: video_keys = ["COMBINED_SEQ"] for v_key in video_keys: cls_keys += ["average"] res[v_key]["average"] = {} for metric, mname in zip(metrics_list, metric_names): cls_res = { cls_key: cls_value[mname] for cls_key, cls_value in res[v_key].items() if cls_key not in cls_keys } res[v_key]["average"][ mname ] = metric.combine_classes_class_averaged( cls_res, ignore_empty=True )
# combine classes to super classes if dataset.use_super_categories: for cat, sub_cats in dataset.super_categories.items(): cls_keys.append(cat) res["COMBINED_SEQ"][cat] = {} for metric, mname in zip(metrics_list, metric_names): cat_res = { cls_key: cls_value[mname] for cls_key, cls_value in res["COMBINED_SEQ"].items() if cls_key in sub_cats } res["COMBINED_SEQ"][cat][ mname ] = metric.combine_classes_det_averaged(cat_res) # Print and output results in various formats if config["TIME_PROGRESS"]: print( f"\nAll sequences for {tracker} finished in" f" {time.time() - time_start} seconds" ) output_fol = dataset.get_output_fol(tracker) os.makedirs(output_fol, exist_ok=True)
# take a mean of each field of each thr if config["OUTPUT_PER_SEQ_RES"]: all_res = copy.deepcopy(res) summary_keys = res.keys() else: all_res = copy.deepcopy(res["COMBINED_SEQ"]) summary_keys = ["COMBINED_SEQ"] thr_key_list = [50] for s_key in summary_keys: for metric, mname in zip(metrics_list, metric_names): if mname != "TETA": if s_key == "COMBINED_SEQ": metric.print_table( {"COMBINED_SEQ": res["COMBINED_SEQ"][cls_keys[0]][mname]}, tracker, cls_keys[0], ) continue
for c_cls in res[s_key].keys(): for thr in thr_key_list: all_res[s_key][c_cls][mname][thr] = metric._summary_row( res[s_key][c_cls][mname][thr] ) x = ( np.array(list(all_res[s_key][c_cls]["TETA"].values())) .astype("float") .mean(axis=0) ) all_res_summary = list(x.round(decimals=2).astype("str")) all_res[s_key][c_cls][mname]["ALL"] = all_res_summary if config["OUTPUT_SUMMARY"] and s_key == "COMBINED_SEQ": for t in thr_key_list: metric.print_summary_table( all_res[s_key][cls_keys[0]][mname][t], t, tracker, cls_keys[0], )
if config["OUTPUT_TEM_RAW_DATA"]: out_file = os.path.join(output_fol, "teta_summary_results.pth") pickle.dump(all_res, open(out_file, "wb")) print("Saved the TETA summary results.")
# output output_res[dname][mname] = all_res[s_key][cls_keys[0]][mname][t] output_msg[dname][tracker] = "Success"
return output_res, output_msg
@_timing.timedef eval_sequence(seq, dataset, tracker, class_list, metrics_list, metric_names): """Function for evaluating a single sequence.""" raw_data = dataset.get_raw_seq_data(tracker, seq) seq_res = {}
if "TETA" in metric_names: thresholds = [50] data_all_class = dataset.get_preprocessed_seq_data( raw_data, "all", thresholds=thresholds ) teta = metrics_list[metric_names.index("TETA")] assignment = teta.compute_global_assignment(data_all_class)
# create a dict to save Cls_FP for each class in different thr. cls_fp = { key: { cls: np.zeros((len(np.arange(0.5, 0.99, 0.05)))) for cls in class_list } for key in thresholds }
for cls in class_list: seq_res[cls] = {} data = dataset.get_preprocessed_seq_data(raw_data, cls, assignment, thresholds)
for metric, mname in zip(metrics_list, metric_names): if mname == "TETA": seq_res[cls][mname], cls_fp, _ = metric.eval_sequence( data, cls, dataset.clsid2cls_name, cls_fp ) else: seq_res[cls][mname] = metric.eval_sequence(data)
if "TETA" in metric_names: for thr in thresholds: for cls in class_list: seq_res[cls]["TETA"][thr]["Cls_FP"] += cls_fp[thr][cls]
return seq_res123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148# fmt: off# flake8: noqa
from abc import ABC, abstractmethod
import numpy as np
from .. import _timingfrom ..utils import TrackEvalException
class _BaseMetric(ABC): @abstractmethod def __init__(self): self.plottable = False self.integer_fields = [] self.float_fields = [] self.array_labels = [] self.integer_array_fields = [] self.float_array_fields = [] self.fields = [] self.summary_fields = [] self.registered = False
##################################################################### # Abstract functions for subclasses to implement
@_timing.time @abstractmethod def eval_sequence(self, data): ...
@abstractmethod def combine_sequences(self, all_res): ...
@abstractmethod def combine_classes_class_averaged(self, all_res, ignore_empty=False): ...
@abstractmethod def combine_classes_det_averaged(self, all_res): ...
def plot_single_tracker_results(self, all_res, tracker, output_folder, cls): """Plot results, only valid for metrics with self.plottable.""" if self.plottable: raise NotImplementedError( f"plot_results is not implemented for metric {self.get_name()}" ) else: pass
##################################################################### # Helper functions which are useful for all metrics:
@classmethod def get_name(cls): return cls.__name__
@staticmethod def _combine_sum(all_res, field): """Combine sequence results via sum""" return sum([all_res[k][field] for k in all_res.keys()])
@staticmethod def _combine_weighted_av(all_res, field, comb_res, weight_field): """Combine sequence results via weighted average.""" return sum( [all_res[k][field] * all_res[k][weight_field] for k in all_res.keys()] ) / np.maximum(1.0, comb_res[weight_field])
def print_table(self, table_res, tracker, cls): """Print table of results for all sequences.""" print("") metric_name = self.get_name() self._row_print( [metric_name + ": " + tracker + "-" + cls] + self.summary_fields ) for seq, results in sorted(table_res.items()): if seq == "COMBINED_SEQ": continue summary_res = self._summary_row(results) self._row_print([seq] + summary_res) summary_res = self._summary_row(table_res["COMBINED_SEQ"]) self._row_print(["COMBINED"] + summary_res)
def _summary_row(self, results_): vals = [] for h in self.summary_fields: if h in self.float_array_fields: vals.append("{0:1.5g}".format(100 * np.mean(results_[h]))) elif h in self.float_fields: vals.append("{0:1.5g}".format(100 * float(results_[h]))) elif h in self.integer_fields: vals.append("{0:d}".format(int(results_[h]))) else: raise NotImplementedError( "Summary function not implemented for this field type." ) return vals
@staticmethod def _row_print(*argv): """Print results in evenly spaced rows, with more space in first row.""" if len(argv) == 1: argv = argv[0] to_print = "%-35s" % argv[0] for v in argv[1:]: to_print += "%-10s" % str(v) print(to_print)
def summary_results(self, table_res): """Return a simple summary of final results for a tracker.""" return dict( zip(self.summary_fields, self._summary_row(table_res["COMBINED_SEQ"]),) )
def detailed_results(self, table_res): """Return detailed final results for a tracker.""" # Get detailed field information detailed_fields = self.float_fields + self.integer_fields for h in self.float_array_fields + self.integer_array_fields: for alpha in [int(100 * x) for x in self.array_labels]: detailed_fields.append(h + "___" + str(alpha)) detailed_fields.append(h + "___AUC")
# Get detailed results detailed_results = {} for seq, res in table_res.items(): detailed_row = self._detailed_row(res) if len(detailed_row) != len(detailed_fields): raise TrackEvalException( f"Field names and data have different sizes " f"({len(detailed_row)} and {len(detailed_fields)})" ) detailed_results[seq] = dict(zip(detailed_fields, detailed_row)) return detailed_results
def _detailed_row(self, res): detailed_row = [] for h in self.float_fields + self.integer_fields: detailed_row.append(res[h]) for h in self.float_array_fields + self.integer_array_fields: for i, _ in enumerate([int(100 * x) for x in self.array_labels]): detailed_row.append(res[h][i]) detailed_row.append(np.mean(res[h])) return detailed_row123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411# Copyright (c) Meta Platforms, Inc. and affiliates. All Rights Reservedimport copyimport gcimport loggingimport osfrom collections import defaultdictfrom operator import xorfrom pathlib import Pathfrom typing import List, Optional
import numpy as npimport pycocotools.mask as mask_utilimport torchfrom pycocotools.cocoeval import COCOevalfrom sam3.eval.cgf1_eval import CGF1Evalfrom sam3.eval.coco_eval_offline import convert_to_xywhfrom sam3.model.box_ops import box_xywh_inter_unionfrom sam3.train.masks_ops import rle_encodefrom sam3.train.utils import distributed as distfrom typing_extensions import override
try: import rapidjson as jsonexcept ModuleNotFoundError: import json
from iopath.common.file_io import g_pathmgr
class YTVISevalMixin: """ Identical to COCOeval but adapts computeIoU to compute IoU between tracklets/masklets. """
@override def _prepare(self): """ Copied from cocoeval.py but doesn't convert masks to RLEs (we assume they already are RLEs) """ p = self.params if p.useCats: gts = self.cocoGt.loadAnns( self.cocoGt.getAnnIds(imgIds=p.imgIds, catIds=p.catIds) ) dts = self.cocoDt.loadAnns( self.cocoDt.getAnnIds(imgIds=p.imgIds, catIds=p.catIds) ) else: gts = self.cocoGt.loadAnns(self.cocoGt.getAnnIds(imgIds=p.imgIds)) dts = self.cocoDt.loadAnns(self.cocoDt.getAnnIds(imgIds=p.imgIds))
# set ignore flag for gt in gts: gt["ignore"] = gt["ignore"] if "ignore" in gt else 0 gt["ignore"] = "iscrowd" in gt and gt["iscrowd"] if p.iouType == "keypoints": gt["ignore"] = (gt["num_keypoints"] == 0) or gt["ignore"] self._gts = defaultdict(list) # gt for evaluation self._dts = defaultdict(list) # dt for evaluation for gt in gts: self._gts[gt["image_id"], gt["category_id"]].append(gt) for dt in dts: self._dts[dt["image_id"], dt["category_id"]].append(dt) self.evalImgs = defaultdict(list) # per-image per-category evaluation results self.eval = {} # accumulated evaluation results
def computeIoU(self, imgId, catId): """ Compute IoU between tracklets. Copied from cocoeval.py but adapted for videos (in YT-VIS format) """ p = self.params if p.useCats: gt = self._gts[imgId, catId] dt = self._dts[imgId, catId] else: gt = [_ for cId in p.catIds for _ in self._gts[imgId, cId]] dt = [_ for cId in p.catIds for _ in self._dts[imgId, cId]] if len(gt) == 0 or len(dt) == 0: return []
# For class mAP and phrase AP evaluation, we sort the detections in descending order of scores (as in COCOeval). # For demo F1 evaluation, we DO NOT sort the detections (but match them with GTs via Hungarian matching). assert hasattr(self, "sort_inds_by_scores_in_iou"), ( "subclasses that inherits YTVISevalMixin should set `self.sort_inds_by_scores_in_iou` " "(True for class mAP and phrase AP, False for demo F1)" ) if self.sort_inds_by_scores_in_iou: inds = np.argsort([-d["score"] for d in dt], kind="mergesort") dt = [dt[i] for i in inds] if len(dt) > p.maxDets[-1]: dt = dt[0 : p.maxDets[-1]]
if p.iouType == "segm": g = [g["segmentations"] for g in gt] d = [d["segmentations"] for d in dt] elif p.iouType == "bbox": g = [g["bboxes"] for g in gt] d = [d["bboxes"] for d in dt] else: raise Exception("unknown iouType for iou computation")
def iou_tracklets(preds, gts): preds = torch.tensor(preds) gts = torch.tensor(gts) inter, union = box_xywh_inter_union( preds.unsqueeze(1), gts.unsqueeze(0) ) # Num preds x Num GTS x Num frames inter = inter.sum(-1) union = union.sum(-1) assert ( union > 0 ).all(), ( "There exists a tracklet with zero GTs across time. This is suspicious" ) return inter / union
def iou_masklets(preds, gts): inter = 0 union = 0 for p_i, gt_i in zip(preds, gts): if p_i and gt_i: # Compute areas of intersection and union inter += mask_util.area( mask_util.merge([p_i, gt_i], intersect=True) ) union += mask_util.area( mask_util.merge([p_i, gt_i], intersect=False) ) elif gt_i: union += mask_util.area(gt_i) elif p_i: union += mask_util.area(p_i) if union > 0: iou = inter / union assert iou >= 0 and iou <= 1, "Encountered an error in IoU computation" else: assert np.isclose(inter, 0) and np.isclose( union, 0 ), "Encountered an error in IoU computation" iou = 1 return iou
if p.iouType == "segm": ious = [[iou_masklets(d_i, g_i) for g_i in g] for d_i in d] else: ious = iou_tracklets(d, g) return np.array(ious)
class YTVISeval(YTVISevalMixin, COCOeval): # For class mAP and phrase AP evaluation, we sort the detections in descending order of scores (as in COCOeval). sort_inds_by_scores_in_iou = True
class VideoDemoF1Eval(YTVISevalMixin, CGF1Eval): # For demo F1 evaluation, we DO NOT sort the detections (but match them with GTs via Hungarian matching). sort_inds_by_scores_in_iou = False
class YTVISResultsWriter: """ Gather and dumps predictions in YT-VIS format. Expected flow of API calls: reset() -> N * update() -> compute_synced() """
def __init__( self, dump_file: str, postprocessor, gather_pred_via_filesys=False, pred_file_evaluators: Optional[List] = None, save_per_frame_scores: bool = False, write_eval_metrics_file: bool = True, eval_metrics_file_suffix: str = ".sam3_eval_metrics", ): self.dump_file = dump_file self.dump = [] self.postprocessor = postprocessor self.gather_pred_via_filesys = gather_pred_via_filesys if dist.is_main_process(): dirname = os.path.dirname(self.dump_file) if not os.path.exists(dirname): os.makedirs(dirname, exist_ok=True) logging.info(f"Creating folder: {dirname}")
# the evaluation hooks to be applied to the prediction files self.pred_file_evaluators = pred_file_evaluators or [] self.save_per_frame_scores = save_per_frame_scores # in addition to the prediction file, we also write the evaluation metrics # for easier debugging and analysis (stored in another eval_metrics_file # so that we can keep the dumped prediction file under YT-VIS format) self.write_eval_metrics_file = write_eval_metrics_file if self.write_eval_metrics_file: self.eval_metrics_file = self.dump_file + eval_metrics_file_suffix os.makedirs(os.path.dirname(self.eval_metrics_file), exist_ok=True)
def _dump_vid_preds(self, results): dumped_results = copy.deepcopy(results) self.dump.extend(dumped_results)
def prepare(self, predictions): ytvis_results = [] for video_id, prediction in predictions.items(): if len(prediction) == 0: continue for k in ["boxes", "scores", "labels"]: assert ( k in prediction ), f"Expected predictions to have `{k}` key, available keys are {prediction.keys()}" if self.save_per_frame_scores: assert ( "per_frame_scores" in prediction ), f"Expected predictions to have `per_frame_scores` key, available keys are {prediction.keys()}" assert xor( "masks" in prediction, "masks_rle" in prediction ), f"Expected predictions to have either `masks` key or `masks_rle` key, available keys are {prediction.keys()}"
boxes = prediction["boxes"] boxes = convert_to_xywh(boxes).tolist() scores = prediction["scores"].tolist() labels = prediction["labels"].tolist() if "masks" in prediction: masks = prediction["masks"].squeeze(2) assert ( masks.ndim == 4 ), "Expected masks to be of shape(N_preds,T_frames,H,W)"
areas = [mask.flatten(1).sum(1).tolist() for mask in masks] rles = [rle_encode(masklet) for masklet in masks]
# memory clean del masks del prediction["masks"] elif "masks_rle" in prediction: rles = prediction.pop("masks_rle") areas = [ [0 if rle is None else rle.pop("area") for rle in rles_per_obj] for rles_per_obj in rles ] else: raise ValueError( "Expected either `masks` or `masks_rle` key in the predictions." )
new_results = [ { "video_id": video_id, "category_id": track_label, "bboxes": track_boxes, "score": track_score, "segmentations": track_masks, "areas": track_areas, } for ( track_boxes, track_masks, track_areas, track_score, track_label, ) in zip(boxes, rles, areas, scores, labels) ] # Optionally, save per-frame scores if self.save_per_frame_scores: per_frame_scores = prediction["per_frame_scores"].tolist() for res, track_per_frame_scores in zip(new_results, per_frame_scores): res["per_frame_scores"] = track_per_frame_scores
ytvis_results.extend(new_results)
return ytvis_results
def set_sync_device(self, device: torch.device): self._sync_device = device
def update(self, *args, **kwargs): predictions = self.postprocessor.process_results(*args, **kwargs) results = self.prepare(predictions) self._dump_vid_preds(results)
def _dump_preds(self): if not dist.is_main_process(): self.dump = [] gc.collect() return dumped_file = Path(self.dump_file) logging.info(f"YTVIS evaluator: Dumping predictions to {dumped_file}") with g_pathmgr.open(str(dumped_file), "w") as f: json.dump(self.dump, f) self.dump = [] gc.collect() return str(dumped_file)
def synchronize_between_processes(self): logging.info("YT-VIS evaluator: Synchronizing between processes") dump_dict = self._dedup_pre_gather(self.dump) if self.gather_pred_via_filesys: dump_dict_all_gpus = dist.gather_to_rank_0_via_filesys(dump_dict) else: dump_dict_all_gpus = dist.all_gather(dump_dict, force_cpu=True) self.dump = self._dedup_post_gather(dump_dict_all_gpus) logging.info(f"Gathered all {len(self.dump)} predictions")
def _dedup_pre_gather(self, predictions): """ Organize the predictions as a dict-of-list using (video_id, category_id) as keys for deduplication after gathering them across GPUs.
During evaluation, PyTorch data loader under `drop_last: False` would wrap around the dataset length to be a multiple of world size (GPU num) and duplicate the remaining batches. This causes the same test sample to appear simultaneously in multiple GPUs, resulting in duplicated predictions being saved into prediction files. These duplicates are then counted as false positives under detection mAP metrics (since a ground truth can be matched with only one prediction).
For example, if there are 4 GPUs and 6 samples [A1, A2, B1, B2, C1, C2], the data loader (under `drop_last: False`) would load it by wrapping it around like `[A1, A2, B1, B2, C1, C2, *A1*, *A2*]` to make a multiple of 4 and then split it as
- GPU 0: A1, C1 - GPU 1: A2, C2 - GPU 3: B1, **A1** - GPU 4: B2, **A2** (as in DistributedSampler in https://github.com/pytorch/pytorch/blob/521588519da9f4876d90ddd7a17c10d0eca89dc6/torch/utils/data/distributed.py#L116-L124)
so the predictions on A1 and A2 will occur twice in the final gathered outputs in the prediction file (and counted as false positives). This also affects our YT-VIS official val evaluation, but to a lesser extent than YT-VIS dev since the latter is much smaller and more susceptible to false positives.
So we to deduplicate this. The tricky part is that we cannot deduplicate them simply using video id, given that we are sharding the classes in each video across multiple batches (with 20 prompts per batch) in our "orig_cats" eval dbs.
The solution is to deduplicate based on (video_id, category_id) tuple as keys. We organize the predictions as a dict-of-list using (video_id, category_id) as keys on each GPU, with the list of masklets under this (video_id, category_id) on this GPU as values. Then, we all-gather this dict-of-list across GPUs and if a key (video_id, category_id) appears in multiple GPUs, we only take the prediction masklet list from one GPU. """ prediction_dict = defaultdict(list) for p in predictions: prediction_dict[(p["video_id"], p["category_id"])].append(p) return prediction_dict
def _dedup_post_gather(self, list_of_prediction_dict): """ Deduplicate the predictions from all GPUs. See `_dedup_pre_gather` for details. """ dedup_prediction_dict = {} duplication_keys = [] for prediction_dict in list_of_prediction_dict: for k, v in prediction_dict.items(): if k not in dedup_prediction_dict: dedup_prediction_dict[k] = v else: duplication_keys.append(k)
logging.info( f"skipped {len(duplication_keys)} duplicated predictions in YTVISResultsWriter " f"with the following (video_id, category_id) tuples: {duplication_keys}" ) dedup_predictions = sum(dedup_prediction_dict.values(), []) return dedup_predictions
def compute_synced( self, ): self.synchronize_between_processes() dumped_file = self._dump_preds() if not dist.is_main_process(): return {"": 0.0}
# run evaluation hooks on the prediction file meters = {} all_video_np_level_results = defaultdict(dict) for evaluator in self.pred_file_evaluators: gc.collect() results, video_np_level_results = evaluator.evaluate(dumped_file) meters.update(results) for (video_id, category_id), res in video_np_level_results.items(): all_video_np_level_results[(video_id, category_id)].update(res)
gc.collect() if self.write_eval_metrics_file: # convert the nested dict of {(video_id, category_id): per_sample_metric_dict} # to a list of per-sample metric dicts (with video_id and category_id) for JSON, # as JSON doesn't allow using tuples like (video_id, category_id) as dict keys video_np_level_metrics = [ {"video_id": video_id, "category_id": category_id, **res} for (video_id, category_id), res in all_video_np_level_results.items() ] eval_metrics = { "dataset_level_metrics": meters, "video_np_level_metrics": video_np_level_metrics, } with g_pathmgr.open(self.eval_metrics_file, "w") as f: json.dump(eval_metrics, f) logging.info( f"YTVIS evaluator: Dumped evaluation metrics to {self.eval_metrics_file}" )
if len(meters) == 0: meters = {"": 0.0} return meters
def compute(self): return {"": 0.0}
def reset(self, *args, **kwargs): self.dump = []123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114# Copyright (c) Meta Platforms, Inc. and affiliates. All Rights Reserved
import inspectfrom functools import wrapsfrom typing import Callable, TypeVar, Union
import torchimport torch.nn as nnimport torch.utils.checkpoint as checkpointfrom torch.utils._pytree import tree_map_only
# Type variables for better type hintingT = TypeVar("T")Module = TypeVar("Module", bound=nn.Module)
def activation_ckpt_wrapper(module: Union[nn.Module, Callable]) -> Callable: """ Wraps a given module to enable or disable activation checkpointing.
Activation checkpointing (gradient checkpointing) trades compute for memory by recomputing intermediate activations during the backward pass instead of storing them in memory during the forward pass.
When activation checkpointing is enabled, the wrapper expects only keyword arguments, and it maps these to positional arguments based on the module's signature.
Args: module: The module or function to wrap with activation checkpointing
Returns: A wrapped callable that supports activation checkpointing
Usage: The returned wrapper function can be called with the same arguments as the original module, with an additional `act_ckpt_enable` keyword argument to control activation checkpointing and optional `use_reentrant` parameter.
Example: ```python wrapped_module = activation_ckpt_wrapper(my_module) output = wrapped_module(x=input_tensor, y=another_tensor, act_ckpt_enable=True) ``` """
@wraps(module) def act_ckpt_wrapper( *args, act_ckpt_enable: bool = True, use_reentrant: bool = False, **kwargs ): if act_ckpt_enable: if len(args) > 0: raise ValueError( "This wrapper expects keyword arguments only when `act_ckpt_enable=True`" ) # Get the signature of the target function/module callable_fn = module.forward if isinstance(module, nn.Module) else module sig = inspect.signature(callable_fn) # Create a mapping of parameter names to their default values param_defaults = { name: param.default for name, param in sig.parameters.items() } args = [] for p_name in param_defaults.keys(): if p_name in kwargs: args.append(kwargs.pop(p_name)) elif param_defaults[p_name] is not inspect.Parameter.empty: # Set arg to default value if it's not in kwargs. Useful for primitive types or args that default to None args.append(param_defaults[p_name]) elif ( sig.parameters[p_name].kind is not inspect.Parameter.VAR_KEYWORD ): # Skip **kwargs parameter raise ValueError(f"Missing positional argument: {p_name}")
# Scan remaining kwargs for torch.Tensor remaining_keys = list(kwargs.keys()) for key in remaining_keys: if isinstance(kwargs[key], torch.Tensor): # Remove the tensor from kwargs, assuming it's not required by the module. # If it is required, the module's signature should be modified to accept it as a positional or keyword argument. kwargs[key] = "_REMOVED_BY_ACT_CKPT_WRAPPER_"
ret = checkpoint.checkpoint( module, *args, use_reentrant=use_reentrant, **kwargs ) else: ret = module(*args, **kwargs)
return ret
return act_ckpt_wrapper
def clone_output_wrapper(f: Callable[..., T]) -> Callable[..., T]: """ Clone the CUDA output tensors of a function to avoid in-place operations.
This wrapper is useful when working with torch.compile to prevent errors related to in-place operations on tensors.
Args: f: The function whose CUDA tensor outputs should be cloned
Returns: A wrapped function that clones any CUDA tensor outputs """
@wraps(f) def wrapped(*args, **kwargs): outputs = f(*args, **kwargs) return tree_map_only( torch.Tensor, lambda t: t.clone() if t.is_cuda else t, outputs )
return wrapped123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594# Copyright (c) Meta Platforms, Inc. and affiliates. All Rights Reserved# Based on https://github.com/IDEA-Research/GroundingDINO
from typing import Any, Dict, List, Optional, Tuple
import torchfrom torch import nn, Tensor
from .act_ckpt_utils import activation_ckpt_wrapperfrom .model_misc import get_activation_fn, get_clones, get_valid_ratio
class TransformerEncoderLayer(nn.Module): """ Transformer encoder layer that performs self-attention followed by cross-attention.
This layer was previously called TransformerDecoderLayer but was renamed to better reflect its role in the architecture. It processes input sequences through self-attention and then cross-attention with another input (typically image features).
The layer supports both pre-norm and post-norm configurations, as well as positional encoding at different stages of the attention mechanism. """
def __init__( self, activation: str, cross_attention: nn.Module, d_model: int, dim_feedforward: int, dropout: float, pos_enc_at_attn: bool, pos_enc_at_cross_attn_keys: bool, pos_enc_at_cross_attn_queries: bool, pre_norm: bool, self_attention: nn.Module, ): """ Initialize a transformer encoder layer.
Args: activation: Activation function to use in the feedforward network cross_attention: Cross-attention module for attending to image features d_model: Model dimension/hidden size dim_feedforward: Dimension of the feedforward network dropout: Dropout probability pos_enc_at_attn: Whether to add positional encodings at self-attention pos_enc_at_cross_attn_keys: Whether to add positional encodings to keys in cross-attention pos_enc_at_cross_attn_queries: Whether to add positional encodings to queries in cross-attention pre_norm: Whether to use pre-norm (True) or post-norm (False) architecture self_attention: Self-attention module """ super().__init__() self.d_model = d_model self.dim_feedforward = dim_feedforward self.dropout_value = dropout self.self_attn = self_attention self.cross_attn_image = cross_attention
# Implementation of Feedforward model self.linear1 = nn.Linear(d_model, dim_feedforward) self.dropout = nn.Dropout(dropout) self.linear2 = nn.Linear(dim_feedforward, d_model)
self.norm1 = nn.LayerNorm(d_model) self.norm2 = nn.LayerNorm(d_model) self.norm3 = nn.LayerNorm(d_model) self.dropout1 = nn.Dropout(dropout) self.dropout2 = nn.Dropout(dropout) self.dropout3 = nn.Dropout(dropout)
self.activation_str = activation self.activation = get_activation_fn(activation) self.pre_norm = pre_norm
self.pos_enc_at_attn = pos_enc_at_attn self.pos_enc_at_cross_attn_queries = pos_enc_at_cross_attn_queries self.pos_enc_at_cross_attn_keys = pos_enc_at_cross_attn_keys
self.layer_idx = None
def forward_post( self, tgt: Tensor, memory: Tensor, tgt_mask: Optional[Tensor] = None, memory_mask: Optional[Tensor] = None, tgt_key_padding_mask: Optional[Tensor] = None, memory_key_padding_mask: Optional[Tensor] = None, pos: Optional[Tensor] = None, query_pos: Optional[Tensor] = None, **kwargs, ) -> Tensor: """ Forward pass for post-norm architecture.
In post-norm architecture, normalization is applied after attention and feedforward operations.
Args: tgt: Input tensor to be processed memory: Memory tensor for cross-attention tgt_mask: Mask for self-attention memory_mask: Mask for cross-attention tgt_key_padding_mask: Key padding mask for self-attention memory_key_padding_mask: Key padding mask for cross-attention pos: Positional encoding for memory query_pos: Positional encoding for query **kwargs: Additional keyword arguments
Returns: Processed tensor """ q = k = tgt + query_pos if self.pos_enc_at_attn else tgt
# Self attention tgt2 = self.self_attn( q, k, value=tgt, attn_mask=tgt_mask, key_padding_mask=tgt_key_padding_mask )[0] tgt = tgt + self.dropout1(tgt2) tgt = self.norm1(tgt)
# Cross attention to image tgt2 = self.cross_attn_image( query=tgt + query_pos if self.pos_enc_at_cross_attn_queries else tgt, key=memory + pos if self.pos_enc_at_cross_attn_keys else memory, value=memory, attn_mask=memory_mask, key_padding_mask=memory_key_padding_mask, )[0] tgt = tgt + self.dropout2(tgt2) tgt = self.norm2(tgt)
# FFN tgt2 = self.linear2(self.dropout(self.activation(self.linear1(tgt)))) tgt = tgt + self.dropout3(tgt2) tgt = self.norm3(tgt) return tgt
def forward_pre( self, tgt: Tensor, memory: Tensor, dac: bool = False, tgt_mask: Optional[Tensor] = None, memory_mask: Optional[Tensor] = None, tgt_key_padding_mask: Optional[Tensor] = None, memory_key_padding_mask: Optional[Tensor] = None, pos: Optional[Tensor] = None, query_pos: Optional[Tensor] = None, # attn_bias: Optional[Tensor] = None, # **kwargs, ) -> Tensor: """ Forward pass for pre-norm architecture.
In pre-norm architecture, normalization is applied before attention and feedforward operations.
Args: tgt: Input tensor to be processed memory: Memory tensor for cross-attention dac: Whether to use Divide-and-Conquer attention tgt_mask: Mask for self-attention memory_mask: Mask for cross-attention tgt_key_padding_mask: Key padding mask for self-attention memory_key_padding_mask: Key padding mask for cross-attention pos: Positional encoding for memory query_pos: Positional encoding for query attn_bias: Optional attention bias tensor **kwargs: Additional keyword arguments
Returns: Processed tensor """ if dac: # we only apply self attention to the first half of the queries assert tgt.shape[0] % 2 == 0 other_tgt = tgt[tgt.shape[0] // 2 :] tgt = tgt[: tgt.shape[0] // 2] tgt2 = self.norm1(tgt) q = k = tgt2 + query_pos if self.pos_enc_at_attn else tgt2 tgt2 = self.self_attn( q, k, value=tgt2, attn_mask=tgt_mask, key_padding_mask=tgt_key_padding_mask )[0] tgt = tgt + self.dropout1(tgt2) if dac: # Recombine tgt = torch.cat((tgt, other_tgt), dim=0) tgt2 = self.norm2(tgt) tgt2 = self.cross_attn_image( query=tgt2 + query_pos if self.pos_enc_at_cross_attn_queries else tgt2, key=memory + pos if self.pos_enc_at_cross_attn_keys else memory, value=memory, attn_mask=memory_mask, key_padding_mask=memory_key_padding_mask, # attn_bias=attn_bias, )[0] tgt = tgt + self.dropout2(tgt2) tgt2 = self.norm3(tgt) tgt2 = self.linear2(self.dropout(self.activation(self.linear1(tgt2)))) tgt = tgt + self.dropout3(tgt2) return tgt
def forward( self, tgt: Tensor, memory: Tensor, dac: bool = False, tgt_mask: Optional[Tensor] = None, memory_mask: Optional[Tensor] = None, tgt_key_padding_mask: Optional[Tensor] = None, memory_key_padding_mask: Optional[Tensor] = None, pos: Optional[Tensor] = None, query_pos: Optional[Tensor] = None, # attn_bias: Optional[Tensor] = None, # **kwds: Any, ) -> torch.Tensor: """ Forward pass for the transformer encoder layer.
Args: tgt: Input tensor to be processed memory: Memory tensor (e.g., image features) for cross-attention dac: Whether to use Divide-and-Conquer attention (only apply self-attention to first half) tgt_mask: Mask for self-attention memory_mask: Mask for cross-attention tgt_key_padding_mask: Key padding mask for self-attention memory_key_padding_mask: Key padding mask for cross-attention pos: Positional encoding for memory query_pos: Positional encoding for query attn_bias: Optional attention bias tensor **kwds: Additional keyword arguments
Returns: Processed tensor after self-attention, cross-attention, and feedforward network """ fwd_fn = self.forward_pre if self.pre_norm else self.forward_post return fwd_fn( tgt, memory, dac=dac, tgt_mask=tgt_mask, memory_mask=memory_mask, tgt_key_padding_mask=tgt_key_padding_mask, memory_key_padding_mask=memory_key_padding_mask, pos=pos, query_pos=query_pos, # attn_bias=attn_bias, # **kwds, )
class TransformerEncoder(nn.Module): """ Transformer encoder that processes multi-level features.
This encoder takes multi-level features (e.g., from a backbone network) and processes them through a stack of transformer encoder layers. It supports features from multiple levels (e.g., different resolutions) and can apply activation checkpointing for memory efficiency during training.
Args: layer: The encoder layer to be stacked multiple times num_layers: Number of encoder layers to stack d_model: Model dimension/hidden size num_feature_levels: Number of feature levels to process frozen: Whether to freeze the parameters of this module use_act_checkpoint: Whether to use activation checkpointing during training """
def __init__( self, layer: nn.Module, num_layers: int, d_model: int, num_feature_levels: int, frozen: bool = False, use_act_checkpoint: bool = False, ): super().__init__() self.layers = get_clones(layer, num_layers) self.num_layers = num_layers
self.num_feature_levels = num_feature_levels self.level_embed = None if num_feature_levels > 1: self.level_embed = nn.Parameter(torch.Tensor(num_feature_levels, d_model))
if frozen: for p in self.parameters(): p.requires_grad_(False)
self.use_act_checkpoint = use_act_checkpoint
# assign layer index to each layer so that some layers can decide what to do # based on which layer index they are (e.g. cross attention to memory bank only # in selected layers) for layer_idx, layer in enumerate(self.layers): layer.layer_idx = layer_idx
@staticmethod def get_reference_points(spatial_shapes, valid_ratios, device): with torch.no_grad(): reference_points_list = [] for lvl, (H_, W_) in enumerate(spatial_shapes): ref_y, ref_x = torch.meshgrid( torch.linspace( 0.5, H_ - 0.5, H_, dtype=torch.float32, device=device ), torch.linspace( 0.5, W_ - 0.5, W_, dtype=torch.float32, device=device ), ) ref_y = ref_y.reshape(-1)[None] / (valid_ratios[:, None, lvl, 1] * H_) ref_x = ref_x.reshape(-1)[None] / (valid_ratios[:, None, lvl, 0] * W_) ref = torch.stack((ref_x, ref_y), -1) reference_points_list.append(ref) reference_points = torch.cat(reference_points_list, 1) reference_points = reference_points[:, :, None] * valid_ratios[:, None]
return reference_points
def _prepare_multilevel_features(self, srcs, masks, pos_embeds): assert ( len(srcs) == self.num_feature_levels ), "mismatch between expected and received # of feature levels"
src_flatten = [] mask_flatten = [] lvl_pos_embed_flatten = [] spatial_shapes = [] has_mask = masks is not None and masks[0] is not None for lvl, (src, mask, pos_embed) in enumerate(zip(srcs, masks, pos_embeds)): bs, c, h, w = src.shape spatial_shape = (h, w) spatial_shapes.append(spatial_shape)
src = src.flatten(2).transpose(1, 2) # bs, hw, c if has_mask: mask = mask.flatten(1) pos_embed = pos_embed.flatten(2).transpose(1, 2) # bs, hw, c if self.level_embed is not None: lvl_pos_embed = pos_embed + self.level_embed[lvl].view(1, 1, -1) else: lvl_pos_embed = pos_embed lvl_pos_embed_flatten.append(lvl_pos_embed) src_flatten.append(src) if has_mask: mask_flatten.append(mask) src_flatten = torch.cat(src_flatten, 1) # bs, \sum{hxw}, c mask_flatten = torch.cat(mask_flatten, 1) if has_mask else None # bs, \sum{hxw} lvl_pos_embed_flatten = torch.cat(lvl_pos_embed_flatten, 1) # bs, \sum{hxw}, c spatial_shapes = torch.tensor( spatial_shapes, dtype=torch.long, device=src_flatten.device ) level_start_index = torch.cat( ( spatial_shapes.new_zeros((1,)), spatial_shapes.prod(1).cumsum(0)[:-1], ) ) if has_mask: valid_ratios = torch.stack([get_valid_ratio(m) for m in masks], 1) else: valid_ratios = torch.ones( (src_flatten.shape[0], self.num_feature_levels, 2), device=src_flatten.device, )
return ( src_flatten, mask_flatten, lvl_pos_embed_flatten, level_start_index, valid_ratios, spatial_shapes, )
def forward( self, src: List[Tensor], src_key_padding_masks: Optional[List[Tensor]] = None, pos: Optional[List[Tensor]] = None, prompt: Optional[Tensor] = None, prompt_key_padding_mask: Optional[Tensor] = None, encoder_extra_kwargs: Optional[Dict] = None, ) -> Tuple[Tensor, Optional[Tensor], Tensor, Tensor, Tensor, Tensor]: """ Process multi-level features through the transformer encoder.
Args: src: List of multi-level features, each with shape (batch_size, channels, height, width) src_key_padding_masks: List of padding masks for each feature level, each with shape (batch_size, height, width) pos: List of positional embeddings for each feature level, each with shape (batch_size, channels, height, width) prompt: Optional text/prompt features to attend to, with shape (seq_len, batch_size, d_model) prompt_key_padding_mask: Optional padding mask for prompt, with shape (batch_size, seq_len) encoder_extra_kwargs: Optional additional arguments to pass to each encoder layer
Returns: A tuple containing: - output: Processed features with shape (seq_len, batch_size, d_model) - key_padding_masks_flatten: Flattened padding masks - lvl_pos_embed_flatten: Flattened positional embeddings - level_start_index: Starting indices for each feature level - spatial_shapes: Spatial dimensions of each feature level - valid_ratios: Valid ratios for each feature level """ assert ( len(src) == self.num_feature_levels ), "must be equal to num_feature_levels" if src_key_padding_masks is not None: assert len(src_key_padding_masks) == self.num_feature_levels if pos is not None: assert len(pos) == self.num_feature_levels # Flatten multilevel feats and add level pos embeds ( src_flatten, key_padding_masks_flatten, lvl_pos_embed_flatten, level_start_index, valid_ratios, spatial_shapes, ) = self._prepare_multilevel_features(src, src_key_padding_masks, pos)
reference_points = self.get_reference_points( spatial_shapes, valid_ratios, device=src_flatten.device )
output = src_flatten for layer in self.layers: layer_kwargs = {}
assert isinstance(layer, TransformerEncoderLayer) layer_kwargs["memory"] = prompt layer_kwargs["memory_key_padding_mask"] = prompt_key_padding_mask layer_kwargs["query_pos"] = lvl_pos_embed_flatten layer_kwargs["tgt"] = output layer_kwargs["tgt_key_padding_mask"] = key_padding_masks_flatten
if self.training: assert self.use_act_checkpoint, "activation ckpt not enabled in encoder" if encoder_extra_kwargs is not None: layer_kwargs.update(encoder_extra_kwargs) output = activation_ckpt_wrapper(layer)( **layer_kwargs, act_ckpt_enable=self.training and self.use_act_checkpoint, ) # return as seq first return ( output.transpose(0, 1), ( key_padding_masks_flatten.transpose(0, 1) if key_padding_masks_flatten is not None else None ), lvl_pos_embed_flatten.transpose(0, 1), level_start_index, spatial_shapes, valid_ratios, )
class TransformerEncoderFusion(TransformerEncoder): """ Transformer encoder that fuses text and image features.
This encoder extends TransformerEncoder to handle both text and image features, with the ability to add pooled text features to image features for better cross-modal fusion. It supports torch.compile for performance optimization.
Args: layer: The encoder layer to be stacked multiple times num_layers: Number of encoder layers to stack d_model: Model dimension/hidden size num_feature_levels: Number of feature levels to process add_pooled_text_to_img_feat: Whether to add pooled text features to image features pool_text_with_mask: Whether to use the mask when pooling text features compile_mode: Mode for torch.compile, or None to disable compilation **kwargs: Additional arguments to pass to the parent class """
def __init__( self, layer: nn.Module, num_layers: int, d_model: int, num_feature_levels: int, add_pooled_text_to_img_feat: bool = True, pool_text_with_mask: bool = False, compile_mode: Optional[str] = None, **kwargs, ): super().__init__( layer, num_layers, d_model, num_feature_levels, **kwargs, ) self.add_pooled_text_to_img_feat = add_pooled_text_to_img_feat if self.add_pooled_text_to_img_feat: self.text_pooling_proj = nn.Linear(d_model, d_model) self.pool_text_with_mask = pool_text_with_mask if compile_mode is not None: self.forward = torch.compile( self.forward, mode=compile_mode, fullgraph=True )
@staticmethod def get_reference_points(spatial_shapes, valid_ratios, device): # Not needed here return None
def forward( self, src: List[Tensor], prompt: Tensor, src_key_padding_mask: Optional[List[Tensor]] = None, src_pos: Optional[List[Tensor]] = None, prompt_key_padding_mask: Optional[Tensor] = None, prompt_pos: Optional[Tensor] = None, feat_sizes: Optional[List[int]] = None, encoder_extra_kwargs: Optional[Dict] = None, ): # Restore spatial shapes of vision bs = src[0].shape[1] # seq first if feat_sizes is not None: assert len(feat_sizes) == len(src) if src_key_padding_mask is None: src_key_padding_mask = [None] * len(src) for i, (h, w) in enumerate(feat_sizes): src[i] = src[i].reshape(h, w, bs, -1).permute(2, 3, 0, 1) src_pos[i] = src_pos[i].reshape(h, w, bs, -1).permute(2, 3, 0, 1) src_key_padding_mask[i] = ( src_key_padding_mask[i].reshape(h, w, bs).permute(2, 0, 1) if src_key_padding_mask[i] is not None else None ) else: assert all( x.dim == 4 for x in src ), "expected list of (bs, c, h, w) tensors"
if self.add_pooled_text_to_img_feat: # Fusion: Add mean pooled text to image features pooled_text = pool_text_feat( prompt, prompt_key_padding_mask, self.pool_text_with_mask ) pooled_text = self.text_pooling_proj(pooled_text)[ ..., None, None ] # prompt is seq first src = [x.add_(pooled_text) for x in src]
( out, key_padding_masks_flatten, lvl_pos_embed_flatten, level_start_index, spatial_shapes, valid_ratios, ) = super().forward( src, src_key_padding_masks=src_key_padding_mask, pos=src_pos, prompt=prompt.transpose(0, 1), prompt_key_padding_mask=prompt_key_padding_mask, encoder_extra_kwargs=encoder_extra_kwargs, )
return { "memory": out, "padding_mask": key_padding_masks_flatten, "pos_embed": lvl_pos_embed_flatten, "memory_text": prompt, "level_start_index": level_start_index, "spatial_shapes": spatial_shapes, "valid_ratios": valid_ratios, }
def pool_text_feat(prompt, prompt_mask, pool_with_mask): # prompt has shape (seq, bs, dim) if not pool_with_mask: return prompt.mean(dim=0)
# prompt_mask has shape (bs, seq), where False is valid and True is padding assert prompt_mask.dim() == 2 # is_valid has shape (seq, bs, 1), where 1 is valid and 0 is padding is_valid = (~prompt_mask).float().permute(1, 0)[..., None] # num_valid has shape (bs, 1) num_valid = torch.clamp(torch.sum(is_valid, dim=0), min=1.0)
# mean pool over all the valid tokens pooled_text = (prompt * is_valid).sum(dim=0) / num_valid return pooled_text123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323# Copyright (c) Meta Platforms, Inc. and affiliates. All Rights Reserved
import mathfrom typing import Dict, List, Optional
import torchimport torch.nn as nnimport torch.nn.functional as Fimport torch.utils.checkpoint as checkpoint
from .model_misc import MLP
class LinearPresenceHead(nn.Sequential): def __init__(self, d_model): # a hack to make `LinearPresenceHead` compatible with old checkpoints super().__init__(nn.Identity(), nn.Identity(), nn.Linear(d_model, 1))
def forward(self, hs, prompt, prompt_mask): return super().forward(hs)
class MaskPredictor(nn.Module): def __init__(self, hidden_dim, mask_dim): super().__init__() self.mask_embed = MLP(hidden_dim, hidden_dim, mask_dim, 3)
def forward(self, obj_queries, pixel_embed): if len(obj_queries.shape) == 3: if pixel_embed.ndim == 3: # batch size was omitted mask_preds = torch.einsum( "bqc,chw->bqhw", self.mask_embed(obj_queries), pixel_embed ) else: mask_preds = torch.einsum( "bqc,bchw->bqhw", self.mask_embed(obj_queries), pixel_embed ) else: # Assumed to have aux masks if pixel_embed.ndim == 3: # batch size was omitted mask_preds = torch.einsum( "lbqc,chw->lbqhw", self.mask_embed(obj_queries), pixel_embed ) else: mask_preds = torch.einsum( "lbqc,bchw->lbqhw", self.mask_embed(obj_queries), pixel_embed )
return mask_preds
class SegmentationHead(nn.Module): def __init__( self, hidden_dim, upsampling_stages, use_encoder_inputs=False, aux_masks=False, no_dec=False, pixel_decoder=None, act_ckpt=False, shared_conv=False, compile_mode_pixel_decoder=None, ): super().__init__() self.use_encoder_inputs = use_encoder_inputs self.aux_masks = aux_masks if pixel_decoder is not None: self.pixel_decoder = pixel_decoder else: self.pixel_decoder = PixelDecoder( hidden_dim, upsampling_stages, shared_conv=shared_conv, compile_mode=compile_mode_pixel_decoder, ) self.no_dec = no_dec if no_dec: self.mask_predictor = nn.Conv2d( hidden_dim, 1, kernel_size=3, stride=1, padding=1 ) else: self.mask_predictor = MaskPredictor(hidden_dim, mask_dim=hidden_dim)
self.act_ckpt = act_ckpt
# used to update the output dictionary self.instance_keys = ["pred_masks"]
@property def device(self): self._device = getattr(self, "_device", None) or next(self.parameters()).device return self._device
def to(self, *args, **kwargs): # clear cached _device in case the model is moved to a different device self._device = None return super().to(*args, **kwargs)
def _embed_pixels( self, backbone_feats: List[torch.Tensor], image_ids, encoder_hidden_states, ) -> torch.Tensor: feature_device = backbone_feats[0].device # features could be on CPU model_device = self.device image_ids_ = image_ids.to(feature_device) if self.use_encoder_inputs: if backbone_feats[0].shape[0] > 1: # For bs > 1, we construct the per query backbone features backbone_visual_feats = [] for feat in backbone_feats: # Copy the img features per query (pixel decoder won't share img feats) backbone_visual_feats.append(feat[image_ids_, ...].to(model_device)) else: # Bs=1, we rely on broadcasting for query-based processing backbone_visual_feats = [bb_feat.clone() for bb_feat in backbone_feats] # Extract visual embeddings encoder_hidden_states = encoder_hidden_states.permute(1, 2, 0) spatial_dim = math.prod(backbone_feats[-1].shape[-2:]) encoder_visual_embed = encoder_hidden_states[..., :spatial_dim].reshape( -1, *backbone_feats[-1].shape[1:] )
backbone_visual_feats[-1] = encoder_visual_embed if self.act_ckpt: pixel_embed = checkpoint.checkpoint( self.pixel_decoder, backbone_visual_feats, use_reentrant=False ) else: pixel_embed = self.pixel_decoder(backbone_visual_feats) else: backbone_feats = [x.to(model_device) for x in backbone_feats] pixel_embed = self.pixel_decoder(backbone_feats) if pixel_embed.shape[0] == 1: # For batch_size=1 training, we can avoid the indexing to save memory pixel_embed = pixel_embed.squeeze(0) else: pixel_embed = pixel_embed[image_ids, ...] return pixel_embed
def forward( self, backbone_feats: List[torch.Tensor], obj_queries: torch.Tensor, image_ids, encoder_hidden_states: Optional[torch.Tensor] = None, **kwargs, ) -> Dict[str, torch.Tensor]: if self.use_encoder_inputs: assert encoder_hidden_states is not None
pixel_embed = self._embed_pixels( backbone_feats=backbone_feats, image_ids=image_ids, encoder_hidden_states=encoder_hidden_states, )
if self.no_dec: mask_pred = self.mask_predictor(pixel_embed) elif self.aux_masks: mask_pred = self.mask_predictor(obj_queries, pixel_embed) else: mask_pred = self.mask_predictor(obj_queries[-1], pixel_embed)
return {"pred_masks": mask_pred}
class PixelDecoder(nn.Module): def __init__( self, hidden_dim, num_upsampling_stages, interpolation_mode="nearest", shared_conv=False, compile_mode=None, ): super().__init__() self.hidden_dim = hidden_dim self.num_upsampling_stages = num_upsampling_stages self.interpolation_mode = interpolation_mode conv_layers = [] norms = [] num_convs = 1 if shared_conv else num_upsampling_stages for _ in range(num_convs): conv_layers.append(nn.Conv2d(self.hidden_dim, self.hidden_dim, 3, 1, 1)) norms.append(nn.GroupNorm(8, self.hidden_dim))
self.conv_layers = nn.ModuleList(conv_layers) self.norms = nn.ModuleList(norms) self.shared_conv = shared_conv self.out_dim = self.conv_layers[-1].out_channels if compile_mode is not None: self.forward = torch.compile( self.forward, mode=compile_mode, dynamic=True, fullgraph=True ) # Needed to make checkpointing happy. But we don't know if the module is checkpointed, so we disable it by default. torch._dynamo.config.optimize_ddp = False
def forward(self, backbone_feats: List[torch.Tensor]): # Assumes backbone features are already projected (C == hidden dim)
prev_fpn = backbone_feats[-1] fpn_feats = backbone_feats[:-1] for layer_idx, bb_feat in enumerate(fpn_feats[::-1]): curr_fpn = bb_feat prev_fpn = curr_fpn + F.interpolate( prev_fpn, size=curr_fpn.shape[-2:], mode=self.interpolation_mode ) if self.shared_conv: # only one conv layer layer_idx = 0 prev_fpn = self.conv_layers[layer_idx](prev_fpn) prev_fpn = F.relu(self.norms[layer_idx](prev_fpn))
return prev_fpn
class UniversalSegmentationHead(SegmentationHead): """This module handles semantic+instance segmentation"""
def __init__( self, hidden_dim, upsampling_stages, pixel_decoder, aux_masks=False, no_dec=False, act_ckpt=False, presence_head: bool = False, dot_product_scorer=None, cross_attend_prompt=None, ): super().__init__( hidden_dim=hidden_dim, upsampling_stages=upsampling_stages, use_encoder_inputs=True, aux_masks=aux_masks, no_dec=no_dec, pixel_decoder=pixel_decoder, act_ckpt=act_ckpt, ) self.d_model = hidden_dim
if dot_product_scorer is not None: assert presence_head, "Specifying a dot product scorer without a presence head is likely a mistake"
self.presence_head = None if presence_head: self.presence_head = ( dot_product_scorer if dot_product_scorer is not None else LinearPresenceHead(self.d_model) )
self.cross_attend_prompt = cross_attend_prompt if self.cross_attend_prompt is not None: self.cross_attn_norm = nn.LayerNorm(self.d_model)
self.semantic_seg_head = nn.Conv2d(self.pixel_decoder.out_dim, 1, kernel_size=1) self.instance_seg_head = nn.Conv2d( self.pixel_decoder.out_dim, self.d_model, kernel_size=1 )
def forward( self, backbone_feats: List[torch.Tensor], obj_queries: torch.Tensor, image_ids, encoder_hidden_states: Optional[torch.Tensor] = None, prompt: Optional[torch.Tensor] = None, prompt_mask: Optional[torch.Tensor] = None, **kwargs, ) -> Dict[str, Optional[torch.Tensor]]: assert encoder_hidden_states is not None bs = encoder_hidden_states.shape[1]
if self.cross_attend_prompt is not None: tgt2 = self.cross_attn_norm(encoder_hidden_states) tgt2 = self.cross_attend_prompt( query=tgt2, key=prompt, value=prompt, key_padding_mask=prompt_mask, )[0] encoder_hidden_states = tgt2 + encoder_hidden_states
presence_logit = None if self.presence_head is not None: pooled_enc = encoder_hidden_states.mean(0) presence_logit = ( self.presence_head( pooled_enc.view(1, bs, 1, self.d_model), prompt=prompt, prompt_mask=prompt_mask, ) .squeeze(0) .squeeze(1) )
pixel_embed = self._embed_pixels( backbone_feats=backbone_feats, image_ids=image_ids, encoder_hidden_states=encoder_hidden_states, )
instance_embeds = self.instance_seg_head(pixel_embed)
if self.no_dec: mask_pred = self.mask_predictor(instance_embeds) elif self.aux_masks: mask_pred = self.mask_predictor(obj_queries, instance_embeds) else: mask_pred = self.mask_predictor(obj_queries[-1], instance_embeds)
return { "pred_masks": mask_pred, "semantic_seg": self.semantic_seg_head(pixel_embed), "presence_logit": presence_logit, }123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458# Copyright (c) Meta Platforms, Inc. and affiliates. All Rights Reserved# All rights reserved.
# This source code is licensed under the license found in the# LICENSE file in the root directory of this source tree.
import logging
from typing import List, Optional, Tuple, Union
import numpy as npimport torch
import torch.nn as nnfrom PIL.Image import Image
from sam3.model.sam3_tracker_base import Sam3TrackerBasefrom sam3.model.utils.sam1_utils import SAM2Transforms
# Adapted from https://github.com/facebookresearch/sam2/blob/main/sam2/sam2_image_predictor.pyclass SAM3InteractiveImagePredictor(nn.Module): def __init__( self, sam_model: Sam3TrackerBase, mask_threshold=0.0, max_hole_area=256.0, max_sprinkle_area=0.0, **kwargs, ) -> None: """ Uses SAM-3 to calculate the image embedding for an image, and then allow repeated, efficient mask prediction given prompts.
Arguments: sam_model : The model to use for mask prediction. mask_threshold (float): The threshold to use when converting mask logits to binary masks. Masks are thresholded at 0 by default. max_hole_area (int): If max_hole_area > 0, we fill small holes in up to the maximum area of max_hole_area in low_res_masks. max_sprinkle_area (int): If max_sprinkle_area > 0, we remove small sprinkles up to the maximum area of max_sprinkle_area in low_res_masks. """ super().__init__() self.model = sam_model self._transforms = SAM2Transforms( resolution=self.model.image_size, mask_threshold=mask_threshold, max_hole_area=max_hole_area, max_sprinkle_area=max_sprinkle_area, )
# Predictor state self._is_image_set = False self._features = None self._orig_hw = None # Whether the predictor is set for single image or a batch of images self._is_batch = False
# Predictor config self.mask_threshold = mask_threshold
# Spatial dim for backbone feature maps self._bb_feat_sizes = [ (288, 288), (144, 144), (72, 72), ]
@torch.no_grad() def set_image( self, image: Union[np.ndarray, Image], ) -> None: """ Calculates the image embeddings for the provided image, allowing masks to be predicted with the 'predict' method.
Arguments: image (np.ndarray or PIL Image): The input image to embed in RGB format. The image should be in HWC format if np.ndarray, or WHC format if PIL Image with pixel values in [0, 255]. image_format (str): The color format of the image, in ['RGB', 'BGR']. """ self.reset_predictor() # Transform the image to the form expected by the model if isinstance(image, np.ndarray): logging.info("For numpy array image, we assume (HxWxC) format") self._orig_hw = [image.shape[:2]] elif isinstance(image, Image): w, h = image.size self._orig_hw = [(h, w)] else: raise NotImplementedError("Image format not supported")
input_image = self._transforms(image) input_image = input_image[None, ...].to(self.device)
assert ( len(input_image.shape) == 4 and input_image.shape[1] == 3 ), f"input_image must be of size 1x3xHxW, got {input_image.shape}" logging.info("Computing image embeddings for the provided image...") backbone_out = self.model.forward_image(input_image) ( _, vision_feats, _, _, ) = self.model._prepare_backbone_features(backbone_out) # Add no_mem_embed, which is added to the lowest rest feat. map during training on videos vision_feats[-1] = vision_feats[-1] + self.model.no_mem_embed
feats = [ feat.permute(1, 2, 0).view(1, -1, *feat_size) for feat, feat_size in zip(vision_feats[::-1], self._bb_feat_sizes[::-1]) ][::-1] self._features = {"image_embed": feats[-1], "high_res_feats": feats[:-1]} self._is_image_set = True logging.info("Image embeddings computed.")
@torch.no_grad() def set_image_batch( self, image_list: List[Union[np.ndarray]], ) -> None: """ Calculates the image embeddings for the provided image batch, allowing masks to be predicted with the 'predict_batch' method.
Arguments: image_list (List[np.ndarray]): The input images to embed in RGB format. The image should be in HWC format if np.ndarray with pixel values in [0, 255]. """ self.reset_predictor() assert isinstance(image_list, list) self._orig_hw = [] for image in image_list: assert isinstance( image, np.ndarray ), "Images are expected to be an np.ndarray in RGB format, and of shape HWC" self._orig_hw.append(image.shape[:2]) # Transform the image to the form expected by the model img_batch = self._transforms.forward_batch(image_list) img_batch = img_batch.to(self.device) batch_size = img_batch.shape[0] assert ( len(img_batch.shape) == 4 and img_batch.shape[1] == 3 ), f"img_batch must be of size Bx3xHxW, got {img_batch.shape}" logging.info("Computing image embeddings for the provided images...") backbone_out = self.model.forward_image(img_batch) ( _, vision_feats, _, _, ) = self.model._prepare_backbone_features(backbone_out) # Add no_mem_embed, which is added to the lowest rest feat. map during training on videos vision_feats[-1] = vision_feats[-1] + self.model.no_mem_embed
feats = [ feat.permute(1, 2, 0).view(batch_size, -1, *feat_size) for feat, feat_size in zip(vision_feats[::-1], self._bb_feat_sizes[::-1]) ][::-1] self._features = {"image_embed": feats[-1], "high_res_feats": feats[:-1]} self._is_image_set = True self._is_batch = True logging.info("Image embeddings computed.")
def predict_batch( self, point_coords_batch: List[np.ndarray] = None, point_labels_batch: List[np.ndarray] = None, box_batch: List[np.ndarray] = None, mask_input_batch: List[np.ndarray] = None, multimask_output: bool = True, return_logits: bool = False, normalize_coords=True, ) -> Tuple[List[np.ndarray], List[np.ndarray], List[np.ndarray]]: """This function is very similar to predict(...), however it is used for batched mode, when the model is expected to generate predictions on multiple images. It returns a tuple of lists of masks, ious, and low_res_masks_logits. """ assert self._is_batch, "This function should only be used when in batched mode" if not self._is_image_set: raise RuntimeError( "An image must be set with .set_image_batch(...) before mask prediction." ) num_images = len(self._features["image_embed"]) all_masks = [] all_ious = [] all_low_res_masks = [] for img_idx in range(num_images): # Transform input prompts point_coords = ( point_coords_batch[img_idx] if point_coords_batch is not None else None ) point_labels = ( point_labels_batch[img_idx] if point_labels_batch is not None else None ) box = box_batch[img_idx] if box_batch is not None else None mask_input = ( mask_input_batch[img_idx] if mask_input_batch is not None else None ) mask_input, unnorm_coords, labels, unnorm_box = self._prep_prompts( point_coords, point_labels, box, mask_input, normalize_coords, img_idx=img_idx, ) masks, iou_predictions, low_res_masks = self._predict( unnorm_coords, labels, unnorm_box, mask_input, multimask_output, return_logits=return_logits, img_idx=img_idx, ) masks_np = masks.squeeze(0).float().detach().cpu().numpy() iou_predictions_np = ( iou_predictions.squeeze(0).float().detach().cpu().numpy() ) low_res_masks_np = low_res_masks.squeeze(0).float().detach().cpu().numpy() all_masks.append(masks_np) all_ious.append(iou_predictions_np) all_low_res_masks.append(low_res_masks_np)
return all_masks, all_ious, all_low_res_masks
def predict( self, point_coords: Optional[np.ndarray] = None, point_labels: Optional[np.ndarray] = None, box: Optional[np.ndarray] = None, mask_input: Optional[np.ndarray] = None, multimask_output: bool = True, return_logits: bool = False, normalize_coords=True, ) -> Tuple[np.ndarray, np.ndarray, np.ndarray]: """ Predict masks for the given input prompts, using the currently set image.
Arguments: point_coords (np.ndarray or None): A Nx2 array of point prompts to the model. Each point is in (X,Y) in pixels. point_labels (np.ndarray or None): A length N array of labels for the point prompts. 1 indicates a foreground point and 0 indicates a background point. box (np.ndarray or None): A length 4 array given a box prompt to the model, in XYXY format. mask_input (np.ndarray): A low resolution mask input to the model, typically coming from a previous prediction iteration. Has form 1xHxW, where for SAM, H=W=256. multimask_output (bool): If true, the model will return three masks. For ambiguous input prompts (such as a single click), this will often produce better masks than a single prediction. If only a single mask is needed, the model's predicted quality score can be used to select the best mask. For non-ambiguous prompts, such as multiple input prompts, multimask_output=False can give better results. return_logits (bool): If true, returns un-thresholded masks logits instead of a binary mask. normalize_coords (bool): If true, the point coordinates will be normalized to the range [0,1] and point_coords is expected to be wrt. image dimensions.
Returns: (np.ndarray): The output masks in CxHxW format, where C is the number of masks, and (H, W) is the original image size. (np.ndarray): An array of length C containing the model's predictions for the quality of each mask. (np.ndarray): An array of shape CxHxW, where C is the number of masks and H=W=256. These low resolution logits can be passed to a subsequent iteration as mask input. """ if not self._is_image_set: raise RuntimeError( "An image must be set with .set_image(...) before mask prediction." )
# Transform input prompts
mask_input, unnorm_coords, labels, unnorm_box = self._prep_prompts( point_coords, point_labels, box, mask_input, normalize_coords )
masks, iou_predictions, low_res_masks = self._predict( unnorm_coords, labels, unnorm_box, mask_input, multimask_output, return_logits=return_logits, )
masks_np = masks.squeeze(0).float().detach().cpu().numpy() iou_predictions_np = iou_predictions.squeeze(0).float().detach().cpu().numpy() low_res_masks_np = low_res_masks.squeeze(0).float().detach().cpu().numpy() return masks_np, iou_predictions_np, low_res_masks_np
def _prep_prompts( self, point_coords, point_labels, box, mask_logits, normalize_coords, img_idx=-1 ): unnorm_coords, labels, unnorm_box, mask_input = None, None, None, None if point_coords is not None: assert ( point_labels is not None ), "point_labels must be supplied if point_coords is supplied." point_coords = torch.as_tensor( point_coords, dtype=torch.float, device=self.device ) unnorm_coords = self._transforms.transform_coords( point_coords, normalize=normalize_coords, orig_hw=self._orig_hw[img_idx] ) labels = torch.as_tensor(point_labels, dtype=torch.int, device=self.device) if len(unnorm_coords.shape) == 2: unnorm_coords, labels = unnorm_coords[None, ...], labels[None, ...] if box is not None: box = torch.as_tensor(box, dtype=torch.float, device=self.device) unnorm_box = self._transforms.transform_boxes( box, normalize=normalize_coords, orig_hw=self._orig_hw[img_idx] ) # Bx2x2 if mask_logits is not None: mask_input = torch.as_tensor( mask_logits, dtype=torch.float, device=self.device ) if len(mask_input.shape) == 3: mask_input = mask_input[None, :, :, :] return mask_input, unnorm_coords, labels, unnorm_box
@torch.no_grad() def _predict( self, point_coords: Optional[torch.Tensor], point_labels: Optional[torch.Tensor], boxes: Optional[torch.Tensor] = None, mask_input: Optional[torch.Tensor] = None, multimask_output: bool = True, return_logits: bool = False, img_idx: int = -1, ) -> Tuple[torch.Tensor, torch.Tensor, torch.Tensor]: """ Predict masks for the given input prompts, using the currently set image. Input prompts are batched torch tensors and are expected to already be transformed to the input frame using SAM2Transforms.
Arguments: point_coords (torch.Tensor or None): A BxNx2 array of point prompts to the model. Each point is in (X,Y) in pixels. point_labels (torch.Tensor or None): A BxN array of labels for the point prompts. 1 indicates a foreground point and 0 indicates a background point. boxes (np.ndarray or None): A Bx4 array given a box prompt to the model, in XYXY format. mask_input (np.ndarray): A low resolution mask input to the model, typically coming from a previous prediction iteration. Has form Bx1xHxW, where for SAM, H=W=256. Masks returned by a previous iteration of the predict method do not need further transformation. multimask_output (bool): If true, the model will return three masks. For ambiguous input prompts (such as a single click), this will often produce better masks than a single prediction. If only a single mask is needed, the model's predicted quality score can be used to select the best mask. For non-ambiguous prompts, such as multiple input prompts, multimask_output=False can give better results. return_logits (bool): If true, returns un-thresholded masks logits instead of a binary mask.
Returns: (torch.Tensor): The output masks in BxCxHxW format, where C is the number of masks, and (H, W) is the original image size. (torch.Tensor): An array of shape BxC containing the model's predictions for the quality of each mask. (torch.Tensor): An array of shape BxCxHxW, where C is the number of masks and H=W=256. These low res logits can be passed to a subsequent iteration as mask input. """ if not self._is_image_set: raise RuntimeError( "An image must be set with .set_image(...) before mask prediction." )
if point_coords is not None: concat_points = (point_coords, point_labels) else: concat_points = None
# Embed prompts if boxes is not None: box_coords = boxes.reshape(-1, 2, 2) box_labels = torch.tensor([[2, 3]], dtype=torch.int, device=boxes.device) box_labels = box_labels.repeat(boxes.size(0), 1) # we merge "boxes" and "points" into a single "concat_points" input (where # boxes are added at the beginning) to sam_prompt_encoder if concat_points is not None: concat_coords = torch.cat([box_coords, concat_points[0]], dim=1) concat_labels = torch.cat([box_labels, concat_points[1]], dim=1) concat_points = (concat_coords, concat_labels) else: concat_points = (box_coords, box_labels)
sparse_embeddings, dense_embeddings = self.model.sam_prompt_encoder( points=concat_points, boxes=None, masks=mask_input, )
# Predict masks batched_mode = ( concat_points is not None and concat_points[0].shape[0] > 1 ) # multi object prediction high_res_features = [ feat_level[img_idx].unsqueeze(0) for feat_level in self._features["high_res_feats"] ] low_res_masks, iou_predictions, _, _ = self.model.sam_mask_decoder( image_embeddings=self._features["image_embed"][img_idx].unsqueeze(0), image_pe=self.model.sam_prompt_encoder.get_dense_pe(), sparse_prompt_embeddings=sparse_embeddings, dense_prompt_embeddings=dense_embeddings, multimask_output=multimask_output, repeat_image=batched_mode, high_res_features=high_res_features, )
# Upscale the masks to the original image resolution masks = self._transforms.postprocess_masks( low_res_masks, self._orig_hw[img_idx] ) low_res_masks = torch.clamp(low_res_masks, -32.0, 32.0) if not return_logits: masks = masks > self.mask_threshold
return masks, iou_predictions, low_res_masks
def get_image_embedding(self) -> torch.Tensor: """ Returns the image embeddings for the currently set image, with shape 1xCxHxW, where C is the embedding dimension and (H,W) are the embedding spatial dimension of SAM (typically C=256, H=W=64). """ if not self._is_image_set: raise RuntimeError( "An image must be set with .set_image(...) to generate an embedding." ) assert ( self._features is not None ), "Features must exist if an image has been set." return self._features["image_embed"]
@property def device(self) -> torch.device: return self.model.device
def reset_predictor(self) -> None: """ Resets the image embeddings and other state variables. """ self._is_image_set = False self._features = None self._orig_hw = None self._is_batch = False123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222# Copyright (c) Meta Platforms, Inc. and affiliates. All Rights Reservedfrom typing import Dict, List
import numpy as npimport PILimport torch
from sam3.model import box_ops
from sam3.model.data_misc import FindStage, interpolatefrom torchvision.transforms import v2
class Sam3Processor: """ """
def __init__(self, model, resolution=1008, device="cuda", confidence_threshold=0.5): self.model = model self.resolution = resolution self.device = device self.transform = v2.Compose( [ v2.ToDtype(torch.uint8, scale=True), v2.Resize(size=(resolution, resolution)), v2.ToDtype(torch.float32, scale=True), v2.Normalize(mean=[0.5, 0.5, 0.5], std=[0.5, 0.5, 0.5]), ] ) self.confidence_threshold = confidence_threshold
self.find_stage = FindStage( img_ids=torch.tensor([0], device=device, dtype=torch.long), text_ids=torch.tensor([0], device=device, dtype=torch.long), input_boxes=None, input_boxes_mask=None, input_boxes_label=None, input_points=None, input_points_mask=None, )
@torch.inference_mode() def set_image(self, image, state=None): """Sets the image on which we want to do predictions.""" if state is None: state = {}
if isinstance(image, PIL.Image.Image): width, height = image.size elif isinstance(image, (torch.Tensor, np.ndarray)): height, width = image.shape[-2:] else: raise ValueError("Image must be a PIL image or a tensor")
image = v2.functional.to_image(image).to(self.device) image = self.transform(image).unsqueeze(0)
state["original_height"] = height state["original_width"] = width state["backbone_out"] = self.model.backbone.forward_image(image) inst_interactivity_en = self.model.inst_interactive_predictor is not None if inst_interactivity_en and "sam2_backbone_out" in state["backbone_out"]: sam2_backbone_out = state["backbone_out"]["sam2_backbone_out"] sam2_backbone_out["backbone_fpn"][0] = ( self.model.inst_interactive_predictor.model.sam_mask_decoder.conv_s0( sam2_backbone_out["backbone_fpn"][0] ) ) sam2_backbone_out["backbone_fpn"][1] = ( self.model.inst_interactive_predictor.model.sam_mask_decoder.conv_s1( sam2_backbone_out["backbone_fpn"][1] ) ) return state
@torch.inference_mode() def set_image_batch(self, images: List[np.ndarray], state=None): """Sets the image batch on which we want to do predictions.""" if state is None: state = {}
if not isinstance(images, list): raise ValueError("Images must be a list of PIL images or tensors") assert len(images) > 0, "Images list must not be empty" assert isinstance( images[0], PIL.Image.Image ), "Images must be a list of PIL images"
state["original_heights"] = [image.height for image in images] state["original_widths"] = [image.width for image in images]
images = [ self.transform(v2.functional.to_image(image).to(self.device)) for image in images ] images = torch.stack(images, dim=0) state["backbone_out"] = self.model.backbone.forward_image(images) inst_interactivity_en = self.model.inst_interactive_predictor is not None if inst_interactivity_en and "sam2_backbone_out" in state["backbone_out"]: sam2_backbone_out = state["backbone_out"]["sam2_backbone_out"] sam2_backbone_out["backbone_fpn"][0] = ( self.model.inst_interactive_predictor.model.sam_mask_decoder.conv_s0( sam2_backbone_out["backbone_fpn"][0] ) ) sam2_backbone_out["backbone_fpn"][1] = ( self.model.inst_interactive_predictor.model.sam_mask_decoder.conv_s1( sam2_backbone_out["backbone_fpn"][1] ) ) return state
@torch.inference_mode() def set_text_prompt(self, prompt: str, state: Dict): """Sets the text prompt and run the inference"""
if "backbone_out" not in state: raise ValueError("You must call set_image before set_text_prompt")
text_outputs = self.model.backbone.forward_text([prompt], device=self.device) # will erase the previous text prompt if any state["backbone_out"].update(text_outputs) if "geometric_prompt" not in state: state["geometric_prompt"] = self.model._get_dummy_prompt()
return self._forward_grounding(state)
@torch.inference_mode() def add_geometric_prompt(self, box: List, label: bool, state: Dict): """Adds a box prompt and run the inference. The image needs to be set, but not necessarily the text prompt. The box is assumed to be in [center_x, center_y, width, height] format and normalized in [0, 1] range. The label is True for a positive box, False for a negative box. """ if "backbone_out" not in state: raise ValueError("You must call set_image before set_text_prompt")
if "language_features" not in state["backbone_out"]: # Looks like we don't have a text prompt yet. This is allowed, but we need to set the text prompt to "visual" for the model to rely only on the geometric prompt dummy_text_outputs = self.model.backbone.forward_text( ["visual"], device=self.device ) state["backbone_out"].update(dummy_text_outputs)
if "geometric_prompt" not in state: state["geometric_prompt"] = self.model._get_dummy_prompt()
# adding a batch and sequence dimension boxes = torch.tensor(box, device=self.device, dtype=torch.float32).view(1, 1, 4) labels = torch.tensor([label], device=self.device, dtype=torch.bool).view(1, 1) state["geometric_prompt"].append_boxes(boxes, labels)
return self._forward_grounding(state)
def reset_all_prompts(self, state: Dict): """Removes all the prompts and results""" if "backbone_out" in state: backbone_keys_to_del = [ "language_features", "language_mask", "language_embeds", ] for key in backbone_keys_to_del: if key in state["backbone_out"]: del state["backbone_out"][key]
keys_to_del = ["geometric_prompt", "boxes", "masks", "masks_logits", "scores"] for key in keys_to_del: if key in state: del state[key]
@torch.inference_mode() def set_confidence_threshold(self, threshold: float, state=None): """Sets the confidence threshold for the masks""" self.confidence_threshold = threshold if state is not None and "boxes" in state: # we need to filter the boxes again # In principle we could do this more efficiently since we would only need # to rerun the heads. But this is simpler and not too inefficient return self._forward_grounding(state) return state
@torch.inference_mode() def _forward_grounding(self, state: Dict): outputs = self.model.forward_grounding( backbone_out=state["backbone_out"], find_input=self.find_stage, geometric_prompt=state["geometric_prompt"], find_target=None, )
out_bbox = outputs["pred_boxes"] out_logits = outputs["pred_logits"] out_masks = outputs["pred_masks"] out_probs = out_logits.sigmoid() presence_score = outputs["presence_logit_dec"].sigmoid().unsqueeze(1) out_probs = (out_probs * presence_score).squeeze(-1)
keep = out_probs > self.confidence_threshold out_probs = out_probs[keep] out_masks = out_masks[keep] out_bbox = out_bbox[keep]
# convert to [x0, y0, x1, y1] format boxes = box_ops.box_cxcywh_to_xyxy(out_bbox)
img_h = state["original_height"] img_w = state["original_width"] scale_fct = torch.tensor([img_w, img_h, img_w, img_h]).to(self.device) boxes = boxes * scale_fct[None, :]
out_masks = interpolate( out_masks.unsqueeze(1), (img_h, img_w), mode="bilinear", align_corners=False, ).sigmoid()
state["masks_logits"] = out_masks state["masks"] = out_masks > 0.5 state["boxes"] = boxes state["scores"] = out_probs return state123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427# Copyright (c) Meta Platforms, Inc. and affiliates. All Rights Reserved
import numpy as npimport torchimport torch.nn.functional as Ffrom numpy.typing import NDArray
from sam3.model.edt import edt_triton
def sample_box_points( masks: torch.Tensor, noise: float = 0.1, # SAM default noise_bound: int = 20, # SAM default top_left_label: int = 2, bottom_right_label: int = 3,) -> tuple[NDArray, NDArray]: """ Sample a noised version of the top left and bottom right corners of a given `bbox`
Inputs: - masks: [B, 1, H, W] tensor - noise: noise as a fraction of box width and height, dtype=float - noise_bound: maximum amount of noise (in pure pixels), dtype=int
Returns: - box_coords: [B, num_pt, 2], contains (x, y) coordinates of top left and bottom right box corners, dtype=torch.float - box_labels: [B, num_pt], label 2 is reserverd for top left and 3 for bottom right corners, dtype=torch.int32 """ device = masks.device box_coords = mask_to_box(masks) B, _, H, W = masks.shape box_labels = torch.tensor( [top_left_label, bottom_right_label], dtype=torch.int, device=device ).repeat(B) if noise > 0.0: if not isinstance(noise_bound, torch.Tensor): noise_bound = torch.tensor(noise_bound, device=device) bbox_w = box_coords[..., 2] - box_coords[..., 0] bbox_h = box_coords[..., 3] - box_coords[..., 1] max_dx = torch.min(bbox_w * noise, noise_bound) max_dy = torch.min(bbox_h * noise, noise_bound) box_noise = 2 * torch.rand(B, 1, 4, device=device) - 1 box_noise = box_noise * torch.stack((max_dx, max_dy, max_dx, max_dy), dim=-1)
box_coords = box_coords + box_noise img_bounds = ( torch.tensor([W, H, W, H], device=device) - 1 ) # uncentered pixel coords box_coords.clamp_(torch.zeros_like(img_bounds), img_bounds) # In place clamping
box_coords = box_coords.reshape(-1, 2, 2) # always 2 points box_labels = box_labels.reshape(-1, 2) return box_coords, box_labels
def mask_to_box(masks: torch.Tensor): """ compute bounding box given an input mask
Inputs: - masks: [B, 1, H, W] tensor
Returns: - box_coords: [B, 1, 4], contains (x, y) coordinates of top left and bottom right box corners, dtype=torch.Tensor """ B, _, h, w = masks.shape device = masks.device mask_area = masks.sum(dim=(-1, -2)) xs = torch.arange(w, device=device, dtype=torch.int32) ys = torch.arange(h, device=device, dtype=torch.int32) grid_xs, grid_ys = torch.meshgrid(xs, ys, indexing="xy") grid_xs = grid_xs[None, None, ...].expand(B, 1, h, w) grid_ys = grid_ys[None, None, ...].expand(B, 1, h, w) min_xs, _ = torch.min(torch.where(masks, grid_xs, w).flatten(-2), dim=-1) max_xs, _ = torch.max(torch.where(masks, grid_xs, -1).flatten(-2), dim=-1) min_ys, _ = torch.min(torch.where(masks, grid_ys, h).flatten(-2), dim=-1) max_ys, _ = torch.max(torch.where(masks, grid_ys, -1).flatten(-2), dim=-1) bbox_coords = torch.stack((min_xs, min_ys, max_xs, max_ys), dim=-1) bbox_coords = torch.where( mask_area[..., None] > 0, bbox_coords, torch.zeros_like(bbox_coords) ) return bbox_coords
def sample_random_points_from_errors(gt_masks, pred_masks, num_pt=1): """ Sample `num_pt` random points (along with their labels) independently from the error regions.
Inputs: - gt_masks: [B, 1, H_im, W_im] masks, dtype=torch.bool - pred_masks: [B, 1, H_im, W_im] masks, dtype=torch.bool or None - num_pt: int, number of points to sample independently for each of the B error maps
Outputs: - points: [B, num_pt, 2], dtype=torch.float, contains (x, y) coordinates of each sampled point - labels: [B, num_pt], dtype=torch.int32, where 1 means positive clicks and 0 means negative clicks """ if pred_masks is None: # if pred_masks is not provided, treat it as empty pred_masks = torch.zeros_like(gt_masks) assert gt_masks.dtype == torch.bool and gt_masks.size(1) == 1 assert pred_masks.dtype == torch.bool and pred_masks.shape == gt_masks.shape assert num_pt >= 0
B, _, H_im, W_im = gt_masks.shape device = gt_masks.device
# false positive region, a new point sampled in this region should have # negative label to correct the FP error fp_masks = ~gt_masks & pred_masks # false negative region, a new point sampled in this region should have # positive label to correct the FN error fn_masks = gt_masks & ~pred_masks # whether the prediction completely match the ground-truth on each mask all_correct = torch.all((gt_masks == pred_masks).flatten(2), dim=2) all_correct = all_correct[..., None, None]
# channel 0 is FP map, while channel 1 is FN map pts_noise = torch.rand(B, num_pt, H_im, W_im, 2, device=device) # sample a negative new click from FP region or a positive new click # from FN region, depend on where the maximum falls, # and in case the predictions are all correct (no FP or FN), we just # sample a negative click from the background region pts_noise[..., 0] *= fp_masks | (all_correct & ~gt_masks) pts_noise[..., 1] *= fn_masks pts_idx = pts_noise.flatten(2).argmax(dim=2) labels = (pts_idx % 2).to(torch.int32) pts_idx = pts_idx // 2 pts_x = pts_idx % W_im pts_y = pts_idx // W_im points = torch.stack([pts_x, pts_y], dim=2).to(torch.float) return points, labels
def sample_one_point_from_error_center(gt_masks, pred_masks, padding=True): """ Sample 1 random point (along with its label) from the center of each error region, that is, the point with the largest distance to the boundary of each error region. This is the RITM sampling method from https://github.com/saic-vul/ritm_interactive_segmentation/blob/master/isegm/inference/clicker.py
Inputs: - gt_masks: [B, 1, H_im, W_im] masks, dtype=torch.bool - pred_masks: [B, 1, H_im, W_im] masks, dtype=torch.bool or None - padding: if True, pad with boundary of 1 px for distance transform
Outputs: - points: [B, 1, 2], dtype=torch.float, contains (x, y) coordinates of each sampled point - labels: [B, 1], dtype=torch.int32, where 1 means positive clicks and 0 means negative clicks """ if pred_masks is None: pred_masks = torch.zeros_like(gt_masks) assert gt_masks.dtype == torch.bool and gt_masks.size(1) == 1 assert pred_masks.dtype == torch.bool and pred_masks.shape == gt_masks.shape
B, _, H, W = gt_masks.shape
# false positive region, a new point sampled in this region should have # negative label to correct the FP error fp_masks = (~gt_masks & pred_masks).squeeze(1) # false negative region, a new point sampled in this region should have # positive label to correct the FN error fn_masks = (gt_masks & ~pred_masks).squeeze(1)
if padding: padded_fp_masks = torch.zeros( B, H + 2, W + 2, dtype=fp_masks.dtype, device=fp_masks.device ) padded_fp_masks[:, 1 : H + 1, 1 : W + 1] = fp_masks padded_fn_masks = torch.zeros( B, H + 2, W + 2, dtype=fp_masks.dtype, device=fp_masks.device ) padded_fn_masks[:, 1 : H + 1, 1 : W + 1] = fn_masks else: padded_fp_masks = fp_masks padded_fn_masks = fn_masks
fn_mask_dt = edt_triton(padded_fn_masks) fp_mask_dt = edt_triton(padded_fp_masks) if padding: fn_mask_dt = fn_mask_dt[:, 1:-1, 1:-1] fp_mask_dt = fp_mask_dt[:, 1:-1, 1:-1]
fn_max, fn_argmax = fn_mask_dt.reshape(B, -1).max(dim=-1) fp_max, fp_argmax = fp_mask_dt.reshape(B, -1).max(dim=-1) is_positive = fn_max > fp_max chosen = torch.where(is_positive, fn_argmax, fp_argmax) points_x = chosen % W points_y = chosen // W
labels = is_positive.long() points = torch.stack([points_x, points_y], -1) return points.unsqueeze(1), labels.unsqueeze(1)
def sample_one_point_from_error_center_slow(gt_masks, pred_masks, padding=True): """ Sample 1 random point (along with its label) from the center of each error region, that is, the point with the largest distance to the boundary of each error region. This is the RITM sampling method from https://github.com/saic-vul/ritm_interactive_segmentation/blob/master/isegm/inference/clicker.py
Inputs: - gt_masks: [B, 1, H_im, W_im] masks, dtype=torch.bool - pred_masks: [B, 1, H_im, W_im] masks, dtype=torch.bool or None - padding: if True, pad with boundary of 1 px for distance transform
Outputs: - points: [B, 1, 2], dtype=torch.float, contains (x, y) coordinates of each sampled point - labels: [B, 1], dtype=torch.int32, where 1 means positive clicks and 0 means negative clicks """ import cv2 # delay OpenCV import to avoid unnecessary dependency
if pred_masks is None: pred_masks = torch.zeros_like(gt_masks) assert gt_masks.dtype == torch.bool and gt_masks.size(1) == 1 assert pred_masks.dtype == torch.bool and pred_masks.shape == gt_masks.shape
B, _, _, W_im = gt_masks.shape device = gt_masks.device
# false positive region, a new point sampled in this region should have # negative label to correct the FP error fp_masks = ~gt_masks & pred_masks # false negative region, a new point sampled in this region should have # positive label to correct the FN error fn_masks = gt_masks & ~pred_masks
fp_masks = fp_masks.cpu().numpy() fn_masks = fn_masks.cpu().numpy() points = torch.zeros(B, 1, 2, dtype=torch.float) labels = torch.ones(B, 1, dtype=torch.int32) for b in range(B): fn_mask = fn_masks[b, 0] fp_mask = fp_masks[b, 0] if padding: fn_mask = np.pad(fn_mask, ((1, 1), (1, 1)), "constant") fp_mask = np.pad(fp_mask, ((1, 1), (1, 1)), "constant") # compute the distance of each point in FN/FP region to its boundary fn_mask_dt = cv2.distanceTransform(fn_mask.astype(np.uint8), cv2.DIST_L2, 0) fp_mask_dt = cv2.distanceTransform(fp_mask.astype(np.uint8), cv2.DIST_L2, 0) if padding: fn_mask_dt = fn_mask_dt[1:-1, 1:-1] fp_mask_dt = fp_mask_dt[1:-1, 1:-1]
# take the point in FN/FP region with the largest distance to its boundary fn_mask_dt_flat = fn_mask_dt.reshape(-1) fp_mask_dt_flat = fp_mask_dt.reshape(-1) fn_argmax = np.argmax(fn_mask_dt_flat) fp_argmax = np.argmax(fp_mask_dt_flat) is_positive = fn_mask_dt_flat[fn_argmax] > fp_mask_dt_flat[fp_argmax] pt_idx = fn_argmax if is_positive else fp_argmax points[b, 0, 0] = pt_idx % W_im # x points[b, 0, 1] = pt_idx // W_im # y labels[b, 0] = int(is_positive)
points = points.to(device) labels = labels.to(device) return points, labels
def get_next_point(gt_masks, pred_masks, method): if method == "uniform": return sample_random_points_from_errors(gt_masks, pred_masks) elif method == "center": return sample_one_point_from_error_center(gt_masks, pred_masks) else: raise ValueError(f"unknown sampling method {method}")
def select_closest_cond_frames( frame_idx, cond_frame_outputs, max_cond_frame_num, keep_first_cond_frame=False): """ Select up to `max_cond_frame_num` conditioning frames from `cond_frame_outputs` that are temporally closest to the current frame at `frame_idx`. Here, we take - a) the closest conditioning frame before `frame_idx` (if any); - b) the closest conditioning frame after `frame_idx` (if any); - c) any other temporally closest conditioning frames until reaching a total of `max_cond_frame_num` conditioning frames.
Outputs: - selected_outputs: selected items (keys & values) from `cond_frame_outputs`. - unselected_outputs: items (keys & values) not selected in `cond_frame_outputs`. """ if max_cond_frame_num == -1 or len(cond_frame_outputs) <= max_cond_frame_num: selected_outputs = cond_frame_outputs unselected_outputs = {} else: assert max_cond_frame_num >= 2, "we should allow using 2+ conditioning frames" selected_outputs = {} if keep_first_cond_frame: idx_first = min( (t for t in cond_frame_outputs if t < frame_idx), default=None ) if idx_first is None: # Maybe we are tracking in reverse idx_first = max( (t for t in cond_frame_outputs if t > frame_idx), default=None ) if idx_first is not None: selected_outputs[idx_first] = cond_frame_outputs[idx_first] # the closest conditioning frame before `frame_idx` (if any) idx_before = max((t for t in cond_frame_outputs if t < frame_idx), default=None) if idx_before is not None: selected_outputs[idx_before] = cond_frame_outputs[idx_before]
# the closest conditioning frame after `frame_idx` (if any) idx_after = min((t for t in cond_frame_outputs if t >= frame_idx), default=None) if idx_after is not None: selected_outputs[idx_after] = cond_frame_outputs[idx_after]
# add other temporally closest conditioning frames until reaching a total # of `max_cond_frame_num` conditioning frames. num_remain = max_cond_frame_num - len(selected_outputs) inds_remain = sorted( (t for t in cond_frame_outputs if t not in selected_outputs), key=lambda x: abs(x - frame_idx), )[:num_remain] selected_outputs.update((t, cond_frame_outputs[t]) for t in inds_remain) unselected_outputs = { t: v for t, v in cond_frame_outputs.items() if t not in selected_outputs }
return selected_outputs, unselected_outputs
def get_1d_sine_pe(pos_inds, dim, temperature=10000): """ Get 1D sine positional embedding as in the original Transformer paper. """ pe_dim = dim // 2 dim_t = torch.arange(pe_dim, dtype=torch.float32, device=pos_inds.device) dim_t = temperature ** (2 * (dim_t // 2) / pe_dim)
pos_embed = pos_inds.unsqueeze(-1) / dim_t pos_embed = torch.cat([pos_embed.sin(), pos_embed.cos()], dim=-1) return pos_embed
def get_best_gt_match_from_multimasks(pred_multimasks, gt_masks, pred_scores=None): """ Get the mask with the best match to GT masks (based on IoU) from pred_multimasks. Optionally, use `pred_scores` to break ties in case all IoUs are zeros. """ assert pred_multimasks.ndim == 4 and gt_masks.ndim == 4 if pred_multimasks.size(1) == 1: return pred_multimasks # only a single mask channel, nothing to select
pred_multimasks_binary = pred_multimasks > 0 area_i = torch.sum(pred_multimasks_binary & gt_masks, dim=(2, 3)).float() area_u = torch.sum(pred_multimasks_binary | gt_masks, dim=(2, 3)).float() ious = area_i / torch.clamp(area_u, min=1.0)
# In case all IoUs are zeros (e.g. because the GT mask is empty), use pred_scores # to break ties and select the best mask if pred_scores is not None: has_nonzero_ious = torch.any(ious > 0).expand_as(ious) scores = torch.where(has_nonzero_ious, ious, pred_scores) else: scores = ious
# Finally, take the best mask prediction (with the highest score) best_scores_inds = torch.argmax(scores, dim=-1) batch_inds = torch.arange(scores.size(0), device=scores.device) best_pred_mask = pred_multimasks[batch_inds, best_scores_inds].unsqueeze(1) return best_pred_mask
def fill_holes_in_mask_scores(mask, max_area, fill_holes=True, remove_sprinkles=True): """ A post processor to fill small holes in mask scores with area under `max_area`. Holes are those small connected components in either background or foreground.
Note that it relies on the "cc_torch" package to find connected components fast. You can install it via the following command (`TORCH_CUDA_ARCH_LIST=8.0` is for A100 GPUs): ``` pip uninstall -y cc_torch; TORCH_CUDA_ARCH_LIST=8.0 9.0 pip install git+https://github.com/ronghanghu/cc_torch ``` Otherwise, it will fallback to a slightly slower triton implementation, or skimage if the tensor is on cpu """
if max_area <= 0: return mask # nothing to fill in this case
if fill_holes: # We remove small connected components in background by changing them to foreground # with a small positive mask score (0.1). mask_bg = mask <= 0 bg_area_thresh = max_area _, areas_bg = _get_connected_components_with_padding(mask_bg) small_components_bg = mask_bg & (areas_bg <= bg_area_thresh) mask = torch.where(small_components_bg, 0.1, mask)
if remove_sprinkles: # We remove small connected components in foreground by changing them to background # with a small negative mask score (-0.1). Here we only remove connected components # whose areas are under both `max_area` and half of the entire mask's area. This # removes sprinkles while avoids filtering out tiny objects that we want to track. mask_fg = mask > 0 fg_area_thresh = torch.sum(mask_fg, dim=(2, 3), keepdim=True, dtype=torch.int32) fg_area_thresh.floor_divide_(2).clamp_(max=max_area) _, areas_fg = _get_connected_components_with_padding(mask_fg) small_components_fg = mask_fg & (areas_fg <= fg_area_thresh) mask = torch.where(small_components_fg, -0.1, mask) return mask
def _get_connected_components_with_padding(mask): """Get connected components from masks (possibly padding them to an even size).""" from sam3.perflib.connected_components import connected_components
mask = mask.to(torch.uint8) _, _, H, W = mask.shape # make sure both height and width are even (to be compatible with cc_torch) pad_h = H % 2 pad_w = W % 2 if pad_h == 0 and pad_w == 0: labels, counts = connected_components(mask) else: # pad the mask to make its height and width even # padding format is (padding_left,padding_right,padding_top,padding_bottom) mask_pad = F.pad(mask, (0, pad_w, 0, pad_h), mode="constant", value=0) labels, counts = connected_components(mask_pad) labels = labels[:, :, :H, :W] counts = counts[:, :, :H, :W]
return labels, counts123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782783784785786787788789790791792793794795796797798799800801802803804805806807808809810811812813814815816817818819820821822823824825826827828829830831832833834835836837838839840841842843844845846847848849850851852853854855856857858859860861862863864865866867868869870871872873874875876877878879880881882883884885886887888889890891892893894895896897898899900901902903904905906907908909910911912913914915916917918919920921922923924925926927928929930931932933934935936937938939940941942943944945946947948949950951952953954955956957958959960961962963964965966967968969970971972973974975976977978979980981982983984985986987988989990991992993994995996997998999100010011002100310041005100610071008100910101011101210131014101510161017101810191020102110221023102410251026102710281029103010311032103310341035103610371038103910401041104210431044104510461047104810491050105110521053105410551056105710581059106010611062106310641065106610671068106910701071107210731074107510761077107810791080108110821083108410851086108710881089109010911092109310941095109610971098109911001101110211031104110511061107110811091110111111121113111411151116111711181119112011211122112311241125112611271128112911301131113211331134113511361137113811391140114111421143114411451146114711481149115011511152115311541155115611571158115911601161116211631164116511661167116811691170117111721173117411751176117711781179118011811182118311841185118611871188118911901191119211931194119511961197119811991200120112021203120412051206120712081209121012111212121312141215121612171218121912201221122212231224122512261227122812291230123112321233123412351236123712381239124012411242124312441245124612471248124912501251125212531254125512561257125812591260126112621263126412651266126712681269127012711272127312741275127612771278127912801281128212831284128512861287128812891290129112921293129412951296129712981299130013011302130313041305130613071308130913101311131213131314131513161317131813191320132113221323132413251326132713281329133013311332133313341335133613371338133913401341134213431344134513461347134813491350135113521353135413551356135713581359136013611362136313641365136613671368# Copyright (c) Meta Platforms, Inc. and affiliates. All Rights Reserved
import loggingfrom collections import OrderedDict
import torch
from sam3.model.sam3_tracker_base import concat_points, NO_OBJ_SCORE, Sam3TrackerBasefrom sam3.model.sam3_tracker_utils import fill_holes_in_mask_scoresfrom sam3.model.utils.sam2_utils import load_video_framesfrom tqdm.auto import tqdm
class Sam3TrackerPredictor(Sam3TrackerBase): """ The demo class that extends the `Sam3TrackerBase` to handle user interactions and manage inference states, with support for multi-object tracking. """
def __init__( self, # whether to clear non-conditioning memory of the surrounding frames (which may contain outdated information) after adding correction clicks; # note that this would only apply to *single-object tracking* unless `clear_non_cond_mem_for_multi_obj` is also set to True) clear_non_cond_mem_around_input=False, # whether to also clear non-conditioning memory of the surrounding frames (only effective when `clear_non_cond_mem_around_input` is True). clear_non_cond_mem_for_multi_obj=False, # if fill_hole_area > 0, we fill small holes in the final masks up to this area (after resizing them to the original video resolution) fill_hole_area=0, # if always_start_from_first_ann_frame is True, we always start tracking from the frame where we receive the first annotation (clicks or mask) # and ignore the `start_frame_idx` passed to `propagate_in_video` always_start_from_first_ann_frame=False, # the maximum number of points to be used in the prompt encoder, which reduce the domain gap between training (that only has 8 points) # - if it's set to a positive integer, we only take the `max_point_num_in_prompt_enc//2` points and # the last `(max_point_num_in_prompt_enc - max_point_num_in_prompt_enc//2)` points in the prompt encoder # - if it's set to 0 or negative, this option is turned off and we use all points in the prompt encoder max_point_num_in_prompt_enc=16, non_overlap_masks_for_output=True, # checkpoint_file=None, **kwargs, ): super().__init__(**kwargs) self.clear_non_cond_mem_around_input = clear_non_cond_mem_around_input self.clear_non_cond_mem_for_multi_obj = clear_non_cond_mem_for_multi_obj self.fill_hole_area = fill_hole_area self.always_start_from_first_ann_frame = always_start_from_first_ann_frame self.max_point_num_in_prompt_enc = max_point_num_in_prompt_enc self.non_overlap_masks_for_output = non_overlap_masks_for_output
self.bf16_context = torch.autocast(device_type="cuda", dtype=torch.bfloat16) self.bf16_context.__enter__() # keep using for the entire model process
self.iter_use_prev_mask_pred = True self.add_all_frames_to_correct_as_cond = True
@torch.inference_mode() def init_state( self, video_height=None, video_width=None, num_frames=None, video_path=None, cached_features=None, offload_video_to_cpu=False, offload_state_to_cpu=False, async_loading_frames=False, ): """Initialize a inference state.""" inference_state = {} # whether to offload the video frames to CPU memory # turning on this option saves the GPU memory with only a very small overhead inference_state["offload_video_to_cpu"] = offload_video_to_cpu # whether to offload the inference state to CPU memory # turning on this option saves the GPU memory at the cost of a lower tracking fps # (e.g. in a test case of 768x768 model, fps dropped from 27 to 24 when tracking one object # and from 24 to 21 when tracking two objects) inference_state["offload_state_to_cpu"] = offload_state_to_cpu inference_state["device"] = self.device if offload_state_to_cpu: inference_state["storage_device"] = torch.device("cpu") else: inference_state["storage_device"] = torch.device("cuda")
if video_path is not None: images, video_height, video_width = load_video_frames( video_path=video_path, image_size=self.image_size, offload_video_to_cpu=offload_video_to_cpu, async_loading_frames=async_loading_frames, compute_device=inference_state["storage_device"], ) inference_state["images"] = images inference_state["num_frames"] = len(images) inference_state["video_height"] = video_height inference_state["video_width"] = video_width else: # the original video height and width, used for resizing final output scores inference_state["video_height"] = video_height inference_state["video_width"] = video_width inference_state["num_frames"] = num_frames # inputs on each frame inference_state["point_inputs_per_obj"] = {} inference_state["mask_inputs_per_obj"] = {} # visual features on a small number of recently visited frames for quick interactions inference_state["cached_features"] = ( {} if cached_features is None else cached_features ) # values that don't change across frames (so we only need to hold one copy of them) inference_state["constants"] = {} # mapping between client-side object id and model-side object index inference_state["obj_id_to_idx"] = OrderedDict() inference_state["obj_idx_to_id"] = OrderedDict() inference_state["obj_ids"] = [] # A storage to hold the model's tracking results and states on each frame inference_state["output_dict"] = { "cond_frame_outputs": {}, # dict containing {frame_idx: <out>} "non_cond_frame_outputs": {}, # dict containing {frame_idx: <out>} } # The index of the frame that received the first annotation inference_state["first_ann_frame_idx"] = None # Slice (view) of each object tracking results, sharing the same memory with "output_dict" inference_state["output_dict_per_obj"] = {} # A temporary storage to hold new outputs when user interact with a frame # to add clicks or mask (it's merged into "output_dict" before propagation starts) inference_state["temp_output_dict_per_obj"] = {} # Frames that already holds consolidated outputs from click or mask inputs # (we directly use their consolidated outputs during tracking) inference_state["consolidated_frame_inds"] = { "cond_frame_outputs": set(), # set containing frame indices "non_cond_frame_outputs": set(), # set containing frame indices } # metadata for each tracking frame (e.g. which direction it's tracked) inference_state["tracking_has_started"] = False inference_state["frames_already_tracked"] = {} self.clear_all_points_in_video(inference_state) return inference_state
def _obj_id_to_idx(self, inference_state, obj_id): """Map client-side object id to model-side object index.""" obj_idx = inference_state["obj_id_to_idx"].get(obj_id, None) if obj_idx is not None: return obj_idx
# This is a new object id not sent to the server before. We only allow adding # new objects *before* the tracking starts. allow_new_object = not inference_state["tracking_has_started"] if allow_new_object: # get the next object slot obj_idx = len(inference_state["obj_id_to_idx"]) inference_state["obj_id_to_idx"][obj_id] = obj_idx inference_state["obj_idx_to_id"][obj_idx] = obj_id inference_state["obj_ids"] = list(inference_state["obj_id_to_idx"]) # set up input and output structures for this object inference_state["point_inputs_per_obj"][obj_idx] = {} inference_state["mask_inputs_per_obj"][obj_idx] = {} inference_state["output_dict_per_obj"][obj_idx] = { "cond_frame_outputs": {}, # dict containing {frame_idx: <out>} "non_cond_frame_outputs": {}, # dict containing {frame_idx: <out>} } inference_state["temp_output_dict_per_obj"][obj_idx] = { "cond_frame_outputs": {}, # dict containing {frame_idx: <out>} "non_cond_frame_outputs": {}, # dict containing {frame_idx: <out>} } return obj_idx else: raise RuntimeError( f"Cannot add new object id {obj_id} after tracking starts. " f"All existing object ids: {inference_state['obj_ids']}." )
def _obj_idx_to_id(self, inference_state, obj_idx): """Map model-side object index to client-side object id.""" return inference_state["obj_idx_to_id"][obj_idx]
def _get_obj_num(self, inference_state): """Get the total number of unique object ids received so far in this session.""" return len(inference_state["obj_idx_to_id"])
@torch.inference_mode() def add_new_points_or_box( self, inference_state, frame_idx, obj_id, points=None, labels=None, clear_old_points=True, rel_coordinates=True, use_prev_mem_frame=False, normalize_coords=True, box=None, ): """Add new points to a frame.""" obj_idx = self._obj_id_to_idx(inference_state, obj_id) point_inputs_per_frame = inference_state["point_inputs_per_obj"][obj_idx] mask_inputs_per_frame = inference_state["mask_inputs_per_obj"][obj_idx]
if (points is not None) != (labels is not None): raise ValueError("points and labels must be provided together") if points is None and box is None: raise ValueError("at least one of points or box must be provided as input")
if points is None: points = torch.zeros(0, 2, dtype=torch.float32) elif not isinstance(points, torch.Tensor): points = torch.tensor(points, dtype=torch.float32) if labels is None: labels = torch.zeros(0, dtype=torch.int32) elif not isinstance(labels, torch.Tensor): labels = torch.tensor(labels, dtype=torch.int32) if points.dim() == 2: points = points.unsqueeze(0) # add batch dimension if labels.dim() == 1: labels = labels.unsqueeze(0) # add batch dimension
if rel_coordinates: # convert the points from relative coordinates to absolute coordinates if points is not None: points = points * self.image_size if box is not None: box = box * self.image_size
# If `box` is provided, we add it as the first two points with labels 2 and 3 # along with the user-provided points (consistent with how SAM 2 is trained). if box is not None: if not clear_old_points: raise ValueError( "cannot add box without clearing old points, since " "box prompt must be provided before any point prompt " "(please use clear_old_points=True instead)" ) if not isinstance(box, torch.Tensor): box = torch.tensor(box, dtype=torch.float32, device=points.device) box_coords = box.reshape(1, 2, 2) box_labels = torch.tensor([2, 3], dtype=torch.int32, device=labels.device) box_labels = box_labels.reshape(1, 2) points = torch.cat([box_coords, points], dim=1) labels = torch.cat([box_labels, labels], dim=1)
points = points.to(inference_state["device"]) labels = labels.to(inference_state["device"])
if not clear_old_points: point_inputs = point_inputs_per_frame.get(frame_idx, None) else: point_inputs = None point_inputs = concat_points(point_inputs, points, labels)
point_inputs_per_frame[frame_idx] = point_inputs mask_inputs_per_frame.pop(frame_idx, None) # If this frame hasn't been tracked before, we treat it as an initial conditioning # frame, meaning that the inputs points are to generate segments on this frame without # using any memory from other frames, like in SAM. Otherwise (if it has been tracked), # the input points will be used to correct the already tracked masks. is_init_cond_frame = frame_idx not in inference_state["frames_already_tracked"] # whether to track in reverse time order if is_init_cond_frame: reverse = False else: reverse = inference_state["frames_already_tracked"][frame_idx]["reverse"] obj_output_dict = inference_state["output_dict_per_obj"][obj_idx] obj_temp_output_dict = inference_state["temp_output_dict_per_obj"][obj_idx] # Add a frame to conditioning output if it's an initial conditioning frame or # if the model sees all frames receiving clicks/mask as conditioning frames. is_cond = is_init_cond_frame or self.add_all_frames_to_correct_as_cond storage_key = "cond_frame_outputs" if is_cond else "non_cond_frame_outputs"
# Limit to a maximum number of input points to the prompt encoder (to reduce domain gap) num_points = point_inputs["point_coords"].size(1) if num_points > self.max_point_num_in_prompt_enc > 0: num_first = self.max_point_num_in_prompt_enc // 2 num_last = self.max_point_num_in_prompt_enc - num_first point_inputs["point_coords"] = torch.cat( [ point_inputs["point_coords"][:, :num_first], point_inputs["point_coords"][:, -num_last:], ], dim=1, ) point_inputs["point_labels"] = torch.cat( [ point_inputs["point_labels"][:, :num_first], point_inputs["point_labels"][:, -num_last:], ], dim=1, ) logging.warning( f"Too many points ({num_points}) are provided on frame {frame_idx}. Only " f"the first {num_first} points and the last {num_last} points will be used." ) # Get any previously predicted mask logits on this object and feed it along with # the new clicks into the SAM mask decoder when `self.iter_use_prev_mask_pred=True`. prev_sam_mask_logits = None if self.iter_use_prev_mask_pred: # lookup temporary output dict first, which contains the most recent output # (if not found, then lookup conditioning and non-conditioning frame output) prev_out = obj_temp_output_dict[storage_key].get(frame_idx) if prev_out is None: prev_out = obj_output_dict["cond_frame_outputs"].get(frame_idx) if prev_out is None: prev_out = obj_output_dict["non_cond_frame_outputs"].get(frame_idx)
if prev_out is not None and prev_out["pred_masks"] is not None: prev_sam_mask_logits = prev_out["pred_masks"].cuda(non_blocking=True) # Clamp the scale of prev_sam_mask_logits to avoid rare numerical issues. prev_sam_mask_logits = torch.clamp(prev_sam_mask_logits, -32.0, 32.0) current_out, _ = self._run_single_frame_inference( inference_state=inference_state, output_dict=obj_output_dict, # run on the slice of a single object frame_idx=frame_idx, batch_size=1, # run on the slice of a single object is_init_cond_frame=is_init_cond_frame, point_inputs=point_inputs, mask_inputs=None, reverse=reverse, # Skip the memory encoder when adding clicks or mask. We execute the memory encoder # at the beginning of `propagate_in_video` (after user finalize their clicks). This # allows us to enforce non-overlapping constraints on all objects before encoding # them into memory. run_mem_encoder=False, prev_sam_mask_logits=prev_sam_mask_logits, use_prev_mem_frame=use_prev_mem_frame, ) # Add the output to the output dict (to be used as future memory) obj_temp_output_dict[storage_key][frame_idx] = current_out
# Resize the output mask to the original video resolution obj_ids = inference_state["obj_ids"] consolidated_out = self._consolidate_temp_output_across_obj( inference_state, frame_idx, is_cond=is_cond, run_mem_encoder=False, consolidate_at_video_res=True, ) _, video_res_masks = self._get_orig_video_res_output( inference_state, consolidated_out["pred_masks_video_res"] ) low_res_masks = None # not needed by the demo return frame_idx, obj_ids, low_res_masks, video_res_masks
@torch.inference_mode() def add_new_mask( self, inference_state, frame_idx, obj_id, mask, add_mask_to_memory=False, ): """Add new mask to a frame.""" obj_idx = self._obj_id_to_idx(inference_state, obj_id) point_inputs_per_frame = inference_state["point_inputs_per_obj"][obj_idx] mask_inputs_per_frame = inference_state["mask_inputs_per_obj"][obj_idx]
assert mask.dim() == 2 mask_H, mask_W = mask.shape mask_inputs_orig = mask[None, None] # add batch and channel dimension mask_inputs_orig = mask_inputs_orig.float().to(inference_state["device"])
# resize the mask if it doesn't match the model's input mask size if mask_H != self.input_mask_size or mask_W != self.input_mask_size: mask_inputs = torch.nn.functional.interpolate( mask_inputs_orig, size=(self.input_mask_size, self.input_mask_size), align_corners=False, mode="bilinear", antialias=True, # use antialias for downsampling ) else: mask_inputs = mask_inputs_orig
# also get the mask at the original video resolution (for outputting) video_H = inference_state["video_height"] video_W = inference_state["video_width"] if mask_H != video_H or mask_W != video_W: mask_inputs_video_res = torch.nn.functional.interpolate( mask_inputs_orig, size=(video_H, video_W), align_corners=False, mode="bilinear", antialias=True, # use antialias for potential downsampling ) else: mask_inputs_video_res = mask_inputs_orig # convert mask_inputs_video_res to binary (threshold at 0.5 as it is in range 0~1) mask_inputs_video_res = mask_inputs_video_res > 0.5
mask_inputs_per_frame[frame_idx] = mask_inputs_video_res point_inputs_per_frame.pop(frame_idx, None) # If this frame hasn't been tracked before, we treat it as an initial conditioning # frame, meaning that the inputs points are to generate segments on this frame without # using any memory from other frames, like in SAM. Otherwise (if it has been tracked), # the input points will be used to correct the already tracked masks. is_init_cond_frame = frame_idx not in inference_state["frames_already_tracked"] # whether to track in reverse time order if is_init_cond_frame: reverse = False else: reverse = inference_state["frames_already_tracked"][frame_idx]["reverse"] obj_output_dict = inference_state["output_dict_per_obj"][obj_idx] obj_temp_output_dict = inference_state["temp_output_dict_per_obj"][obj_idx] # Add a frame to conditioning output if it's an initial conditioning frame or # if the model sees all frames receiving clicks/mask as conditioning frames. is_cond = is_init_cond_frame or self.add_all_frames_to_correct_as_cond storage_key = "cond_frame_outputs" if is_cond else "non_cond_frame_outputs"
current_out, _ = self._run_single_frame_inference( inference_state=inference_state, output_dict=obj_output_dict, # run on the slice of a single object frame_idx=frame_idx, batch_size=1, # run on the slice of a single object is_init_cond_frame=is_init_cond_frame, point_inputs=None, mask_inputs=mask_inputs, reverse=reverse, # Skip the memory encoder when adding clicks or mask. We execute the memory encoder # at the beginning of `propagate_in_video` (after user finalize their clicks). This # allows us to enforce non-overlapping constraints on all objects before encoding # them into memory. run_mem_encoder=False, ) # We directly use the input mask at video resolution as the output mask for a better # video editing experience (so that the masks don't change after each brushing). # Here NO_OBJ_SCORE is a large negative value to represent the background and # similarly -NO_OBJ_SCORE is a large positive value to represent the foreground. current_out["pred_masks"] = None current_out["pred_masks_video_res"] = torch.where( mask_inputs_video_res, -NO_OBJ_SCORE, NO_OBJ_SCORE ) # Add the output to the output dict (to be used as future memory) obj_temp_output_dict[storage_key][frame_idx] = current_out # Remove the overlapping proportion of other objects' input masks on this frame temp_output_dict_per_obj = inference_state["temp_output_dict_per_obj"] for obj_idx2, obj_temp_output_dict2 in temp_output_dict_per_obj.items(): if obj_idx2 == obj_idx: continue current_out2 = obj_temp_output_dict2[storage_key].get(frame_idx, None) if current_out2 is not None and "pred_masks_video_res" in current_out2: current_out2["pred_masks_video_res"] = torch.where( mask_inputs_video_res, NO_OBJ_SCORE, current_out2["pred_masks_video_res"], )
# Resize the output mask to the original video resolution obj_ids = inference_state["obj_ids"] consolidated_out = self._consolidate_temp_output_across_obj( inference_state, frame_idx, is_cond=is_cond, run_mem_encoder=False, consolidate_at_video_res=True, ) _, video_res_masks = self._get_orig_video_res_output( inference_state, consolidated_out["pred_masks_video_res"] ) low_res_masks = None # not needed by the demo return frame_idx, obj_ids, low_res_masks, video_res_masks
def add_new_points(self, *args, **kwargs): """Deprecated method. Please use `add_new_points_or_box` instead.""" return self.add_new_points_or_box(*args, **kwargs)
def _get_orig_video_res_output(self, inference_state, any_res_masks): """ Resize the object scores to the original video resolution (video_res_masks) and apply non-overlapping constraints for final output. """ device = inference_state["device"] video_H = inference_state["video_height"] video_W = inference_state["video_width"] any_res_masks = any_res_masks.to(device, non_blocking=True) if any_res_masks.shape[-2:] == (video_H, video_W): video_res_masks = any_res_masks else: video_res_masks = torch.nn.functional.interpolate( any_res_masks, size=(video_H, video_W), mode="bilinear", align_corners=False, ) if self.non_overlap_masks_for_output: video_res_masks = self._apply_non_overlapping_constraints(video_res_masks) # potentially fill holes in the predicted masks if self.fill_hole_area > 0: video_res_masks = fill_holes_in_mask_scores( video_res_masks, self.fill_hole_area ) return any_res_masks, video_res_masks
def _consolidate_temp_output_across_obj( self, inference_state, frame_idx, is_cond, run_mem_encoder, consolidate_at_video_res=False, ): """ Consolidate the per-object temporary outputs in `temp_output_dict_per_obj` on a frame into a single output for all objects, including 1) fill any missing objects either from `output_dict_per_obj` (if they exist in `output_dict_per_obj` for this frame) or leave them as placeholder values (if they don't exist in `output_dict_per_obj` for this frame); 2) if specified, rerun memory encoder after apply non-overlapping constraints on the object scores. """ batch_size = self._get_obj_num(inference_state) storage_key = "cond_frame_outputs" if is_cond else "non_cond_frame_outputs" # Optionally, we allow consolidating the temporary outputs at the original # video resolution (to provide a better editing experience for mask prompts). if consolidate_at_video_res: assert not run_mem_encoder, "memory encoder cannot run at video resolution" consolidated_H = inference_state["video_height"] consolidated_W = inference_state["video_width"] consolidated_mask_key = "pred_masks_video_res" else: consolidated_H = consolidated_W = self.low_res_mask_size consolidated_mask_key = "pred_masks"
# Initialize `consolidated_out`. Its "maskmem_features" and "maskmem_pos_enc" # will be added when rerunning the memory encoder after applying non-overlapping # constraints to object scores. Its "pred_masks" are prefilled with a large # negative value (NO_OBJ_SCORE) to represent missing objects. consolidated_out = { "maskmem_features": None, "maskmem_pos_enc": None, consolidated_mask_key: torch.full( size=(batch_size, 1, consolidated_H, consolidated_W), fill_value=NO_OBJ_SCORE, dtype=torch.float32, device=inference_state["storage_device"], ), "obj_ptr": torch.full( size=(batch_size, self.hidden_dim), fill_value=NO_OBJ_SCORE, dtype=torch.float32, device=inference_state["device"], ), "object_score_logits": torch.full( size=(batch_size, 1), # default to 10.0 for object_score_logits, i.e. assuming the object is # present as sigmoid(10)=1, same as in `predict_masks` of `MaskDecoder` fill_value=10.0, dtype=torch.float32, device=inference_state["device"], ), } if self.use_memory_selection: consolidated_out["iou_score"] = torch.full( size=(batch_size, 1), fill_value=0.0, dtype=torch.float32, device=inference_state["device"], ) empty_mask_ptr = None for obj_idx in range(batch_size): obj_temp_output_dict = inference_state["temp_output_dict_per_obj"][obj_idx] obj_output_dict = inference_state["output_dict_per_obj"][obj_idx] out = obj_temp_output_dict[storage_key].get(frame_idx, None) # If the object doesn't appear in "temp_output_dict_per_obj" on this frame, # we fall back and look up its previous output in "output_dict_per_obj". # We look up both "cond_frame_outputs" and "non_cond_frame_outputs" in # "output_dict_per_obj" to find a previous output for this object. if out is None: out = obj_output_dict["cond_frame_outputs"].get(frame_idx, None) if out is None: out = obj_output_dict["non_cond_frame_outputs"].get(frame_idx, None) # If the object doesn't appear in "output_dict_per_obj" either, we skip it # and leave its mask scores to the default scores (i.e. the NO_OBJ_SCORE # placeholder above) and set its object pointer to be a dummy pointer. if out is None: # Fill in dummy object pointers for those objects without any inputs or # tracking outcomes on this frame (only do it under `run_mem_encoder=True`, # i.e. when we need to build the memory for tracking). if run_mem_encoder: if empty_mask_ptr is None: empty_mask_ptr = self._get_empty_mask_ptr( inference_state, frame_idx ) # fill object pointer with a dummy pointer (based on an empty mask) consolidated_out["obj_ptr"][obj_idx : obj_idx + 1] = empty_mask_ptr continue # Add the temporary object output mask to consolidated output mask # (use "pred_masks_video_res" if it's available) obj_mask = out.get("pred_masks_video_res", out["pred_masks"]) consolidated_pred_masks = consolidated_out[consolidated_mask_key] if obj_mask.shape[-2:] == consolidated_pred_masks.shape[-2:]: consolidated_pred_masks[obj_idx : obj_idx + 1] = obj_mask else: # Resize first if temporary object mask has a different resolution is_downsampling = "pred_masks_video_res" in out resized_obj_mask = torch.nn.functional.interpolate( obj_mask, size=consolidated_pred_masks.shape[-2:], mode="bilinear", align_corners=False, antialias=is_downsampling, # use antialias for downsampling ) consolidated_pred_masks[obj_idx : obj_idx + 1] = resized_obj_mask consolidated_out["obj_ptr"][obj_idx : obj_idx + 1] = out["obj_ptr"] consolidated_out["object_score_logits"][obj_idx : obj_idx + 1] = out[ "object_score_logits" ] if self.use_memory_selection: consolidated_out["iou_score"][obj_idx : obj_idx + 1] = out["iou_score"] # Optionally, apply non-overlapping constraints on the consolidated scores # and rerun the memory encoder if run_mem_encoder: device = inference_state["device"] high_res_masks = torch.nn.functional.interpolate( consolidated_out["pred_masks"].to(device, non_blocking=True), size=(self.image_size, self.image_size), mode="bilinear", align_corners=False, ) high_res_masks = self._apply_non_overlapping_constraints(high_res_masks) maskmem_features, maskmem_pos_enc = self._run_memory_encoder( inference_state=inference_state, frame_idx=frame_idx, batch_size=batch_size, high_res_masks=high_res_masks, object_score_logits=consolidated_out["object_score_logits"], is_mask_from_pts=True, # these frames are what the user interacted with ) consolidated_out["maskmem_features"] = maskmem_features consolidated_out["maskmem_pos_enc"] = maskmem_pos_enc
return consolidated_out
def _get_empty_mask_ptr(self, inference_state, frame_idx): """Get a dummy object pointer based on an empty mask on the current frame.""" # A dummy (empty) mask with a single object batch_size = 1 mask_inputs = torch.zeros( (batch_size, 1, self.image_size, self.image_size), dtype=torch.float32, device=inference_state["device"], )
# Retrieve correct image features ( image, _, current_vision_feats, current_vision_pos_embeds, feat_sizes, ) = self._get_image_feature(inference_state, frame_idx, batch_size)
# Feed the empty mask and image feature above to get a dummy object pointer current_out = self.track_step( frame_idx=frame_idx, is_init_cond_frame=True, current_vision_feats=current_vision_feats, current_vision_pos_embeds=current_vision_pos_embeds, feat_sizes=feat_sizes, image=image, point_inputs=None, mask_inputs=mask_inputs, output_dict={ "cond_frame_outputs": {}, "non_cond_frame_outputs": {}, }, num_frames=inference_state["num_frames"], track_in_reverse=False, run_mem_encoder=False, prev_sam_mask_logits=None, ) return current_out["obj_ptr"]
@torch.inference_mode() def propagate_in_video_preflight(self, inference_state, run_mem_encoder=True): """Prepare inference_state and consolidate temporary outputs before tracking.""" # Tracking has started and we don't allow adding new objects until session is reset. inference_state["tracking_has_started"] = True batch_size = self._get_obj_num(inference_state)
# Consolidate per-object temporary outputs in "temp_output_dict_per_obj" and # add them into "output_dict". temp_output_dict_per_obj = inference_state["temp_output_dict_per_obj"] output_dict = inference_state["output_dict"] # "consolidated_frame_inds" contains indices of those frames where consolidated # temporary outputs have been added (either in this call or any previous calls # to `propagate_in_video_preflight`). consolidated_frame_inds = inference_state["consolidated_frame_inds"] for is_cond in [False, True]: # Separately consolidate conditioning and non-conditioning temp outptus storage_key = "cond_frame_outputs" if is_cond else "non_cond_frame_outputs" # Find all the frames that contain temporary outputs for any objects # (these should be the frames that have just received clicks for mask inputs # via `add_new_points` or `add_new_mask`) temp_frame_inds = set() for obj_temp_output_dict in temp_output_dict_per_obj.values(): temp_frame_inds.update(obj_temp_output_dict[storage_key].keys()) consolidated_frame_inds[storage_key].update(temp_frame_inds) # consolidate the temprary output across all objects on this frame for frame_idx in temp_frame_inds: consolidated_out = self._consolidate_temp_output_across_obj( inference_state, frame_idx, is_cond=is_cond, run_mem_encoder=run_mem_encoder, ) # merge them into "output_dict" and also create per-object slices output_dict[storage_key][frame_idx] = consolidated_out self._add_output_per_object( inference_state, frame_idx, consolidated_out, storage_key ) clear_non_cond_mem = self.clear_non_cond_mem_around_input and ( self.clear_non_cond_mem_for_multi_obj or batch_size <= 1 ) if clear_non_cond_mem: # clear non-conditioning memory of the surrounding frames self._clear_non_cond_mem_around_input(inference_state, frame_idx)
# clear temporary outputs in `temp_output_dict_per_obj` for obj_temp_output_dict in temp_output_dict_per_obj.values(): obj_temp_output_dict[storage_key].clear()
# edge case: if an output is added to "cond_frame_outputs", we remove any prior # output on the same frame in "non_cond_frame_outputs" for frame_idx in output_dict["cond_frame_outputs"]: output_dict["non_cond_frame_outputs"].pop(frame_idx, None) for obj_output_dict in inference_state["output_dict_per_obj"].values(): for frame_idx in obj_output_dict["cond_frame_outputs"]: obj_output_dict["non_cond_frame_outputs"].pop(frame_idx, None) for frame_idx in consolidated_frame_inds["cond_frame_outputs"]: assert frame_idx in output_dict["cond_frame_outputs"] consolidated_frame_inds["non_cond_frame_outputs"].discard(frame_idx)
# Make sure that the frame indices in "consolidated_frame_inds" are exactly those frames # with either points or mask inputs (which should be true under a correct demo workflow). all_consolidated_frame_inds = ( consolidated_frame_inds["cond_frame_outputs"] | consolidated_frame_inds["non_cond_frame_outputs"] ) input_frames_inds = set() for point_inputs_per_frame in inference_state["point_inputs_per_obj"].values(): input_frames_inds.update(point_inputs_per_frame.keys()) for mask_inputs_per_frame in inference_state["mask_inputs_per_obj"].values(): input_frames_inds.update(mask_inputs_per_frame.keys()) assert all_consolidated_frame_inds == input_frames_inds # Record the first interacted frame index (for tracking start) if inference_state["first_ann_frame_idx"] is None: inference_state["first_ann_frame_idx"] = min( input_frames_inds, default=None ) # In case `first_ann_frame_idx` is not in the conditioning frames (e.g. because # we cleared the input points on that frame), pick the first conditioning frame if ( inference_state["first_ann_frame_idx"] not in output_dict["cond_frame_outputs"] ): inference_state["first_ann_frame_idx"] = min( output_dict["cond_frame_outputs"], default=None )
def _get_processing_order( self, inference_state, start_frame_idx, max_frame_num_to_track, reverse ): num_frames = inference_state["num_frames"] # set start index, end index, and processing order if self.always_start_from_first_ann_frame: # in this case, we always start tracking from the frame where we receive # the initial annotation and ignore the provided start_frame_idx start_frame_idx = inference_state["first_ann_frame_idx"] if start_frame_idx is None: # default: start from the earliest frame with input points start_frame_idx = min(inference_state["output_dict"]["cond_frame_outputs"]) if max_frame_num_to_track is None: # default: track all the frames in the video max_frame_num_to_track = num_frames if reverse: end_frame_idx = max(start_frame_idx - max_frame_num_to_track, 0) if start_frame_idx > 0: processing_order = range(start_frame_idx, end_frame_idx - 1, -1) else: # this is the edge case where we start from frame 0 and track in reverse order; # in this case, we track a single frame (frame 0) processing_order = [0] else: end_frame_idx = min( start_frame_idx + max_frame_num_to_track, num_frames - 1 ) processing_order = range(start_frame_idx, end_frame_idx + 1) return processing_order
@torch.inference_mode() def propagate_in_video( self, inference_state, start_frame_idx, max_frame_num_to_track, reverse, tqdm_disable=False, obj_ids=None, run_mem_encoder=True, propagate_preflight=False, ): """Propagate the input points across frames to track in the entire video.""" if propagate_preflight: self.propagate_in_video_preflight(inference_state) # NOTE: This is a copy from the parent class, except that we return object scores as well. output_dict = inference_state["output_dict"] consolidated_frame_inds = inference_state["consolidated_frame_inds"] if obj_ids is not None: raise NotImplementedError( "Per-object tracking yet for batched inference if not implemented." ) obj_ids = inference_state["obj_ids"] batch_size = self._get_obj_num(inference_state) if len(output_dict["cond_frame_outputs"]) == 0: raise RuntimeError("No points are provided; please add points first") clear_non_cond_mem = self.clear_non_cond_mem_around_input and ( self.clear_non_cond_mem_for_multi_obj or batch_size <= 1 )
processing_order = self._get_processing_order( inference_state, start_frame_idx, max_frame_num_to_track, reverse, )
for frame_idx in tqdm( processing_order, desc="propagate in video", disable=tqdm_disable ): # We skip those frames already in consolidated outputs (these are frames # that received input clicks or mask). Note that we cannot directly run # batched forward on them via `_run_single_frame_inference` because the # number of clicks on each object might be different. if frame_idx in consolidated_frame_inds["cond_frame_outputs"]: storage_key = "cond_frame_outputs" current_out = output_dict[storage_key][frame_idx] pred_masks = current_out["pred_masks"] obj_scores = current_out["object_score_logits"] if clear_non_cond_mem: # clear non-conditioning memory of the surrounding frames self._clear_non_cond_mem_around_input(inference_state, frame_idx) elif frame_idx in consolidated_frame_inds["non_cond_frame_outputs"]: storage_key = "non_cond_frame_outputs" current_out = output_dict[storage_key][frame_idx] pred_masks = current_out["pred_masks"] obj_scores = current_out["object_score_logits"] else: storage_key = "non_cond_frame_outputs" current_out, pred_masks = self._run_single_frame_inference( inference_state=inference_state, output_dict=output_dict, frame_idx=frame_idx, batch_size=batch_size, is_init_cond_frame=False, point_inputs=None, mask_inputs=None, reverse=reverse, run_mem_encoder=run_mem_encoder, ) obj_scores = current_out["object_score_logits"] output_dict[storage_key][frame_idx] = current_out # Create slices of per-object outputs for subsequent interaction with each # individual object after tracking. self._add_output_per_object( inference_state, frame_idx, current_out, storage_key ) inference_state["frames_already_tracked"][frame_idx] = {"reverse": reverse}
# Resize the output mask to the original video resolution (we directly use # the mask scores on GPU for output to avoid any CPU conversion in between) low_res_masks, video_res_masks = self._get_orig_video_res_output( inference_state, pred_masks ) yield frame_idx, obj_ids, low_res_masks, video_res_masks, obj_scores
def _add_output_per_object( self, inference_state, frame_idx, current_out, storage_key ): """ Split a multi-object output into per-object output slices and add them into `output_dict_per_obj`. The resulting slices share the same tensor storage. """ maskmem_features = current_out["maskmem_features"] assert maskmem_features is None or isinstance(maskmem_features, torch.Tensor)
maskmem_pos_enc = current_out["maskmem_pos_enc"] assert maskmem_pos_enc is None or isinstance(maskmem_pos_enc, list)
output_dict_per_obj = inference_state["output_dict_per_obj"] for obj_idx, obj_output_dict in output_dict_per_obj.items(): obj_slice = slice(obj_idx, obj_idx + 1) obj_out = { "maskmem_features": None, "maskmem_pos_enc": None, "pred_masks": current_out["pred_masks"][obj_slice], "obj_ptr": current_out["obj_ptr"][obj_slice], "object_score_logits": current_out["object_score_logits"][obj_slice], } if self.use_memory_selection: obj_out["iou_score"] = current_out["iou_score"][obj_slice] if maskmem_features is not None: obj_out["maskmem_features"] = maskmem_features[obj_slice] if maskmem_pos_enc is not None: obj_out["maskmem_pos_enc"] = [x[obj_slice] for x in maskmem_pos_enc] obj_output_dict[storage_key][frame_idx] = obj_out
@torch.inference_mode() def clear_all_points_in_frame( self, inference_state, frame_idx, obj_id, need_output=True ): """Remove all input points or mask in a specific frame for a given object.""" obj_idx = self._obj_id_to_idx(inference_state, obj_id)
# Clear the conditioning information on the given frame inference_state["point_inputs_per_obj"][obj_idx].pop(frame_idx, None) inference_state["mask_inputs_per_obj"][obj_idx].pop(frame_idx, None)
temp_output_dict_per_obj = inference_state["temp_output_dict_per_obj"] temp_output_dict_per_obj[obj_idx]["cond_frame_outputs"].pop(frame_idx, None) temp_output_dict_per_obj[obj_idx]["non_cond_frame_outputs"].pop(frame_idx, None)
# Check and see if there are still any inputs left on this frame batch_size = self._get_obj_num(inference_state) frame_has_input = False for obj_idx2 in range(batch_size): if frame_idx in inference_state["point_inputs_per_obj"][obj_idx2]: frame_has_input = True break if frame_idx in inference_state["mask_inputs_per_obj"][obj_idx2]: frame_has_input = True break
# If this frame has no remaining inputs for any objects, we further clear its # conditioning frame status if not frame_has_input: output_dict = inference_state["output_dict"] consolidated_frame_inds = inference_state["consolidated_frame_inds"] consolidated_frame_inds["cond_frame_outputs"].discard(frame_idx) consolidated_frame_inds["non_cond_frame_outputs"].discard(frame_idx) # Remove the frame's conditioning output (possibly downgrading it to non-conditioning) out = output_dict["cond_frame_outputs"].pop(frame_idx, None) if out is not None: # The frame is not a conditioning frame anymore since it's not receiving inputs, # so we "downgrade" its output (if exists) to a non-conditioning frame output. output_dict["non_cond_frame_outputs"][frame_idx] = out inference_state["frames_already_tracked"].pop(frame_idx, None) # Similarly, do it for the sliced output on each object. for obj_idx2 in range(batch_size): obj_output_dict = inference_state["output_dict_per_obj"][obj_idx2] obj_out = obj_output_dict["cond_frame_outputs"].pop(frame_idx, None) if obj_out is not None: obj_output_dict["non_cond_frame_outputs"][frame_idx] = obj_out
# If all the conditioning frames have been removed, we also clear the tracking outputs if len(output_dict["cond_frame_outputs"]) == 0: self._reset_tracking_results(inference_state)
if not need_output: return # Finally, output updated masks per object (after removing the inputs above) obj_ids = inference_state["obj_ids"] is_cond = any( frame_idx in obj_temp_output_dict["cond_frame_outputs"] for obj_temp_output_dict in temp_output_dict_per_obj.values() ) consolidated_out = self._consolidate_temp_output_across_obj( inference_state, frame_idx, is_cond=is_cond, run_mem_encoder=False, consolidate_at_video_res=True, ) _, video_res_masks = self._get_orig_video_res_output( inference_state, consolidated_out["pred_masks_video_res"] ) low_res_masks = None # not needed by the demo return frame_idx, obj_ids, low_res_masks, video_res_masks
@torch.inference_mode() def clear_all_points_in_video(self, inference_state): """Remove all input points or mask in all frames throughout the video.""" self._reset_tracking_results(inference_state) # Remove all object ids inference_state["obj_id_to_idx"].clear() inference_state["obj_idx_to_id"].clear() inference_state["obj_ids"].clear() inference_state["point_inputs_per_obj"].clear() inference_state["mask_inputs_per_obj"].clear() inference_state["output_dict_per_obj"].clear() inference_state["temp_output_dict_per_obj"].clear()
def _reset_tracking_results(self, inference_state): """Reset all tracking inputs and results across the videos.""" for v in inference_state["point_inputs_per_obj"].values(): v.clear() for v in inference_state["mask_inputs_per_obj"].values(): v.clear() for v in inference_state["output_dict_per_obj"].values(): v["cond_frame_outputs"].clear() v["non_cond_frame_outputs"].clear() for v in inference_state["temp_output_dict_per_obj"].values(): v["cond_frame_outputs"].clear() v["non_cond_frame_outputs"].clear() inference_state["output_dict"]["cond_frame_outputs"].clear() inference_state["output_dict"]["non_cond_frame_outputs"].clear() inference_state["consolidated_frame_inds"]["cond_frame_outputs"].clear() inference_state["consolidated_frame_inds"]["non_cond_frame_outputs"].clear() inference_state["tracking_has_started"] = False inference_state["frames_already_tracked"].clear() inference_state["first_ann_frame_idx"] = None
def _get_image_feature(self, inference_state, frame_idx, batch_size): """Compute the image features on a given frame.""" # Look up in the cache image, backbone_out = inference_state["cached_features"].get( frame_idx, (None, None) ) if backbone_out is None: if self.backbone is None: raise RuntimeError( f"Image features for frame {frame_idx} are not cached. " "Please run inference on this frame first." ) else: # Cache miss -- we will run inference on a single image image = inference_state["images"][frame_idx].cuda().float().unsqueeze(0) backbone_out = self.forward_image(image) # Cache the most recent frame's feature (for repeated interactions with # a frame; we can use an LRU cache for more frames in the future). inference_state["cached_features"] = {frame_idx: (image, backbone_out)} if "tracker_backbone_out" in backbone_out: backbone_out = backbone_out["tracker_backbone_out"] # get backbone output
# expand the features to have the same dimension as the number of objects expanded_image = image.expand(batch_size, -1, -1, -1) expanded_backbone_out = { "backbone_fpn": backbone_out["backbone_fpn"].copy(), "vision_pos_enc": backbone_out["vision_pos_enc"].copy(), } for i, feat in enumerate(expanded_backbone_out["backbone_fpn"]): feat = feat.expand(batch_size, -1, -1, -1) expanded_backbone_out["backbone_fpn"][i] = feat for i, pos in enumerate(expanded_backbone_out["vision_pos_enc"]): pos = pos.expand(batch_size, -1, -1, -1) expanded_backbone_out["vision_pos_enc"][i] = pos
features = self._prepare_backbone_features(expanded_backbone_out) features = (expanded_image,) + features return features
def _run_single_frame_inference( self, inference_state, output_dict, frame_idx, batch_size, is_init_cond_frame, point_inputs, mask_inputs, reverse, run_mem_encoder, prev_sam_mask_logits=None, use_prev_mem_frame=True, ): """Run tracking on a single frame based on current inputs and previous memory.""" # Retrieve correct image features ( image, _, current_vision_feats, current_vision_pos_embeds, feat_sizes, ) = self._get_image_feature(inference_state, frame_idx, batch_size)
# point and mask should not appear as input simultaneously on the same frame assert point_inputs is None or mask_inputs is None current_out = self.track_step( frame_idx=frame_idx, is_init_cond_frame=is_init_cond_frame, current_vision_feats=current_vision_feats, current_vision_pos_embeds=current_vision_pos_embeds, feat_sizes=feat_sizes, image=image, point_inputs=point_inputs, mask_inputs=mask_inputs, output_dict=output_dict, num_frames=inference_state["num_frames"], track_in_reverse=reverse, run_mem_encoder=run_mem_encoder, prev_sam_mask_logits=prev_sam_mask_logits, use_prev_mem_frame=use_prev_mem_frame, )
# optionally offload the output to CPU memory to save GPU space storage_device = inference_state["storage_device"] maskmem_features = current_out["maskmem_features"] if maskmem_features is not None: maskmem_features = maskmem_features.to(torch.bfloat16) maskmem_features = maskmem_features.to(storage_device, non_blocking=True) pred_masks_gpu = current_out["pred_masks"] pred_masks = pred_masks_gpu.to(storage_device, non_blocking=True) # "maskmem_pos_enc" is the same across frames, so we only need to store one copy of it maskmem_pos_enc = self._get_maskmem_pos_enc(inference_state, current_out) # object pointer is a small tensor, so we always keep it on GPU memory for fast access obj_ptr = current_out["obj_ptr"] object_score_logits = current_out["object_score_logits"] # make a compact version of this frame's output to reduce the state size compact_current_out = { "maskmem_features": maskmem_features, "maskmem_pos_enc": maskmem_pos_enc, "pred_masks": pred_masks, "obj_ptr": obj_ptr, "object_score_logits": object_score_logits, } if self.use_memory_selection: compact_current_out["iou_score"] = current_out["iou_score"] compact_current_out["eff_iou_score"] = current_out["eff_iou_score"] return compact_current_out, pred_masks_gpu
def _run_memory_encoder( self, inference_state, frame_idx, batch_size, high_res_masks, object_score_logits, is_mask_from_pts, ): """ Run the memory encoder on `high_res_masks`. This is usually after applying non-overlapping constraints to object scores. Since their scores changed, their memory also need to be computed again with the memory encoder. """ # Retrieve correct image features image, _, current_vision_feats, _, feat_sizes = self._get_image_feature( inference_state, frame_idx, batch_size ) maskmem_features, maskmem_pos_enc = self._encode_new_memory( image=image, current_vision_feats=current_vision_feats, feat_sizes=feat_sizes, pred_masks_high_res=high_res_masks, object_score_logits=object_score_logits, is_mask_from_pts=is_mask_from_pts, )
# optionally offload the output to CPU memory to save GPU space storage_device = inference_state["storage_device"] maskmem_features = maskmem_features.to(torch.bfloat16) maskmem_features = maskmem_features.to(storage_device, non_blocking=True) # "maskmem_pos_enc" is the same across frames, so we only need to store one copy of it maskmem_pos_enc = self._get_maskmem_pos_enc( inference_state, {"maskmem_pos_enc": maskmem_pos_enc} ) return maskmem_features, maskmem_pos_enc
def _get_maskmem_pos_enc(self, inference_state, current_out): """ `maskmem_pos_enc` is the same across frames and objects, so we cache it as a constant in the inference session to reduce session storage size. """ model_constants = inference_state["constants"] # "out_maskmem_pos_enc" should be either a list of tensors or None out_maskmem_pos_enc = current_out["maskmem_pos_enc"] if out_maskmem_pos_enc is not None: if "maskmem_pos_enc" not in model_constants: assert isinstance(out_maskmem_pos_enc, list) # only take the slice for one object, since it's same across objects maskmem_pos_enc = [x[0:1].clone() for x in out_maskmem_pos_enc] model_constants["maskmem_pos_enc"] = maskmem_pos_enc else: maskmem_pos_enc = model_constants["maskmem_pos_enc"] # expand the cached maskmem_pos_enc to the actual batch size batch_size = out_maskmem_pos_enc[0].size(0) expanded_maskmem_pos_enc = [ x.expand(batch_size, -1, -1, -1) for x in maskmem_pos_enc ] else: expanded_maskmem_pos_enc = None return expanded_maskmem_pos_enc
@torch.inference_mode() def remove_object(self, inference_state, obj_id, strict=False, need_output=True): """ Remove an object id from the tracking state. If strict is True, we check whether the object id actually exists and raise an error if it doesn't exist. """ old_obj_idx_to_rm = inference_state["obj_id_to_idx"].get(obj_id, None) updated_frames = [] # Check whether this object_id to remove actually exists and possibly raise an error. if old_obj_idx_to_rm is None: if not strict: return inference_state["obj_ids"], updated_frames raise RuntimeError( f"Cannot remove object id {obj_id} as it doesn't exist. " f"All existing object ids: {inference_state['obj_ids']}." )
# If this is the only remaining object id, we simply reset the state. if len(inference_state["obj_id_to_idx"]) == 1: self.clear_all_points_in_video(inference_state) return inference_state["obj_ids"], updated_frames
# There are still remaining objects after removing this object id. In this case, # we need to delete the object storage from inference state tensors. # Step 0: clear the input on those frames where this object id has point or mask input # (note that this step is required as it might downgrade conditioning frames to # non-conditioning ones) obj_input_frames_inds = set() obj_input_frames_inds.update( inference_state["point_inputs_per_obj"][old_obj_idx_to_rm] ) obj_input_frames_inds.update( inference_state["mask_inputs_per_obj"][old_obj_idx_to_rm] ) for frame_idx in obj_input_frames_inds: self.clear_all_points_in_frame( inference_state, frame_idx, obj_id, need_output=False )
# Step 1: Update the object id mapping (note that it must be done after Step 0, # since Step 0 still requires the old object id mappings in inference_state) old_obj_ids = inference_state["obj_ids"] old_obj_inds = list(range(len(old_obj_ids))) remain_old_obj_inds = old_obj_inds.copy() remain_old_obj_inds.remove(old_obj_idx_to_rm) new_obj_ids = [old_obj_ids[old_idx] for old_idx in remain_old_obj_inds] new_obj_inds = list(range(len(new_obj_ids))) # build new mappings old_idx_to_new_idx = dict(zip(remain_old_obj_inds, new_obj_inds)) inference_state["obj_id_to_idx"] = dict(zip(new_obj_ids, new_obj_inds)) inference_state["obj_idx_to_id"] = dict(zip(new_obj_inds, new_obj_ids)) inference_state["obj_ids"] = new_obj_ids
# Step 2: For per-object tensor storage, we shift their obj_idx in the dict keys. # (note that "consolidated_frame_inds" doesn't need to be updated in this step as # it's already handled in Step 0) def _map_keys(container): new_kvs = [] for k in old_obj_inds: v = container.pop(k) if k in old_idx_to_new_idx: new_kvs.append((old_idx_to_new_idx[k], v)) container.update(new_kvs)
_map_keys(inference_state["point_inputs_per_obj"]) _map_keys(inference_state["mask_inputs_per_obj"]) _map_keys(inference_state["output_dict_per_obj"]) _map_keys(inference_state["temp_output_dict_per_obj"])
# Step 3: For packed tensor storage, we index the remaining ids and rebuild the per-object slices. def _slice_state(output_dict, storage_key): for frame_idx, out in output_dict[storage_key].items(): out["maskmem_features"] = out["maskmem_features"][remain_old_obj_inds] out["maskmem_pos_enc"] = [ x[remain_old_obj_inds] for x in out["maskmem_pos_enc"] ] # "maskmem_pos_enc" is the same across frames, so we only need to store one copy of it out["maskmem_pos_enc"] = self._get_maskmem_pos_enc(inference_state, out) out["pred_masks"] = out["pred_masks"][remain_old_obj_inds] out["obj_ptr"] = out["obj_ptr"][remain_old_obj_inds] out["object_score_logits"] = out["object_score_logits"][ remain_old_obj_inds ] if self.use_memory_selection: out["iou_score"] = out["iou_score"][remain_old_obj_inds] out["eff_iou_score"] = self.cal_mem_score( out["object_score_logits"], out["iou_score"] ) # recalculate the memory frame score # also update the per-object slices self._add_output_per_object( inference_state, frame_idx, out, storage_key )
_slice_state(inference_state["output_dict"], "cond_frame_outputs") _slice_state(inference_state["output_dict"], "non_cond_frame_outputs")
# Step 4: Further collect the outputs on those frames in `obj_input_frames_inds`, which # could show an updated mask for objects previously occluded by the object being removed if need_output: temp_output_dict_per_obj = inference_state["temp_output_dict_per_obj"] for frame_idx in obj_input_frames_inds: is_cond = any( frame_idx in obj_temp_output_dict["cond_frame_outputs"] for obj_temp_output_dict in temp_output_dict_per_obj.values() ) consolidated_out = self._consolidate_temp_output_across_obj( inference_state, frame_idx, is_cond=is_cond, run_mem_encoder=False, consolidate_at_video_res=True, ) _, video_res_masks = self._get_orig_video_res_output( inference_state, consolidated_out["pred_masks_video_res"] ) updated_frames.append((frame_idx, video_res_masks))
return inference_state["obj_ids"], updated_frames
def _clear_non_cond_mem_around_input(self, inference_state, frame_idx): """ Remove the non-conditioning memory around the input frame. When users provide correction clicks, the surrounding frames' non-conditioning memories can still contain outdated object appearance information and could confuse the model.
This method clears those non-conditioning memories surrounding the interacted frame to avoid giving the model both old and new information about the object. """ r = self.memory_temporal_stride_for_eval frame_idx_begin = frame_idx - r * self.num_maskmem frame_idx_end = frame_idx + r * self.num_maskmem batch_size = self._get_obj_num(inference_state) for obj_idx in range(batch_size): obj_output_dict = inference_state["output_dict_per_obj"][obj_idx] non_cond_frame_outputs = obj_output_dict["non_cond_frame_outputs"] for t in range(frame_idx_begin, frame_idx_end + 1): non_cond_frame_outputs.pop(t, None)
def _suppress_shrinked_masks( self, pred_masks, new_pred_masks, shrink_threshold=0.3 ): area_before = (pred_masks > 0).sum(dim=(-1, -2)) area_after = (new_pred_masks > 0).sum(dim=(-1, -2)) area_before = torch.clamp(area_before, min=1.0) area_ratio = area_after / area_before keep = area_ratio >= shrink_threshold keep_mask = keep[..., None, None].expand_as(pred_masks) pred_masks_after = torch.where( keep_mask, pred_masks, torch.clamp(pred_masks, max=-10.0) ) return pred_masks_after
def _suppress_object_pw_area_shrinkage(self, pred_masks): """ This function suppresses masks that shrink in area after applying pixelwise non-overlapping constriants. Note that the final output can still be overlapping. """ # Apply pixel-wise non-overlapping constraint based on mask scores pixel_level_non_overlapping_masks = super()._apply_non_overlapping_constraints( pred_masks ) # Fully suppress masks with high shrinkage (probably noisy) based on the pixel wise non-overlapping constraints # NOTE: The output of this function can be a no op if none of the masks shrinked by a large factor. pred_masks = self._suppress_shrinked_masks( pred_masks, pixel_level_non_overlapping_masks ) return pred_masks
def _apply_object_wise_non_overlapping_constraints( self, pred_masks, obj_scores, background_value=-10.0 ): """ Applies non-overlapping constraints object wise (i.e. only one object can claim the overlapping region) """ # Replace pixel scores with object scores pred_masks_single_score = torch.where( pred_masks > 0, obj_scores[..., None, None], background_value ) # Apply pixel-wise non-overlapping constraint based on mask scores pixel_level_non_overlapping_masks = super()._apply_non_overlapping_constraints( pred_masks_single_score ) # Replace object scores with pixel scores. Note, that now only one object can claim the overlapping region pred_masks = torch.where( pixel_level_non_overlapping_masks > 0, pred_masks, torch.clamp(pred_masks, max=background_value), ) return pred_masks12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273747576777879808182838485868788899091929394959697989910010110210310410510610710810911011111211311411511611711811912012112212312412512612712812913013113213313413513613713813914014114214314414514614714814915015115215315415515615715815916016116216316416516616716816917017117217317417517617717817918018118218318418518618718818919019119219319419519619719819920020120220320420520620720820921021121221321421521621721821922022122222322422522622722822923023123223323423523623723823924024124224324424524624724824925025125225325425525625725825926026126226326426526626726826927027127227327427527627727827928028128228328428528628728828929029129229329429529629729829930030130230330430530630730830931031131231331431531631731831932032132232332432532632732832933033133233333433533633733833934034134234334434534634734834935035135235335435535635735835936036136236336436536636736836937037137237337437537637737837938038138238338438538638738838939039139239339439539639739839940040140240340440540640740840941041141241341441541641741841942042142242342442542642742842943043143243343443543643743843944044144244344444544644744844945045145245345445545645745845946046146246346446546646746846947047147247347447547647747847948048148248348448548648748848949049149249349449549649749849950050150250350450550650750850951051151251351451551651751851952052152252352452552652752852953053153253353453553653753853954054154254354454554654754854955055155255355455555655755855956056156256356456556656756856957057157257357457557657757857958058158258358458558658758858959059159259359459559659759859960060160260360460560660760860961061161261361461561661761861962062162262362462562662762862963063163263363463563663763863964064164264364464564664764864965065165265365465565665765865966066166266366466566666766866967067167267367467567667767867968068168268368468568668768868969069169269369469569669769869970070170270370470570670770870971071171271371471571671771871972072172272372472572672772872973073173273373473573673773873974074174274374474574674774874975075175275375475575675775875976076176276376476576676776876977077177277377477577677777877978078178278378478578678778878979079179279379479579679779879980080180280380480580680780880981081181281381481581681781881982082182282382482582682782882983083183283383483583683783883984084184284384484584684784884985085185285385485585685785885986086186286386486586686786886987087187287387487587687787887988088188288388488588688788888989089189289389489589689789889990090190290390490590690790890991091191291391491591691791891992092192292392492592692792892993093193293393493593693793893994094194294394494594694794894995095195295395495595695795895996096196296396496596696796896997097197297397497597697797897998098198298398498598698798898999099199299399499599699799899910001001100210031004100510061007100810091010101110121013101410151016101710181019102010211022102310241025102610271028102910301031103210331034103510361037103810391040104110421043104410451046104710481049105010511052105310541055105610571058105910601061106210631064106510661067106810691070107110721073107410751076107710781079108010811082108310841085108610871088108910901091109210931094109510961097109810991100110111021103110411051106110711081109111011111112111311141115111611171118111911201121112211231124112511261127112811291130113111321133113411351136113711381139114011411142114311441145114611471148114911501151115211531154115511561157115811591160116111621163116411651166116711681169117011711172117311741175117611771178117911801181118211831184118511861187118811891190119111921193119411951196119711981199120012011202120312041205120612071208120912101211121212131214121512161217121812191220122112221223122412251226122712281229123012311232123312341235123612371238123912401241124212431244124512461247124812491250125112521253125412551256125712581259126012611262126312641265126612671268126912701271127212731274127512761277127812791280128112821283128412851286128712881289129012911292129312941295129612971298129913001301130213031304130513061307130813091310131113121313131413151316131713181319132013211322132313241325132613271328132913301331133213331334133513361337133813391340134113421343134413451346134713481349135013511352135313541355135613571358135913601361136213631364136513661367136813691370137113721373137413751376137713781379138013811382138313841385138613871388138913901391139213931394139513961397139813991400140114021403140414051406140714081409141014111412141314141415141614171418141914201421142214231424142514261427142814291430143114321433143414351436143714381439144014411442144314441445144614471448144914501451145214531454145514561457145814591460146114621463146414651466146714681469147014711472147314741475147614771478147914801481148214831484148514861487148814891490149114921493149414951496149714981499150015011502150315041505150615071508150915101511151215131514151515161517151815191520152115221523152415251526152715281529153015311532153315341535153615371538153915401541154215431544154515461547154815491550155115521553155415551556155715581559156015611562156315641565156615671568156915701571157215731574157515761577157815791580158115821583158415851586158715881589159015911592159315941595159615971598159916001601160216031604160516061607160816091610161116121613161416151616161716181619162016211622162316241625162616271628162916301631163216331634163516361637163816391640164116421643164416451646164716481649165016511652165316541655165616571658165916601661166216631664166516661667166816691670167116721673167416751676167716781679168016811682168316841685168616871688168916901691169216931694169516961697169816991700170117021703170417051706170717081709# Copyright (c) Meta Platforms, Inc. and affiliates. All Rights Reserved
import loggingfrom collections import defaultdict
import numpy as npimport torchimport torch.distributed as distimport torch.nn.functional as F
from sam3 import perflibfrom sam3.logger import get_loggerfrom sam3.model.act_ckpt_utils import clone_output_wrapperfrom sam3.model.box_ops import box_xywh_to_cxcywh, box_xyxy_to_xywhfrom sam3.model.data_misc import BatchedDatapoint, convert_my_tensors, FindStagefrom sam3.model.geometry_encoders import Promptfrom sam3.model.io_utils import IMAGE_EXTS, load_resource_as_video_framesfrom sam3.model.sam3_tracker_utils import fill_holes_in_mask_scoresfrom sam3.model.sam3_video_base import MaskletConfirmationStatus, Sam3VideoBasefrom sam3.model.utils.misc import copy_data_to_devicefrom sam3.perflib.compile import compile_wrapper, shape_logging_wrapperfrom sam3.perflib.masks_ops import masks_to_boxes as perf_masks_to_boxesfrom torchvision.ops import masks_to_boxesfrom tqdm.auto import tqdm
logger = get_logger(__name__)
class Sam3VideoInference(Sam3VideoBase): TEXT_ID_FOR_TEXT = 0 TEXT_ID_FOR_VISUAL = 1
def __init__( self, image_size=1008, image_mean=(0.5, 0.5, 0.5), image_std=(0.5, 0.5, 0.5), compile_model=False, **kwargs, ): """ hotstart_delay: int, the delay (in #frames) before the model starts to yield output, 0 to disable hotstart delay. hotstart_unmatch_thresh: int, remove the object if it has this many unmatched frames within its hotstart_delay period. If `hotstart_delay` is set to 0, this parameter is ignored. hotstart_dup_thresh: int, remove the object if it has overlapped with another object this many frames within its hotstart_delay period. """ super().__init__(**kwargs) self.image_size = image_size self.image_mean = image_mean self.image_std = image_std self.compile_model = compile_model
@torch.inference_mode() def init_state( self, resource_path, offload_video_to_cpu=False, async_loading_frames=False, video_loader_type="cv2", ): """Initialize an inference state from `resource_path` (an image or a video).""" images, orig_height, orig_width = load_resource_as_video_frames( resource_path=resource_path, image_size=self.image_size, offload_video_to_cpu=offload_video_to_cpu, img_mean=self.image_mean, img_std=self.image_std, async_loading_frames=async_loading_frames, video_loader_type=video_loader_type, ) inference_state = {} inference_state["image_size"] = self.image_size inference_state["num_frames"] = len(images) # the original video height and width, used for resizing final output scores inference_state["orig_height"] = orig_height inference_state["orig_width"] = orig_width # values that don't change across frames (so we only need to hold one copy of them) inference_state["constants"] = {} # inputs on each frame self._construct_initial_input_batch(inference_state, images) # initialize extra states inference_state["tracker_inference_states"] = [] inference_state["tracker_metadata"] = {} inference_state["feature_cache"] = {} inference_state["cached_frame_outputs"] = {} inference_state["action_history"] = [] # for logging user actions inference_state["is_image_only"] = is_image_type(resource_path) return inference_state
@torch.inference_mode() def reset_state(self, inference_state): """Revert `inference_state` to what it was right after initialization.""" inference_state["input_batch"].find_text_batch[0] = "<text placeholder>" inference_state["text_prompt"] = None for t in range(inference_state["num_frames"]): inference_state["input_batch"].find_inputs[t].text_ids[...] = 0 # constructing an output list in inference state (we start with an empty list) inference_state["previous_stages_out"][t] = None inference_state["per_frame_raw_point_input"][t] = None inference_state["per_frame_raw_box_input"][t] = None inference_state["per_frame_visual_prompt"][t] = None inference_state["per_frame_geometric_prompt"][t] = None inference_state["per_frame_cur_step"][t] = 0
inference_state["visual_prompt_embed"] = None inference_state["visual_prompt_mask"] = None inference_state["tracker_inference_states"].clear() inference_state["tracker_metadata"].clear() inference_state["feature_cache"].clear() inference_state["cached_frame_outputs"].clear() inference_state["action_history"].clear() # for logging user actions
def _construct_initial_input_batch(self, inference_state, images): """Construct an initial `BatchedDatapoint` instance as input.""" # 1) img_batch num_frames = len(images) device = self.device
# 2) find_text_batch # "<text placeholder>" will be replaced by the actual text prompt when adding prompts find_text_batch = ["<text placeholder>", "visual"]
# 3) find_inputs input_box_embedding_dim = 258 # historical default input_points_embedding_dim = 257 # historical default stages = [ FindStage( img_ids=[stage_id], text_ids=[0], input_boxes=[torch.zeros(input_box_embedding_dim)], input_boxes_mask=[torch.empty(0, dtype=torch.bool)], input_boxes_label=[torch.empty(0, dtype=torch.long)], input_points=[torch.empty(0, input_points_embedding_dim)], input_points_mask=[torch.empty(0)], object_ids=[], ) for stage_id in range(num_frames) ] for i in range(len(stages)): stages[i] = convert_my_tensors(stages[i])
# construct the final `BatchedDatapoint` and cast to GPU input_batch = BatchedDatapoint( img_batch=images, find_text_batch=find_text_batch, find_inputs=stages, find_targets=[None] * num_frames, find_metadatas=[None] * num_frames, ) input_batch = copy_data_to_device(input_batch, device, non_blocking=True) inference_state["input_batch"] = input_batch
# construct the placeholder interactive prompts and tracking queries bs = 1 inference_state["constants"]["empty_geometric_prompt"] = Prompt( box_embeddings=torch.zeros(0, bs, 4, device=device), box_mask=torch.zeros(bs, 0, device=device, dtype=torch.bool), box_labels=torch.zeros(0, bs, device=device, dtype=torch.long), point_embeddings=torch.zeros(0, bs, 2, device=device), point_mask=torch.zeros(bs, 0, device=device, dtype=torch.bool), point_labels=torch.zeros(0, bs, device=device, dtype=torch.long), )
# constructing an output list in inference state (we start with an empty list) inference_state["previous_stages_out"] = [None] * num_frames inference_state["text_prompt"] = None inference_state["per_frame_raw_point_input"] = [None] * num_frames inference_state["per_frame_raw_box_input"] = [None] * num_frames inference_state["per_frame_visual_prompt"] = [None] * num_frames inference_state["per_frame_geometric_prompt"] = [None] * num_frames inference_state["per_frame_cur_step"] = [0] * num_frames
# placeholders for cached outputs # (note: currently, a single visual prompt embedding is shared for all frames) inference_state["visual_prompt_embed"] = None inference_state["visual_prompt_mask"] = None
def _get_visual_prompt(self, inference_state, frame_idx, boxes_cxcywh, box_labels): """ Handle the case of visual prompt. Currently, in the inference API we do not explicitly distinguish between initial box as visual prompt vs subsequent boxes or boxes after inference for refinement. """ # If the frame hasn't had any inference results before (prompting or propagation), # we treat the first added box prompt as a visual prompt; otherwise, we treat # the first box just as a refinement prompt. is_new_visual_prompt = ( inference_state["per_frame_visual_prompt"][frame_idx] is None and inference_state["previous_stages_out"][frame_idx] is None ) if is_new_visual_prompt: if boxes_cxcywh.size(0) != 1: raise RuntimeError( "visual prompts (box as an initial prompt) should only have one box, " f"but got {boxes_cxcywh.shape=}" ) if not box_labels.item(): logging.warning("A negative box is added as a visual prompt.") # take the first box prompt as a visual prompt device = self.device new_visual_prompt = Prompt( box_embeddings=boxes_cxcywh[None, 0:1, :].to(device), # (seq, bs, 4) box_mask=None, box_labels=box_labels[None, 0:1].to(device), # (seq, bs) point_embeddings=None, point_mask=None, point_labels=None, ) inference_state["per_frame_visual_prompt"][frame_idx] = new_visual_prompt else: new_visual_prompt = None
# `boxes_cxcywh` and `box_labels` contains all the raw box inputs added so far # strip any visual prompt from the input boxes (for geometric prompt encoding) if inference_state["per_frame_visual_prompt"][frame_idx] is not None: boxes_cxcywh = boxes_cxcywh[1:] box_labels = box_labels[1:]
return boxes_cxcywh, box_labels, new_visual_prompt
def _get_processing_order( self, inference_state, start_frame_idx, max_frame_num_to_track, reverse ): num_frames = inference_state["num_frames"] previous_stages_out = inference_state["previous_stages_out"] if all(out is None for out in previous_stages_out) and start_frame_idx is None: raise RuntimeError( "No prompts are received on any frames. Please add prompt on at least one frame before propagation." ) # set start index, end index, and processing order if start_frame_idx is None: # default: start from the earliest frame with input points start_frame_idx = min( t for t, out in enumerate(previous_stages_out) if out is not None ) if max_frame_num_to_track is None: # default: track all the frames in the video max_frame_num_to_track = num_frames if reverse: end_frame_idx = start_frame_idx - max_frame_num_to_track end_frame_idx = max(end_frame_idx, 0) processing_order = range(start_frame_idx - 1, end_frame_idx - 1, -1) else: end_frame_idx = start_frame_idx + max_frame_num_to_track end_frame_idx = min(end_frame_idx, num_frames - 1) processing_order = range(start_frame_idx, end_frame_idx + 1) return processing_order, end_frame_idx
@torch.inference_mode() def propagate_in_video( self, inference_state, start_frame_idx=None, max_frame_num_to_track=None, reverse=False, ): """ Propagate the prompts to get grounding results for the entire video. This method is a generator and yields inference outputs for all frames in the range specified by `start_frame_idx`, `max_frame_num_to_track`, and `reverse`. """ # compile the model (it's a no-op if the model is already compiled) # note that it's intentionally added to `self.propagate_in_video`, so that the first # `self.add_prompt` call will be done in eager mode to fill in the decoder buffers # such as positional encoding cache) self._compile_model()
processing_order, end_frame_idx = self._get_processing_order( inference_state, start_frame_idx, max_frame_num_to_track, reverse=reverse, )
# Store max_frame_num_to_track in feature_cache for downstream methods inference_state["feature_cache"]["tracking_bounds"] = { "max_frame_num_to_track": max_frame_num_to_track, "propagate_in_video_start_frame_idx": start_frame_idx, }
hotstart_buffer = [] hotstart_removed_obj_ids = set() # when deciding whether to output a masklet on `yield_frame_idx`, we check whether the object is confirmed # in a future frame (`unconfirmed_frame_delay` frames after the current frame). For example, if we require # an object to be detected in 3 consecutive frames to be confirmed, then we look 2 frames in the future -- # e.g., we output an object on frame 4 only if it becomes confirmed on frame 6. unconfirmed_status_delay = self.masklet_confirmation_consecutive_det_thresh - 1 unconfirmed_obj_ids_per_frame = {} # frame_idx -> hidden_obj_ids for frame_idx in tqdm( processing_order, desc="propagate_in_video", disable=self.rank > 0 ): out = self._run_single_frame_inference(inference_state, frame_idx, reverse)
if self.hotstart_delay > 0: # accumulate the outputs for the first `hotstart_delay` frames hotstart_buffer.append([frame_idx, out]) # update the object IDs removed by hotstart so that we don't output them if self.rank == 0: hotstart_removed_obj_ids.update(out["removed_obj_ids"]) unconfirmed_obj_ids = out.get("unconfirmed_obj_ids", None) if unconfirmed_obj_ids is not None: unconfirmed_obj_ids_per_frame[frame_idx] = unconfirmed_obj_ids
if frame_idx == end_frame_idx: # we reached the end of propagation -- yield all frames in the buffer yield_list = hotstart_buffer hotstart_buffer = [] elif len(hotstart_buffer) >= self.hotstart_delay: # we have enough frames -- yield and remove the first (oldest) frame from the buffer yield_list = hotstart_buffer[:1] hotstart_buffer = hotstart_buffer[1:] else: # not enough frames yet -- skip yielding yield_list = [] else: yield_list = [(frame_idx, out)] # output the current frame
for yield_frame_idx, yield_out in yield_list: # post-process the output and yield it if self.rank == 0: suppressed_obj_ids = yield_out["suppressed_obj_ids"] unconfirmed_status_frame_idx = ( yield_frame_idx + unconfirmed_status_delay if not reverse else yield_frame_idx - unconfirmed_status_delay )
# Clamp the frame index to stay within video bounds num_frames = inference_state["num_frames"] unconfirmed_status_frame_idx = max( 0, min(unconfirmed_status_frame_idx, num_frames - 1) )
unconfirmed_obj_ids = unconfirmed_obj_ids_per_frame.get( unconfirmed_status_frame_idx, None ) postprocessed_out = self._postprocess_output( inference_state, yield_out, hotstart_removed_obj_ids, suppressed_obj_ids, unconfirmed_obj_ids, )
self._cache_frame_outputs( inference_state, yield_frame_idx, yield_out["obj_id_to_mask"], suppressed_obj_ids=suppressed_obj_ids, removed_obj_ids=hotstart_removed_obj_ids, unconfirmed_obj_ids=unconfirmed_obj_ids, ) else: postprocessed_out = None # no output on other GPUs yield yield_frame_idx, postprocessed_out
def _run_single_frame_inference(self, inference_state, frame_idx, reverse): """ Perform inference on a single frame and get its inference results. This would also update `inference_state`. """ # prepare inputs input_batch = inference_state["input_batch"] tracker_states_local = inference_state["tracker_inference_states"] has_text_prompt = inference_state["text_prompt"] is not None has_geometric_prompt = ( inference_state["per_frame_geometric_prompt"][frame_idx] is not None ) # run inference for the current frame ( obj_id_to_mask, obj_id_to_score, tracker_states_local_new, tracker_metadata_new, frame_stats, _, ) = self._det_track_one_frame( frame_idx=frame_idx, num_frames=inference_state["num_frames"], reverse=reverse, input_batch=input_batch, geometric_prompt=( inference_state["constants"]["empty_geometric_prompt"] if not has_geometric_prompt else inference_state["per_frame_geometric_prompt"][frame_idx] ), tracker_states_local=tracker_states_local, tracker_metadata_prev=inference_state["tracker_metadata"], feature_cache=inference_state["feature_cache"], orig_vid_height=inference_state["orig_height"], orig_vid_width=inference_state["orig_width"], is_image_only=inference_state["is_image_only"], allow_new_detections=has_text_prompt or has_geometric_prompt, ) # update inference state inference_state["tracker_inference_states"] = tracker_states_local_new inference_state["tracker_metadata"] = tracker_metadata_new # use a dummy string in "previous_stages_out" to indicate this frame has outputs inference_state["previous_stages_out"][frame_idx] = "_THIS_FRAME_HAS_OUTPUTS_"
if self.rank == 0: self._cache_frame_outputs(inference_state, frame_idx, obj_id_to_mask)
out = { "obj_id_to_mask": obj_id_to_mask, "obj_id_to_score": obj_id_to_score, # first frame detection score "obj_id_to_tracker_score": tracker_metadata_new[ "obj_id_to_tracker_score_frame_wise" ][frame_idx], } # removed_obj_ids is only needed on rank 0 to handle hotstart delay buffer if self.rank == 0: rank0_metadata = tracker_metadata_new["rank0_metadata"] removed_obj_ids = rank0_metadata["removed_obj_ids"] out["removed_obj_ids"] = removed_obj_ids out["suppressed_obj_ids"] = rank0_metadata["suppressed_obj_ids"][frame_idx] out["frame_stats"] = frame_stats if self.masklet_confirmation_enable: status = rank0_metadata["masklet_confirmation"]["status"] is_unconfirmed = status == MaskletConfirmationStatus.UNCONFIRMED.value out["unconfirmed_obj_ids"] = tracker_metadata_new["obj_ids_all_gpu"][ is_unconfirmed ].tolist() else: out["unconfirmed_obj_ids"] = []
return out
def _postprocess_output( self, inference_state, out, removed_obj_ids=None, suppressed_obj_ids=None, unconfirmed_obj_ids=None, ): obj_id_to_mask = out["obj_id_to_mask"] # low res masks curr_obj_ids = sorted(obj_id_to_mask.keys()) H_video, W_video = inference_state["orig_height"], inference_state["orig_width"] if len(curr_obj_ids) == 0: out_obj_ids = torch.zeros(0, dtype=torch.int64) out_probs = torch.zeros(0, dtype=torch.float32) out_binary_masks = torch.zeros(0, H_video, W_video, dtype=torch.bool) out_boxes_xywh = torch.zeros(0, 4, dtype=torch.float32) else: out_obj_ids = torch.tensor(curr_obj_ids, dtype=torch.int64) out_probs = torch.tensor( [out["obj_id_to_score"][obj_id] for obj_id in curr_obj_ids] ) out_tracker_probs = torch.tensor( [ ( out["obj_id_to_tracker_score"][obj_id] if obj_id in out["obj_id_to_tracker_score"] else 0.0 ) for obj_id in curr_obj_ids ] ) out_binary_masks = torch.cat( [obj_id_to_mask[obj_id] for obj_id in curr_obj_ids], dim=0 )
assert out_binary_masks.dtype == torch.bool keep = out_binary_masks.any(dim=(1, 2)).cpu() # remove masks with 0 areas # hide outputs for those object IDs in `obj_ids_to_hide` obj_ids_to_hide = [] if suppressed_obj_ids is not None: obj_ids_to_hide.extend(suppressed_obj_ids) if removed_obj_ids is not None: obj_ids_to_hide.extend(removed_obj_ids) if unconfirmed_obj_ids is not None: obj_ids_to_hide.extend(unconfirmed_obj_ids) if len(obj_ids_to_hide) > 0: obj_ids_to_hide_t = torch.tensor(obj_ids_to_hide, dtype=torch.int64) keep &= ~torch.isin(out_obj_ids, obj_ids_to_hide_t)
# slice those valid entries from the original outputs keep_idx = torch.nonzero(keep, as_tuple=True)[0] keep_idx_gpu = keep_idx.pin_memory().to( device=out_binary_masks.device, non_blocking=True )
out_obj_ids = torch.index_select(out_obj_ids, 0, keep_idx) out_probs = torch.index_select(out_probs, 0, keep_idx) out_tracker_probs = torch.index_select(out_tracker_probs, 0, keep_idx) out_binary_masks = torch.index_select(out_binary_masks, 0, keep_idx_gpu)
if perflib.is_enabled: out_boxes_xyxy = perf_masks_to_boxes( out_binary_masks, out_obj_ids.tolist() ) else: out_boxes_xyxy = masks_to_boxes(out_binary_masks)
out_boxes_xywh = box_xyxy_to_xywh(out_boxes_xyxy) # convert to xywh format # normalize boxes out_boxes_xywh[..., 0] /= W_video out_boxes_xywh[..., 1] /= H_video out_boxes_xywh[..., 2] /= W_video out_boxes_xywh[..., 3] /= H_video
# apply non-overlapping constraints on the existing masklets if out_binary_masks.shape[0] > 1: assert len(out_binary_masks) == len(out_tracker_probs) out_binary_masks = ( self.tracker._apply_object_wise_non_overlapping_constraints( out_binary_masks.unsqueeze(1), out_tracker_probs.unsqueeze(1).to(out_binary_masks.device), background_value=0, ).squeeze(1) ) > 0
outputs = { "out_obj_ids": out_obj_ids.cpu().numpy(), "out_probs": out_probs.cpu().numpy(), "out_boxes_xywh": out_boxes_xywh.cpu().numpy(), "out_binary_masks": out_binary_masks.cpu().numpy(), "frame_stats": out.get("frame_stats", None), } return outputs
def _cache_frame_outputs( self, inference_state, frame_idx, obj_id_to_mask, suppressed_obj_ids=None, removed_obj_ids=None, unconfirmed_obj_ids=None, ): # Filter out suppressed, removed, and unconfirmed objects from the cache filtered_obj_id_to_mask = obj_id_to_mask.copy()
objects_to_exclude = set() if suppressed_obj_ids is not None: objects_to_exclude.update(suppressed_obj_ids) if removed_obj_ids is not None: objects_to_exclude.update(removed_obj_ids) if unconfirmed_obj_ids is not None: objects_to_exclude.update(unconfirmed_obj_ids)
if objects_to_exclude: for obj_id in objects_to_exclude: if obj_id in filtered_obj_id_to_mask: del filtered_obj_id_to_mask[obj_id]
inference_state["cached_frame_outputs"][frame_idx] = filtered_obj_id_to_mask
def _build_tracker_output( self, inference_state, frame_idx, refined_obj_id_to_mask=None ): assert ( "cached_frame_outputs" in inference_state and frame_idx in inference_state["cached_frame_outputs"] ), "No cached outputs found. Ensure normal propagation has run first to populate the cache." cached_outputs = inference_state["cached_frame_outputs"][frame_idx]
obj_id_to_mask = cached_outputs.copy()
# Update with refined masks if provided if refined_obj_id_to_mask is not None: for obj_id, refined_mask in refined_obj_id_to_mask.items(): assert ( refined_mask is not None ), f"Refined mask data must be provided for obj_id {obj_id}" obj_id_to_mask[obj_id] = refined_mask
return obj_id_to_mask
def _compile_model(self): """Compile the SAM model with torch.compile for speedup.""" is_compiled = getattr(self, "_model_is_compiled", False) if is_compiled or not self.compile_model: return
import torch._dynamo
# a larger cache size to hold varying number of shapes for torch.compile # see https://github.com/pytorch/pytorch/blob/v2.5.1/torch/_dynamo/config.py#L42-L49 torch._dynamo.config.cache_size_limit = 128 torch._dynamo.config.accumulated_cache_size_limit = 2048 torch._dynamo.config.capture_scalar_outputs = True torch._dynamo.config.suppress_errors = True
# Compile module components # skip compilation of `_encode_prompt` since it sometimes tiggger SymInt errors # self._encode_prompt = clone_output_wrapper( # torch.compile(self._encode_prompt, fullgraph=True, mode="max-autotune") # )
## Compile SAM3 model components self.detector.backbone.vision_backbone.forward = clone_output_wrapper( torch.compile( self.detector.backbone.vision_backbone.forward, fullgraph=True, mode="max-autotune", ) ) self.detector.transformer.encoder.forward = clone_output_wrapper( torch.compile( self.detector.transformer.encoder.forward, fullgraph=True, mode="max-autotune", ) ) self.detector.transformer.decoder.forward = clone_output_wrapper( torch.compile( self.detector.transformer.decoder.forward, fullgraph=True, mode="max-autotune", dynamic=False, ) )
self.detector.segmentation_head.forward = clone_output_wrapper( torch.compile( self.detector.segmentation_head.forward, fullgraph=True, mode="max-autotune", ) )
## Compile Tracker model components self.tracker.maskmem_backbone.forward = compile_wrapper( self.tracker.maskmem_backbone.forward, mode="max-autotune", fullgraph=True, dynamic=False, )
self.tracker.transformer.encoder.forward = shape_logging_wrapper( compile_wrapper( self.tracker.transformer.encoder.forward, mode="max-autotune-no-cudagraphs", fullgraph=True, dynamic=True, ), keep_kwargs=["src", "src_pos", "prompt", "prompt_pos"], )
self.tracker.sam_mask_decoder.forward = compile_wrapper( self.tracker.sam_mask_decoder.forward, mode="max-autotune", fullgraph=True, dynamic=False, # Accuracy regression on True )
self._model_is_compiled = True
def _warm_up_vg_propagation(self, inference_state, start_frame_idx=0): # use different tracking score thresholds for each round to simulate different number of output objects num_objects_list = range(self.num_obj_for_compile + 1) new_det_score_thresh_list = [0.3, 0.5, 0.7] num_rounds = len(new_det_score_thresh_list) orig_new_det_thresh = self.new_det_thresh
for i, thresh in enumerate(new_det_score_thresh_list): self.new_det_thresh = thresh for num_objects in num_objects_list: logger.info(f"{i+1}/{num_rounds} warming up model compilation") self.add_prompt( inference_state, frame_idx=start_frame_idx, text_str="cat" ) logger.info( f"{i+1}/{num_rounds} warming up model compilation -- simulating {num_objects}/{self.num_obj_for_compile} objects" ) inference_state = self.add_fake_objects_to_inference_state( inference_state, num_objects, frame_idx=start_frame_idx ) inference_state["tracker_metadata"]["rank0_metadata"].update( { "masklet_confirmation": { "status": np.zeros(num_objects, dtype=np.int64), "consecutive_det_num": np.zeros( num_objects, dtype=np.int64 ), } } ) for _ in self.propagate_in_video( inference_state, start_frame_idx, reverse=False ): pass for _ in self.propagate_in_video( inference_state, start_frame_idx, reverse=True ): pass self.reset_state(inference_state) logger.info( f"{i+1}/{num_rounds} warming up model compilation -- completed round {i+1} out of {num_rounds}" )
# Warm up Tracker memory encoder with varying input shapes num_iters = 3 feat_size = self.tracker.sam_image_embedding_size**2 # 72 * 72 = 5184 hidden_dim = self.tracker.hidden_dim # 256 mem_dim = self.tracker.mem_dim # 64 for _ in tqdm(range(num_iters)): for b in range(1, self.num_obj_for_compile + 1): for i in range( 1, self.tracker.max_cond_frames_in_attn + self.tracker.num_maskmem, ): for j in range( self.tracker.max_cond_frames_in_attn + self.tracker.max_obj_ptrs_in_encoder ): num_obj_ptr_tokens = (hidden_dim // mem_dim) * j src = torch.randn(feat_size, b, hidden_dim, device=self.device) src_pos = torch.randn( feat_size, b, hidden_dim, device=self.device ) prompt = torch.randn( feat_size * i + num_obj_ptr_tokens, b, mem_dim, device=self.device, ) prompt_pos = torch.randn( feat_size * i + num_obj_ptr_tokens, b, mem_dim, device=self.device, )
self.tracker.transformer.encoder.forward( src=src, src_pos=src_pos, prompt=prompt, prompt_pos=prompt_pos, num_obj_ptr_tokens=num_obj_ptr_tokens, )
self.new_det_thresh = orig_new_det_thresh return inference_state
def add_fake_objects_to_inference_state( self, inference_state, num_objects, frame_idx ): new_det_obj_ids_local = np.arange(num_objects) high_res_H, high_res_W = ( self.tracker.maskmem_backbone.mask_downsampler.interpol_size ) new_det_masks = torch.ones( len(new_det_obj_ids_local), high_res_H, high_res_W ).to(self.device)
inference_state["tracker_inference_states"] = self._tracker_add_new_objects( frame_idx=frame_idx, num_frames=inference_state["num_frames"], new_obj_ids=new_det_obj_ids_local, new_obj_masks=new_det_masks, tracker_states_local=inference_state["tracker_inference_states"], orig_vid_height=inference_state["orig_height"], orig_vid_width=inference_state["orig_width"], feature_cache=inference_state["feature_cache"], )
# Synthesize obj_id_to_mask data for cached_frame_outputs to support _build_tracker_output during warmup obj_id_to_mask = {} if num_objects > 0: H_video = inference_state["orig_height"] W_video = inference_state["orig_width"]
video_res_masks = F.interpolate( new_det_masks.unsqueeze(1), # Add channel dimension for interpolation size=(H_video, W_video), mode="bilinear", align_corners=False, ) # (num_objects, 1, H_video, W_video) for i, obj_id in enumerate(new_det_obj_ids_local): obj_id_to_mask[obj_id] = (video_res_masks[i] > 0.0).to(torch.bool) if self.rank == 0: for fidx in range(inference_state["num_frames"]): self._cache_frame_outputs(inference_state, fidx, obj_id_to_mask)
inference_state["tracker_metadata"].update( { "obj_ids_per_gpu": [np.arange(num_objects)], "obj_ids_all_gpu": np.arange(num_objects), # Same as 1 GPU "num_obj_per_gpu": [num_objects], "obj_id_to_score": {i: 1.0 for i in range(num_objects)}, "max_obj_id": num_objects, "rank0_metadata": { "masklet_confirmation": { "status": np.zeros(num_objects, dtype=np.int64), "consecutive_det_num": np.zeros(num_objects, dtype=np.int64), }, "removed_obj_ids": set(), "suppressed_obj_ids": defaultdict(set), }, } ) return inference_state
@torch.inference_mode() @torch.autocast(device_type="cuda", dtype=torch.bfloat16) def warm_up_compilation(self): """ Warm up the model by running a dummy inference to compile the model. This is useful to avoid the compilation overhead in the first inference call. """ if not self.compile_model: return self._warm_up_complete = False if self.device.type != "cuda": raise RuntimeError( f"The model must be on CUDA for warm-up compilation, got {self.device=}." )
# temporally set to single GPU temporarily for warm-up compilation orig_rank = self.rank orig_world_size = self.world_size self.rank = self.detector.rank = 0 self.world_size = self.detector.world_size = 1 orig_recondition_every_nth_frame = self.recondition_every_nth_frame # self.recondition_every_nth_frame = 2
# Get a random video inference_state = self.init_state(resource_path="<load-dummy-video-30>") start_frame_idx = 0
# Run basic propagation warm-up inference_state = self._warm_up_vg_propagation(inference_state, start_frame_idx)
logger.info("Warm-up compilation completed.")
# revert to the original GPU and rank self.rank = self.detector.rank = orig_rank self.world_size = self.detector.world_size = orig_world_size self.recondition_every_nth_frame = orig_recondition_every_nth_frame self._warm_up_complete = True self.tracker.transformer.encoder.forward.set_logging(True)
@torch.inference_mode() def add_prompt( self, inference_state, frame_idx, text_str=None, boxes_xywh=None, box_labels=None, ): """ Add text, point or box prompts on a single frame. This method returns the inference outputs only on the prompted frame.
Note that text prompts are NOT associated with a particular frame (i.e. they apply to all frames). However, we only run inference on the frame specified in `frame_idx`. """ logger.debug("Running add_prompt on frame %d", frame_idx)
num_frames = inference_state["num_frames"] assert ( text_str is not None or boxes_xywh is not None ), "at least one type of prompt (text, boxes) must be provided" assert ( 0 <= frame_idx < num_frames ), f"{frame_idx=} is out of range for a total of {num_frames} frames"
# since it's a semantic prompt, we start over self.reset_state(inference_state)
# 1) add text prompt if text_str is not None and text_str != "visual": inference_state["text_prompt"] = text_str inference_state["input_batch"].find_text_batch[0] = text_str text_id = self.TEXT_ID_FOR_TEXT else: inference_state["text_prompt"] = None inference_state["input_batch"].find_text_batch[0] = "<text placeholder>" text_id = self.TEXT_ID_FOR_VISUAL for t in range(inference_state["num_frames"]): inference_state["input_batch"].find_inputs[t].text_ids[...] = text_id
# 2) handle box prompt assert (boxes_xywh is not None) == (box_labels is not None) if boxes_xywh is not None: boxes_xywh = torch.as_tensor(boxes_xywh, dtype=torch.float32) box_labels = torch.as_tensor(box_labels, dtype=torch.long) # input boxes are expected to be [xmin, ymin, width, height] format # in normalized coordinates of range 0~1, similar to FA assert boxes_xywh.dim() == 2 assert boxes_xywh.size(0) > 0 and boxes_xywh.size(-1) == 4 assert box_labels.dim() == 1 and box_labels.size(0) == boxes_xywh.size(0) boxes_cxcywh = box_xywh_to_cxcywh(boxes_xywh) assert (boxes_xywh >= 0).all().item() and (boxes_xywh <= 1).all().item() assert (boxes_cxcywh >= 0).all().item() and (boxes_cxcywh <= 1).all().item()
new_box_input = boxes_cxcywh, box_labels inference_state["per_frame_raw_box_input"][frame_idx] = new_box_input
# handle the case of visual prompt (also added as an input box from the UI) boxes_cxcywh, box_labels, geometric_prompt = self._get_visual_prompt( inference_state, frame_idx, boxes_cxcywh, box_labels )
inference_state["per_frame_geometric_prompt"][frame_idx] = geometric_prompt
out = self._run_single_frame_inference( inference_state, frame_idx, reverse=False ) return frame_idx, self._postprocess_output(inference_state, out)
@torch.autocast(device_type="cuda", dtype=torch.bfloat16) def forward(self, input: BatchedDatapoint, is_inference: bool = False): """This method is only used for benchmark eval (not used in the demo).""" # set the model to single GPU for benchmark evaluation (to be compatible with trainer) orig_rank = self.rank orig_world_size = self.world_size self.rank = self.detector.rank = 0 self.world_size = self.detector.world_size = 1
# get data text_prompt_ids = input.find_metadatas[0].original_category_id text_prompt_list = input.find_text_batch
# loop over txt prompts tracking_res = defaultdict(dict) # frame_idx --> {obj_id: mask} scores_labels = defaultdict(tuple) # obj_id --> (score, text_prompt_id) inference_state = self.init_state(resource_path=input.raw_images) for prompt_id, prompt in zip(text_prompt_ids, text_prompt_list): self.add_prompt(inference_state, frame_idx=0, text_str=prompt) start_obj_id = max(scores_labels.keys(), default=-1) + 1 # prev max + 1
# propagate the prompts obj_ids_this_prompt = set() for frame_idx, out in self.propagate_in_video( inference_state, start_frame_idx=0, max_frame_num_to_track=inference_state["num_frames"], reverse=False, ): current_frame_res = tracking_res[frame_idx] for obj_id, mask in zip(out["out_obj_ids"], out["out_binary_masks"]): mask_tensor = torch.tensor(mask[None], dtype=torch.bool) current_frame_res[obj_id + start_obj_id] = mask_tensor obj_ids_this_prompt.update(current_frame_res.keys())
obj_id_to_score = inference_state["tracker_metadata"]["obj_id_to_score"] for obj_id, score in obj_id_to_score.items(): if obj_id + start_obj_id in obj_ids_this_prompt: score_tensor = torch.tensor(score, dtype=torch.float32) scores_labels[obj_id + start_obj_id] = (score_tensor, prompt_id)
self.reset_state(inference_state)
video_id = input.find_metadatas[0].original_image_id[0].cpu().item() preds = self.prep_for_evaluator(input.raw_images, tracking_res, scores_labels)
# revert the model to the original GPU and rank self.rank = self.detector.rank = orig_rank self.world_size = self.detector.world_size = orig_world_size return {video_id: preds}
def back_convert(self, targets): # Needed for retraining compatibility with trainer return targets
class Sam3VideoInferenceWithInstanceInteractivity(Sam3VideoInference): def __init__( self, use_prev_mem_frame=False, use_stateless_refinement=False, refinement_detector_cond_frame_removal_window=16, **kwargs, ): """ use_prev_mem_frame: bool, whether to condition on previous memory frames for adding points use_stateless_refinement: bool, whether to enable stateless refinement behavior refinement_detector_cond_frame_removal_window: int, we remove a detector conditioning frame if it is within this many frames of a user refined frame. Set to a large value (e.g. 10000) to always remove detector conditioning frames if there is any user refinement in the video. """ super().__init__(**kwargs) self.use_prev_mem_frame = use_prev_mem_frame self.use_stateless_refinement = use_stateless_refinement self.refinement_detector_cond_frame_removal_window = ( refinement_detector_cond_frame_removal_window )
def _init_new_tracker_state(self, inference_state): return self.tracker.init_state( cached_features=inference_state["feature_cache"], video_height=inference_state["orig_height"], video_width=inference_state["orig_width"], num_frames=inference_state["num_frames"], )
@torch.inference_mode() def propagate_in_video( self, inference_state, start_frame_idx=None, max_frame_num_to_track=None, reverse=False, ): # step 1: check which type of propagation to run, should be the same for all GPUs. propagation_type, obj_ids = self.parse_action_history_for_propagation( inference_state ) self.add_action_history( inference_state, action_type=propagation_type, obj_ids=obj_ids, frame_idx=start_frame_idx, )
# step 2: run full VG propagation if propagation_type == "propagation_full": logger.debug(f"Running full VG propagation (reverse={reverse}).") yield from super().propagate_in_video( inference_state, start_frame_idx=start_frame_idx, max_frame_num_to_track=max_frame_num_to_track, reverse=reverse, ) return
# step 3: run Tracker partial propagation or direct fetch existing predictions assert propagation_type in ["propagation_partial", "propagation_fetch"] logger.debug( f"Running Tracker propagation for objects {obj_ids} and merging it with existing VG predictions (reverse={reverse})." if propagation_type == "propagation_partial" else f"Fetching existing VG predictions without running any propagation (reverse={reverse})." ) processing_order, _ = self._get_processing_order( inference_state, start_frame_idx=start_frame_idx, max_frame_num_to_track=max_frame_num_to_track, reverse=reverse, )
tracker_metadata = inference_state["tracker_metadata"]
# if fetch just return from output if propagation_type == "propagation_fetch": for frame_idx in tqdm(processing_order): if self.rank == 0: obj_id_to_mask = inference_state["cached_frame_outputs"].get( frame_idx, {} ) # post processing - remove suppressed obj_ids obj_id_to_score = tracker_metadata["obj_id_to_score"] suppressed_obj_ids = tracker_metadata["rank0_metadata"][ "suppressed_obj_ids" ][frame_idx] obj_id_to_tracker_score = tracker_metadata[ "obj_id_to_tracker_score_frame_wise" ][frame_idx]
out = { "obj_id_to_mask": obj_id_to_mask, "obj_id_to_score": obj_id_to_score, "obj_id_to_tracker_score": obj_id_to_tracker_score, } yield ( frame_idx, self._postprocess_output( inference_state, out, suppressed_obj_ids=suppressed_obj_ids ), ) else: yield frame_idx, None
return
# get Tracker inference states containing selected obj_ids if propagation_type == "propagation_partial": # can be empty for GPUs where objects are not in their inference states tracker_states_local = self._get_tracker_inference_states_by_obj_ids( inference_state, obj_ids ) for tracker_state in tracker_states_local: self.tracker.propagate_in_video_preflight( tracker_state, run_mem_encoder=True )
for frame_idx in tqdm(processing_order): # run Tracker propagation if propagation_type == "propagation_partial": self._prepare_backbone_feats(inference_state, frame_idx, reverse) obj_ids_local, low_res_masks_local, tracker_scores_local = ( self._propogate_tracker_one_frame_local_gpu( tracker_states_local, frame_idx=frame_idx, reverse=reverse, run_mem_encoder=True, ) )
# broadcast refined object tracker scores and masks to all GPUs # handle multiple objects that can be located on different GPUs refined_obj_data = {} # obj_id -> (score, mask_video_res)
# Collect data for objects on this GPU local_obj_data = {} for obj_id in obj_ids: obj_rank = self._get_gpu_id_by_obj_id(inference_state, obj_id) if self.rank == obj_rank and obj_id in obj_ids_local: refined_obj_idx = obj_ids_local.index(obj_id) refined_mask_low_res = low_res_masks_local[ refined_obj_idx ] # (H_low_res, W_low_res) refined_score = tracker_scores_local[refined_obj_idx]
# Keep low resolution for broadcasting to reduce communication cost local_obj_data[obj_id] = (refined_score, refined_mask_low_res)
# Broadcast data from each GPU that has refined objects if self.world_size > 1: for obj_id in obj_ids: obj_rank = self._get_gpu_id_by_obj_id(inference_state, obj_id) if self.rank == obj_rank: # This GPU has the object, broadcast its data data_to_broadcast = local_obj_data.get(obj_id, None) data_list = [ (data_to_broadcast[0].cpu(), data_to_broadcast[1].cpu()) ] self.broadcast_python_obj_cpu(data_list, src=obj_rank) if data_to_broadcast is not None: refined_obj_data[obj_id] = data_to_broadcast elif self.rank != obj_rank: # This GPU doesn't have the object, receive data data_list = [None] self.broadcast_python_obj_cpu(data_list, src=obj_rank) refined_obj_data[obj_id] = ( data_list[0][0].to(self.device), data_list[0][1].to(self.device), ) else: # Single GPU case refined_obj_data = local_obj_data
# Update Tracker scores for all refined objects for obj_id, (refined_score, _) in refined_obj_data.items(): tracker_metadata["obj_id_to_tracker_score_frame_wise"][ frame_idx ].update({obj_id: refined_score.item()})
if self.rank == 0: # get predictions from Tracker inference states, it includes the original # VG predictions and the refined predictions from interactivity.
# Prepare refined masks dictionary - upscale to video resolution after broadcast refined_obj_id_to_mask = {} for obj_id, (_, refined_mask_low_res) in refined_obj_data.items(): refined_mask_video_res = ( self._convert_low_res_mask_to_video_res( refined_mask_low_res, inference_state ) ) # (1, H_video, W_video) bool refined_obj_id_to_mask[obj_id] = refined_mask_video_res
obj_id_to_mask = self._build_tracker_output( inference_state, frame_idx, refined_obj_id_to_mask ) out = { "obj_id_to_mask": obj_id_to_mask, "obj_id_to_score": tracker_metadata["obj_id_to_score"], "obj_id_to_tracker_score": tracker_metadata[ "obj_id_to_tracker_score_frame_wise" ][frame_idx], } suppressed_obj_ids = tracker_metadata["rank0_metadata"][ "suppressed_obj_ids" ][frame_idx] self._cache_frame_outputs( inference_state, frame_idx, obj_id_to_mask, suppressed_obj_ids=suppressed_obj_ids, ) suppressed_obj_ids = tracker_metadata["rank0_metadata"][ "suppressed_obj_ids" ][frame_idx] yield ( frame_idx, self._postprocess_output( inference_state, out, suppressed_obj_ids=suppressed_obj_ids ), ) else: yield frame_idx, None
def add_action_history( self, inference_state, action_type, frame_idx=None, obj_ids=None ): """ action_history is used to automatically decide what to do during propagation. action_type: one of ["add", "remove", "refine"] + ["propagation_full", "propagation_partial", "propagation_fetch"] """ instance_actions = ["add", "remove", "refine"] propagation_actions = [ "propagation_full", "propagation_partial", "propagation_fetch", ] assert ( action_type in instance_actions + propagation_actions ), f"Invalid action type: {action_type}, must be one of {instance_actions + propagation_actions}" action = { "type": action_type, "frame_idx": frame_idx, "obj_ids": obj_ids, } inference_state["action_history"].append(action)
def _has_object_been_refined(self, inference_state, obj_id): action_history = inference_state["action_history"] for action in action_history: if action["type"] in ["add", "refine"] and action.get("obj_ids"): if obj_id in action["obj_ids"]: return True return False
def parse_action_history_for_propagation(self, inference_state): """ Parse the actions in history before the last propagation and prepare for the next propagation. We support multiple actions (add/remove/refine) between two propagations. If we had an action history similar to this ["propagate", "add", "refine", "remove", "add"], the next propagation would remove the removed object, and also propagate the two added/refined objects.
Returns: propagation_type: one of ["propagation_full", "propagation_partial", "propagation_fetch"] - "propagation_full": run VG propagation for all objects - "propagation_partial": run Tracker propagation for selected objects, useful for add/refine actions - "propagation_fetch": fetch existing VG predictions without running any propagation obj_ids: list of object ids to run Tracker propagation on if propagation_type is "propagation_partial". """ action_history = inference_state["action_history"] if len(action_history) == 0: # we run propagation for the first time return "propagation_full", None
if "propagation" in action_history[-1]["type"]: if action_history[-1]["type"] in ["propagation_fetch"]: # last propagation is direct fetch, we fetch existing predictions return "propagation_fetch", None elif action_history[-1]["type"] in [ "propagation_partial", "propagation_full", ]: # we do fetch prediction if we have already run propagation twice or we have run # propagation once and it is from the first frame or last frame. if ( len(action_history) > 1 and action_history[-2]["type"] in ["propagation_partial", "propagation_full"] ) or action_history[-1]["frame_idx"] in [ 0, inference_state["num_frames"] - 1, ]: # we have run both forward and backward partial/full propagation return "propagation_fetch", None else: # we have run partial/full forward or backward propagation once, need run it for the rest of the frames return action_history[-1]["type"], action_history[-1]["obj_ids"]
# parse actions since last propagation obj_ids = [] for action in action_history[::-1]: if "propagation" in action["type"]: # we reached the last propagation action, stop parsing break if action["type"] in ["add", "refine"]: obj_ids.extend(action["obj_ids"]) # else action["type"] == "remove": noop obj_ids = list(set(obj_ids)) if len(obj_ids) > 0 else None propagation_type = ( "propagation_partial" if obj_ids is not None else "propagation_fetch" ) return propagation_type, obj_ids
def remove_object(self, inference_state, obj_id, is_user_action=False): """ We try to remove object from tracker states on every GPU, it will do nothing for states without this object. """ obj_rank = self._get_gpu_id_by_obj_id(inference_state, obj_id) assert obj_rank is not None, f"Object {obj_id} not found in any GPU."
tracker_states_local = inference_state["tracker_inference_states"] if self.rank == obj_rank: self._tracker_remove_object(tracker_states_local, obj_id)
if is_user_action: self.add_action_history( inference_state, action_type="remove", obj_ids=[obj_id] )
# update metadata tracker_metadata = inference_state["tracker_metadata"] _obj_ids = tracker_metadata["obj_ids_per_gpu"][obj_rank] tracker_metadata["obj_ids_per_gpu"][obj_rank] = _obj_ids[_obj_ids != obj_id] tracker_metadata["num_obj_per_gpu"][obj_rank] = len( tracker_metadata["obj_ids_per_gpu"][obj_rank] ) tracker_metadata["obj_ids_all_gpu"] = np.concatenate( tracker_metadata["obj_ids_per_gpu"] ) tracker_metadata["obj_id_to_score"].pop(obj_id, None) # tracker_metadata["max_obj_id"] # we do not reuse the object id, so we do not update it here
# Clean up cached frame outputs to remove references to the deleted object if "cached_frame_outputs" in inference_state: for frame_idx in inference_state["cached_frame_outputs"]: frame_cache = inference_state["cached_frame_outputs"][frame_idx] if obj_id in frame_cache: del frame_cache[obj_id]
def _get_gpu_id_by_obj_id(self, inference_state, obj_id): """ Locate GPU ID for a given object. """ obj_ids_per_gpu = inference_state["tracker_metadata"]["obj_ids_per_gpu"] for rank, obj_ids in enumerate(obj_ids_per_gpu): if obj_id in obj_ids: return rank return None # object not found in any GPU
def _get_tracker_inference_states_by_obj_ids(self, inference_state, obj_ids): """ Get the Tracker inference states that contain the given object ids. This is used to run partial Tracker propagation on a single object/bucket. Possibly multiple or zero states can be returned. """ states = [ state for state in inference_state["tracker_inference_states"] if set(obj_ids) & set(state["obj_ids"]) ] return states
def _prepare_backbone_feats(self, inference_state, frame_idx, reverse): input_batch = inference_state["input_batch"] feature_cache = inference_state["feature_cache"] num_frames = inference_state["num_frames"] geometric_prompt = ( inference_state["constants"]["empty_geometric_prompt"] if inference_state["per_frame_geometric_prompt"][frame_idx] is None else inference_state["per_frame_geometric_prompt"][frame_idx] ) _ = self.run_backbone_and_detection( frame_idx=frame_idx, num_frames=num_frames, input_batch=input_batch, geometric_prompt=geometric_prompt, feature_cache=feature_cache, reverse=reverse, allow_new_detections=True, )
@torch.inference_mode() def add_prompt( self, inference_state, frame_idx, text_str=None, boxes_xywh=None, box_labels=None, points=None, point_labels=None, obj_id=None, rel_coordinates=True, ): if points is not None: # Tracker instance prompts assert ( text_str is None and boxes_xywh is None ), "When points are provided, text_str and boxes_xywh must be None." assert ( obj_id is not None ), "When points are provided, obj_id must be provided." return self.add_tracker_new_points( inference_state, frame_idx, obj_id=obj_id, points=points, labels=point_labels, rel_coordinates=rel_coordinates, use_prev_mem_frame=self.use_prev_mem_frame, ) else: # SAM3 prompts return super().add_prompt( inference_state, frame_idx, text_str=text_str, boxes_xywh=boxes_xywh, box_labels=box_labels, )
@torch.inference_mode() def add_tracker_new_points( self, inference_state, frame_idx, obj_id, points, labels, rel_coordinates=True, use_prev_mem_frame=False, ): """Add a new point prompt to Tracker. Suppporting instance refinement to existing objects by passing existing obj_id or adding a new object by passing a new obj_id. use_prev_mem_frame=False to disable cross attention to previous memory frames. Every GPU returns the same results, and results should contain all masks including these masks not refined or not added by the current user points. """ assert obj_id is not None, "obj_id must be provided to add new points" tracker_metadata = inference_state["tracker_metadata"] if tracker_metadata == {}: # initialize masklet metadata if it's uninitialized (empty dict) tracker_metadata.update(self._initialize_metadata())
obj_rank = self._get_gpu_id_by_obj_id(inference_state, obj_id)
# prepare feature self._prepare_backbone_feats(inference_state, frame_idx, reverse=False)
object_has_been_refined = self._has_object_been_refined(inference_state, obj_id) if ( obj_rank is not None and self.use_stateless_refinement and not object_has_been_refined ): # The first time we start refinement on the object, we remove it. logger.debug( f"[rank={self.rank}] Removing object {obj_id} before refinement." ) self.remove_object(inference_state, obj_id, is_user_action=False) obj_rank = None
if obj_rank is None: # new object, we assign it a GPU and create a new inference state if limit allows num_prev_obj = np.sum(tracker_metadata["num_obj_per_gpu"]) if num_prev_obj >= self.max_num_objects: logger.warning( f"add_tracker_new_points: cannot add a new object as we are already tracking {num_prev_obj=} " f"masklets (under {self.max_num_objects=})" ) obj_ids = [] H_low_res = W_low_res = self.tracker.low_res_mask_size H_video_res = inference_state["orig_height"] W_video_res = inference_state["orig_width"] low_res_masks = torch.zeros(0, 1, H_low_res, W_low_res) video_res_masks = torch.zeros(0, 1, H_video_res, W_video_res) return frame_idx, obj_ids, low_res_masks, video_res_masks
new_det_gpu_ids = self._assign_new_det_to_gpus( new_det_num=1, prev_workload_per_gpu=tracker_metadata["num_obj_per_gpu"], ) obj_rank = new_det_gpu_ids[0]
# get tracker inference state for the new object if self.rank == obj_rank: # for batched inference, we create a new inference state tracker_state = self._init_new_tracker_state(inference_state) inference_state["tracker_inference_states"].append(tracker_state)
# update metadata tracker_metadata["obj_ids_per_gpu"][obj_rank] = np.concatenate( [ tracker_metadata["obj_ids_per_gpu"][obj_rank], np.array([obj_id], dtype=np.int64), ] ) tracker_metadata["num_obj_per_gpu"][obj_rank] = len( tracker_metadata["obj_ids_per_gpu"][obj_rank] ) tracker_metadata["obj_ids_all_gpu"] = np.concatenate( tracker_metadata["obj_ids_per_gpu"] ) tracker_metadata["max_obj_id"] = max(tracker_metadata["max_obj_id"], obj_id)
logger.debug( f"[rank={self.rank}] Adding new object with id {obj_id} at frame {frame_idx}." ) self.add_action_history( inference_state, "add", frame_idx=frame_idx, obj_ids=[obj_id] ) else: # existing object, for refinement if self.rank == obj_rank: tracker_states = self._get_tracker_inference_states_by_obj_ids( inference_state, [obj_id] ) assert ( len(tracker_states) == 1 ), f"[rank={self.rank}] Multiple Tracker inference states found for the same object id." tracker_state = tracker_states[0]
# log logger.debug( f"[rank={self.rank}] Refining existing object with id {obj_id} at frame {frame_idx}." ) self.add_action_history( inference_state, "refine", frame_idx=frame_idx, obj_ids=[obj_id] )
# assign higher score to added/refined object tracker_metadata["obj_id_to_score"][obj_id] = 1.0 tracker_metadata["obj_id_to_tracker_score_frame_wise"][frame_idx][obj_id] = 1.0
if self.rank == 0: rank0_metadata = tracker_metadata.get("rank0_metadata", {})
if "removed_obj_ids" in rank0_metadata: rank0_metadata["removed_obj_ids"].discard(obj_id)
if "suppressed_obj_ids" in rank0_metadata: for frame_id in rank0_metadata["suppressed_obj_ids"]: rank0_metadata["suppressed_obj_ids"][frame_id].discard(obj_id)
if "masklet_confirmation" in rank0_metadata: obj_ids_all_gpu = tracker_metadata["obj_ids_all_gpu"] obj_indices = np.where(obj_ids_all_gpu == obj_id)[0] if len(obj_indices) > 0: obj_idx = obj_indices[0] if obj_idx < len(rank0_metadata["masklet_confirmation"]["status"]): rank0_metadata["masklet_confirmation"]["status"][obj_idx] = 1 rank0_metadata["masklet_confirmation"]["consecutive_det_num"][ obj_idx ] = self.masklet_confirmation_consecutive_det_thresh
if self.rank == obj_rank: frame_idx, obj_ids, low_res_masks, video_res_masks = ( self.tracker.add_new_points( inference_state=tracker_state, frame_idx=frame_idx, obj_id=obj_id, points=points, labels=labels, clear_old_points=True, rel_coordinates=rel_coordinates, use_prev_mem_frame=use_prev_mem_frame, ) )
if video_res_masks is not None and len(video_res_masks) > 0: video_res_masks = fill_holes_in_mask_scores( video_res_masks, # shape (N, 1, H_video, W_video) max_area=self.fill_hole_area, fill_holes=True, remove_sprinkles=True, )
# Since the mem encoder has already run for the current input points? self.tracker.propagate_in_video_preflight( tracker_state, run_mem_encoder=True ) # Clear detector conditioning frames when user clicks are received to allow # model updating masks on these frames. It is a noop if user is refining on the # detector conditioning frames or adding new objects. self.clear_detector_added_cond_frame_in_tracker( tracker_state, obj_id, frame_idx )
# fetch results from states and gather across GPUs # Use optimized caching approach to avoid reprocessing unmodified objects if self.rank == obj_rank and len(obj_ids) > 0: new_mask_data = (video_res_masks[obj_ids.index(obj_id)] > 0.0).to( torch.bool ) else: new_mask_data = None # Broadcast the new mask data across all ranks for consistency if self.world_size > 1: data_list = [new_mask_data.cpu() if new_mask_data is not None else None] self.broadcast_python_obj_cpu(data_list, src=obj_rank) new_mask_data = data_list[0].to(self.device)
if self.rank == 0: obj_id_to_mask = self._build_tracker_output( inference_state, frame_idx, {obj_id: new_mask_data} if new_mask_data is not None else None, ) # post processing - remove suppressed obj_ids obj_id_to_score = tracker_metadata["obj_id_to_score"] suppressed_obj_ids = tracker_metadata["rank0_metadata"][ "suppressed_obj_ids" ][frame_idx] obj_id_to_tracker_score = tracker_metadata[ "obj_id_to_tracker_score_frame_wise" ][frame_idx]
out = { "obj_id_to_mask": obj_id_to_mask, "obj_id_to_score": obj_id_to_score, "obj_id_to_tracker_score": obj_id_to_tracker_score, } self._cache_frame_outputs( inference_state, frame_idx, obj_id_to_mask, suppressed_obj_ids=suppressed_obj_ids, ) return frame_idx, self._postprocess_output( inference_state, out, suppressed_obj_ids=suppressed_obj_ids ) else: return frame_idx, None # no output on other GPUs
def _gather_obj_id_to_mask_across_gpus(self, inference_state, obj_id_to_mask_local): """Gather obj_id_to_mask from all GPUs. Optionally resize the masks to the video resolution.""" tracker_metadata = inference_state["tracker_metadata"]
# concatenate the output masklets from all local inference states H_mask = W_mask = self.tracker.low_res_mask_size obj_ids_local = tracker_metadata["obj_ids_per_gpu"][self.rank] low_res_masks_local = [] for obj_id in obj_ids_local: if obj_id in obj_id_to_mask_local: low_res_masks_local.append(obj_id_to_mask_local[obj_id]) else: low_res_masks_local.append( torch.full((H_mask, W_mask), -1024.0, device=self.device) ) if len(low_res_masks_local) > 0: low_res_masks_local = torch.stack(low_res_masks_local, dim=0) # (N, H, W) assert low_res_masks_local.shape[1:] == (H_mask, W_mask) else: low_res_masks_local = torch.zeros(0, H_mask, W_mask, device=self.device)
# all-gather `low_res_masks_local` into `low_res_masks_global` # - low_res_masks_global: Tensor -- (num_global_obj, H_mask, W_mask) if self.world_size > 1: low_res_masks_local = low_res_masks_local.float().contiguous() low_res_masks_peers = [ low_res_masks_local.new_empty(num_obj, H_mask, W_mask) for num_obj in tracker_metadata["num_obj_per_gpu"] ] dist.all_gather(low_res_masks_peers, low_res_masks_local) low_res_masks_global = torch.cat(low_res_masks_peers, dim=0) else: low_res_masks_global = low_res_masks_local return low_res_masks_global
def _convert_low_res_mask_to_video_res(self, low_res_mask, inference_state): """ Convert a low-res mask to video resolution, matching the format expected by _build_tracker_output.
Args: low_res_mask: Tensor of shape (H_low_res, W_low_res) inference_state: Contains video dimensions
Returns: video_res_mask: Tensor of shape (1, H_video, W_video) bool """ if low_res_mask is None: return None
# Convert to 3D for interpolation: (H_low_res, W_low_res) -> (1, H_low_res, W_low_res) low_res_mask_3d = low_res_mask.unsqueeze(0).unsqueeze(0)
# Get video dimensions H_video = inference_state["orig_height"] W_video = inference_state["orig_width"]
video_res_mask = F.interpolate( low_res_mask_3d.float(), size=(H_video, W_video), mode="bilinear", align_corners=False, ) # (1, H_video, W_video)
# Convert to boolean - already in the right shape! return (video_res_mask.squeeze(0) > 0.0).to(torch.bool)
def clear_detector_added_cond_frame_in_tracker( self, tracker_state, obj_id, refined_frame_idx ): """Clear detector added conditioning frame if it is within a predefined window of the refined frame. This allow model to update masks on these frames.""" obj_idx = self.tracker._obj_id_to_idx(tracker_state, obj_id)
mask_only_cond_frame_indices = [] window = self.refinement_detector_cond_frame_removal_window for frame_idx in tracker_state["mask_inputs_per_obj"][obj_idx]: if frame_idx not in tracker_state["point_inputs_per_obj"][obj_idx]: # clear conditioning frames within a window of the refined frame if abs(frame_idx - refined_frame_idx) <= window: mask_only_cond_frame_indices.append(frame_idx)
# clear if len(mask_only_cond_frame_indices) > 0: for frame_idx in mask_only_cond_frame_indices: # obj_ids_on_this_frame is essentially all obj_ids in the state # since they are bucket batched obj_ids_on_this_frame = tracker_state["obj_id_to_idx"].keys() for obj_id2 in obj_ids_on_this_frame: self.tracker.clear_all_points_in_frame( tracker_state, frame_idx, obj_id2, need_output=False ) logger.debug( f"Cleared detector mask only conditioning frames ({mask_only_cond_frame_indices}) in Tracker." ) return
def is_image_type(resource_path: str) -> bool: if isinstance(resource_path, list): return len(resource_path) == 1 return resource_path.lower().endswith(tuple(IMAGE_EXTS))123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782783784785786787788789790791792793# Copyright (c) Meta Platforms, Inc. and affiliates. All Rights Reserved
import osfrom typing import Optional
import torchimport torch.nn as nnfrom huggingface_hub import hf_hub_downloadfrom iopath.common.file_io import g_pathmgrfrom sam3.model.decoder import ( TransformerDecoder, TransformerDecoderLayer, TransformerDecoderLayerv2, TransformerEncoderCrossAttention,)from sam3.model.encoder import TransformerEncoderFusion, TransformerEncoderLayerfrom sam3.model.geometry_encoders import SequenceGeometryEncoderfrom sam3.model.maskformer_segmentation import PixelDecoder, UniversalSegmentationHeadfrom sam3.model.memory import ( CXBlock, SimpleFuser, SimpleMaskDownSampler, SimpleMaskEncoder,)from sam3.model.model_misc import ( DotProductScoring, MLP, MultiheadAttentionWrapper as MultiheadAttention, TransformerWrapper,)from sam3.model.necks import Sam3DualViTDetNeckfrom sam3.model.position_encoding import PositionEmbeddingSinefrom sam3.model.sam1_task_predictor import SAM3InteractiveImagePredictorfrom sam3.model.sam3_image import Sam3Image, Sam3ImageOnVideoMultiGPUfrom sam3.model.sam3_tracking_predictor import Sam3TrackerPredictorfrom sam3.model.sam3_video_inference import Sam3VideoInferenceWithInstanceInteractivityfrom sam3.model.sam3_video_predictor import Sam3VideoPredictorMultiGPUfrom sam3.model.text_encoder_ve import VETextEncoderfrom sam3.model.tokenizer_ve import SimpleTokenizerfrom sam3.model.vitdet import ViTfrom sam3.model.vl_combiner import SAM3VLBackbonefrom sam3.sam.transformer import RoPEAttention
# Setup TensorFloat-32 for Ampere GPUs if availabledef _setup_tf32() -> None: """Enable TensorFloat-32 for Ampere GPUs if available.""" if torch.cuda.is_available(): device_props = torch.cuda.get_device_properties(0) if device_props.major >= 8: torch.backends.cuda.matmul.allow_tf32 = True torch.backends.cudnn.allow_tf32 = True
_setup_tf32()
def _create_position_encoding(precompute_resolution=None): """Create position encoding for visual backbone.""" return PositionEmbeddingSine( num_pos_feats=256, normalize=True, scale=None, temperature=10000, precompute_resolution=precompute_resolution, )
def _create_vit_backbone(compile_mode=None): """Create ViT backbone for visual feature extraction.""" return ViT( img_size=1008, pretrain_img_size=336, patch_size=14, embed_dim=1024, depth=32, num_heads=16, mlp_ratio=4.625, norm_layer="LayerNorm", drop_path_rate=0.1, qkv_bias=True, use_abs_pos=True, tile_abs_pos=True, global_att_blocks=(7, 15, 23, 31), rel_pos_blocks=(), use_rope=True, use_interp_rope=True, window_size=24, pretrain_use_cls_token=True, retain_cls_token=False, ln_pre=True, ln_post=False, return_interm_layers=False, bias_patch_embed=False, compile_mode=compile_mode, )
def _create_vit_neck(position_encoding, vit_backbone, enable_inst_interactivity=False): """Create ViT neck for feature pyramid.""" return Sam3DualViTDetNeck( position_encoding=position_encoding, d_model=256, scale_factors=[4.0, 2.0, 1.0, 0.5], trunk=vit_backbone, add_sam2_neck=enable_inst_interactivity, )
def _create_vl_backbone(vit_neck, text_encoder): """Create visual-language backbone.""" return SAM3VLBackbone(visual=vit_neck, text=text_encoder, scalp=1)
def _create_transformer_encoder() -> TransformerEncoderFusion: """Create transformer encoder with its layer.""" encoder_layer = TransformerEncoderLayer( activation="relu", d_model=256, dim_feedforward=2048, dropout=0.1, pos_enc_at_attn=True, pos_enc_at_cross_attn_keys=False, pos_enc_at_cross_attn_queries=False, pre_norm=True, self_attention=MultiheadAttention( num_heads=8, dropout=0.1, embed_dim=256, batch_first=True, ), cross_attention=MultiheadAttention( num_heads=8, dropout=0.1, embed_dim=256, batch_first=True, ), )
encoder = TransformerEncoderFusion( layer=encoder_layer, num_layers=6, d_model=256, num_feature_levels=1, frozen=False, use_act_checkpoint=True, add_pooled_text_to_img_feat=False, pool_text_with_mask=True, ) return encoder
def _create_transformer_decoder() -> TransformerDecoder: """Create transformer decoder with its layer.""" decoder_layer = TransformerDecoderLayer( activation="relu", d_model=256, dim_feedforward=2048, dropout=0.1, cross_attention=MultiheadAttention( num_heads=8, dropout=0.1, embed_dim=256, ), n_heads=8, use_text_cross_attention=True, )
decoder = TransformerDecoder( layer=decoder_layer, num_layers=6, num_queries=200, return_intermediate=True, box_refine=True, num_o2m_queries=0, dac=True, boxRPB="log", d_model=256, frozen=False, interaction_layer=None, dac_use_selfatt_ln=True, resolution=1008, stride=14, use_act_checkpoint=True, presence_token=True, ) return decoder
def _create_dot_product_scoring(): """Create dot product scoring module.""" prompt_mlp = MLP( input_dim=256, hidden_dim=2048, output_dim=256, num_layers=2, dropout=0.1, residual=True, out_norm=nn.LayerNorm(256), ) return DotProductScoring(d_model=256, d_proj=256, prompt_mlp=prompt_mlp)
def _create_segmentation_head(compile_mode=None): """Create segmentation head with pixel decoder.""" pixel_decoder = PixelDecoder( num_upsampling_stages=3, interpolation_mode="nearest", hidden_dim=256, compile_mode=compile_mode, )
cross_attend_prompt = MultiheadAttention( num_heads=8, dropout=0, embed_dim=256, )
segmentation_head = UniversalSegmentationHead( hidden_dim=256, upsampling_stages=3, aux_masks=False, presence_head=False, dot_product_scorer=None, act_ckpt=True, cross_attend_prompt=cross_attend_prompt, pixel_decoder=pixel_decoder, ) return segmentation_head
def _create_geometry_encoder(): """Create geometry encoder with all its components.""" # Create position encoding for geometry encoder geo_pos_enc = _create_position_encoding() # Create CX block for fuser cx_block = CXBlock( dim=256, kernel_size=7, padding=3, layer_scale_init_value=1.0e-06, use_dwconv=True, ) # Create geometry encoder layer geo_layer = TransformerEncoderLayer( activation="relu", d_model=256, dim_feedforward=2048, dropout=0.1, pos_enc_at_attn=False, pre_norm=True, self_attention=MultiheadAttention( num_heads=8, dropout=0.1, embed_dim=256, batch_first=False, ), pos_enc_at_cross_attn_queries=False, pos_enc_at_cross_attn_keys=True, cross_attention=MultiheadAttention( num_heads=8, dropout=0.1, embed_dim=256, batch_first=False, ), )
# Create geometry encoder input_geometry_encoder = SequenceGeometryEncoder( pos_enc=geo_pos_enc, encode_boxes_as_points=False, points_direct_project=True, points_pool=True, points_pos_enc=True, boxes_direct_project=True, boxes_pool=True, boxes_pos_enc=True, d_model=256, num_layers=3, layer=geo_layer, use_act_ckpt=True, add_cls=True, add_post_encode_proj=True, ) return input_geometry_encoder
def _create_sam3_model( backbone, transformer, input_geometry_encoder, segmentation_head, dot_prod_scoring, inst_interactive_predictor, eval_mode,): """Create the SAM3 image model.""" common_params = { "backbone": backbone, "transformer": transformer, "input_geometry_encoder": input_geometry_encoder, "segmentation_head": segmentation_head, "num_feature_levels": 1, "o2m_mask_predict": True, "dot_prod_scoring": dot_prod_scoring, "use_instance_query": False, "multimask_output": True, "inst_interactive_predictor": inst_interactive_predictor, }
matcher = None if not eval_mode: from sam3.train.matcher import BinaryHungarianMatcherV2
matcher = BinaryHungarianMatcherV2( focal=True, cost_class=2.0, cost_bbox=5.0, cost_giou=2.0, alpha=0.25, gamma=2, stable=False, ) common_params["matcher"] = matcher model = Sam3Image(**common_params)
return model
def _create_tracker_maskmem_backbone(): """Create the SAM3 Tracker memory encoder.""" # Position encoding for mask memory backbone position_encoding = PositionEmbeddingSine( num_pos_feats=64, normalize=True, scale=None, temperature=10000, precompute_resolution=1008, )
# Mask processing components mask_downsampler = SimpleMaskDownSampler( kernel_size=3, stride=2, padding=1, interpol_size=[1152, 1152] )
cx_block_layer = CXBlock( dim=256, kernel_size=7, padding=3, layer_scale_init_value=1.0e-06, use_dwconv=True, )
fuser = SimpleFuser(layer=cx_block_layer, num_layers=2)
maskmem_backbone = SimpleMaskEncoder( out_dim=64, position_encoding=position_encoding, mask_downsampler=mask_downsampler, fuser=fuser, )
return maskmem_backbone
def _create_tracker_transformer(): """Create the SAM3 Tracker transformer components.""" # Self attention self_attention = RoPEAttention( embedding_dim=256, num_heads=1, downsample_rate=1, dropout=0.1, rope_theta=10000.0, feat_sizes=[72, 72], use_fa3=False, use_rope_real=False, )
# Cross attention cross_attention = RoPEAttention( embedding_dim=256, num_heads=1, downsample_rate=1, dropout=0.1, kv_in_dim=64, rope_theta=10000.0, feat_sizes=[72, 72], rope_k_repeat=True, use_fa3=False, use_rope_real=False, )
# Encoder layer encoder_layer = TransformerDecoderLayerv2( cross_attention_first=False, activation="relu", dim_feedforward=2048, dropout=0.1, pos_enc_at_attn=False, pre_norm=True, self_attention=self_attention, d_model=256, pos_enc_at_cross_attn_keys=True, pos_enc_at_cross_attn_queries=False, cross_attention=cross_attention, )
# Encoder encoder = TransformerEncoderCrossAttention( remove_cross_attention_layers=[], batch_first=True, d_model=256, frozen=False, pos_enc_at_input=True, layer=encoder_layer, num_layers=4, use_act_checkpoint=False, )
# Transformer wrapper transformer = TransformerWrapper( encoder=encoder, decoder=None, d_model=256, )
return transformer
def build_tracker( apply_temporal_disambiguation: bool, with_backbone: bool = False, compile_mode=None) -> Sam3TrackerPredictor: """ Build the SAM3 Tracker module for video tracking.
Returns: Sam3TrackerPredictor: Wrapped SAM3 Tracker module """
# Create model components maskmem_backbone = _create_tracker_maskmem_backbone() transformer = _create_tracker_transformer() backbone = None if with_backbone: vision_backbone = _create_vision_backbone(compile_mode=compile_mode) backbone = SAM3VLBackbone(scalp=1, visual=vision_backbone, text=None) # Create the Tracker module model = Sam3TrackerPredictor( image_size=1008, num_maskmem=7, backbone=backbone, backbone_stride=14, transformer=transformer, maskmem_backbone=maskmem_backbone, # SAM parameters multimask_output_in_sam=True, # Evaluation forward_backbone_per_frame_for_eval=True, trim_past_non_cond_mem_for_eval=False, # Multimask multimask_output_for_tracking=True, multimask_min_pt_num=0, multimask_max_pt_num=1, # Additional settings always_start_from_first_ann_frame=False, # Mask overlap non_overlap_masks_for_mem_enc=False, non_overlap_masks_for_output=False, max_cond_frames_in_attn=4, offload_output_to_cpu_for_eval=False, # SAM decoder settings sam_mask_decoder_extra_args={ "dynamic_multimask_via_stability": True, "dynamic_multimask_stability_delta": 0.05, "dynamic_multimask_stability_thresh": 0.98, }, clear_non_cond_mem_around_input=True, fill_hole_area=0, use_memory_selection=apply_temporal_disambiguation, )
return model
def _create_text_encoder(bpe_path: str) -> VETextEncoder: """Create SAM3 text encoder.""" tokenizer = SimpleTokenizer(bpe_path=bpe_path) return VETextEncoder( tokenizer=tokenizer, d_model=256, width=1024, heads=16, layers=24, )
def _create_vision_backbone( compile_mode=None, enable_inst_interactivity=True) -> Sam3DualViTDetNeck: """Create SAM3 visual backbone with ViT and neck.""" # Position encoding position_encoding = _create_position_encoding(precompute_resolution=1008) # ViT backbone vit_backbone: ViT = _create_vit_backbone(compile_mode=compile_mode) vit_neck: Sam3DualViTDetNeck = _create_vit_neck( position_encoding, vit_backbone, enable_inst_interactivity=enable_inst_interactivity, ) # Visual neck return vit_neck
def _create_sam3_transformer(has_presence_token: bool = True) -> TransformerWrapper: """Create SAM3 transformer encoder and decoder.""" encoder: TransformerEncoderFusion = _create_transformer_encoder() decoder: TransformerDecoder = _create_transformer_decoder()
return TransformerWrapper(encoder=encoder, decoder=decoder, d_model=256)
def _load_checkpoint(model, checkpoint_path): """Load model checkpoint from file.""" with g_pathmgr.open(checkpoint_path, "rb") as f: ckpt = torch.load(f, map_location="cpu", weights_only=True) if "model" in ckpt and isinstance(ckpt["model"], dict): ckpt = ckpt["model"] sam3_image_ckpt = { k.replace("detector.", ""): v for k, v in ckpt.items() if "detector" in k } if model.inst_interactive_predictor is not None: sam3_image_ckpt.update( { k.replace("tracker.", "inst_interactive_predictor.model."): v for k, v in ckpt.items() if "tracker" in k } ) missing_keys, _ = model.load_state_dict(sam3_image_ckpt, strict=False) if len(missing_keys) > 0: print( f"loaded {checkpoint_path} and found " f"missing and/or unexpected keys:\n{missing_keys=}" )
def _setup_device_and_mode(model, device, eval_mode): """Setup model device and evaluation mode.""" if device == "cuda": model = model.cuda() if eval_mode: model.eval() return model
def build_sam3_image_model( bpe_path=None, device="cuda" if torch.cuda.is_available() else "cpu", eval_mode=True, checkpoint_path=None, load_from_HF=True, enable_segmentation=True, enable_inst_interactivity=False, compile=False,): """ Build SAM3 image model
Args: bpe_path: Path to the BPE tokenizer vocabulary device: Device to load the model on ('cuda' or 'cpu') eval_mode: Whether to set the model to evaluation mode checkpoint_path: Optional path to model checkpoint enable_segmentation: Whether to enable segmentation head enable_inst_interactivity: Whether to enable instance interactivity (SAM 1 task) compile_mode: To enable compilation, set to "default"
Returns: A SAM3 image model """ if bpe_path is None: bpe_path = os.path.join( os.path.dirname(__file__), "..", "assets", "bpe_simple_vocab_16e6.txt.gz" ) # Create visual components compile_mode = "default" if compile else None vision_encoder = _create_vision_backbone( compile_mode=compile_mode, enable_inst_interactivity=enable_inst_interactivity )
# Create text components text_encoder = _create_text_encoder(bpe_path)
# Create visual-language backbone backbone = _create_vl_backbone(vision_encoder, text_encoder)
# Create transformer components transformer = _create_sam3_transformer()
# Create dot product scoring dot_prod_scoring = _create_dot_product_scoring()
# Create segmentation head if enabled segmentation_head = ( _create_segmentation_head(compile_mode=compile_mode) if enable_segmentation else None )
# Create geometry encoder input_geometry_encoder = _create_geometry_encoder() if enable_inst_interactivity: sam3_pvs_base = build_tracker(apply_temporal_disambiguation=False) inst_predictor = SAM3InteractiveImagePredictor(sam3_pvs_base) else: inst_predictor = None # Create the SAM3 model model = _create_sam3_model( backbone, transformer, input_geometry_encoder, segmentation_head, dot_prod_scoring, inst_predictor, eval_mode, ) if load_from_HF and checkpoint_path is None: checkpoint_path = download_ckpt_from_hf() # Load checkpoint if provided if checkpoint_path is not None: _load_checkpoint(model, checkpoint_path)
# Setup device and mode model = _setup_device_and_mode(model, device, eval_mode)
return model
def download_ckpt_from_hf(): SAM3_MODEL_ID = "facebook/sam3" SAM3_CKPT_NAME = "sam3.pt" SAM3_CFG_NAME = "config.json" _ = hf_hub_download(repo_id=SAM3_MODEL_ID, filename=SAM3_CFG_NAME) checkpoint_path = hf_hub_download(repo_id=SAM3_MODEL_ID, filename=SAM3_CKPT_NAME) return checkpoint_path
def build_sam3_video_model( checkpoint_path: Optional[str] = None, load_from_HF=True, bpe_path: Optional[str] = None, has_presence_token: bool = True, geo_encoder_use_img_cross_attn: bool = True, strict_state_dict_loading: bool = True, apply_temporal_disambiguation: bool = True, device="cuda" if torch.cuda.is_available() else "cpu", compile=False,) -> Sam3VideoInferenceWithInstanceInteractivity: """ Build SAM3 dense tracking model.
Args: checkpoint_path: Optional path to checkpoint file bpe_path: Path to the BPE tokenizer file
Returns: Sam3VideoInferenceWithInstanceInteractivity: The instantiated dense tracking model """ if bpe_path is None: bpe_path = os.path.join( os.path.dirname(__file__), "..", "assets", "bpe_simple_vocab_16e6.txt.gz" )
# Build Tracker module tracker = build_tracker(apply_temporal_disambiguation=apply_temporal_disambiguation)
# Build Detector components visual_neck = _create_vision_backbone() text_encoder = _create_text_encoder(bpe_path) backbone = SAM3VLBackbone(scalp=1, visual=visual_neck, text=text_encoder) transformer = _create_sam3_transformer(has_presence_token=has_presence_token) segmentation_head: UniversalSegmentationHead = _create_segmentation_head() input_geometry_encoder = _create_geometry_encoder()
# Create main dot product scoring main_dot_prod_mlp = MLP( input_dim=256, hidden_dim=2048, output_dim=256, num_layers=2, dropout=0.1, residual=True, out_norm=nn.LayerNorm(256), ) main_dot_prod_scoring = DotProductScoring( d_model=256, d_proj=256, prompt_mlp=main_dot_prod_mlp )
# Build Detector module detector = Sam3ImageOnVideoMultiGPU( num_feature_levels=1, backbone=backbone, transformer=transformer, segmentation_head=segmentation_head, semantic_segmentation_head=None, input_geometry_encoder=input_geometry_encoder, use_early_fusion=True, use_dot_prod_scoring=True, dot_prod_scoring=main_dot_prod_scoring, supervise_joint_box_scores=has_presence_token, )
# Build the main SAM3 video model if apply_temporal_disambiguation: model = Sam3VideoInferenceWithInstanceInteractivity( detector=detector, tracker=tracker, score_threshold_detection=0.5, assoc_iou_thresh=0.1, det_nms_thresh=0.1, new_det_thresh=0.7, hotstart_delay=15, hotstart_unmatch_thresh=8, hotstart_dup_thresh=8, suppress_unmatched_only_within_hotstart=True, min_trk_keep_alive=-1, max_trk_keep_alive=30, init_trk_keep_alive=30, suppress_overlapping_based_on_recent_occlusion_threshold=0.7, suppress_det_close_to_boundary=False, fill_hole_area=16, recondition_every_nth_frame=16, masklet_confirmation_enable=False, decrease_trk_keep_alive_for_empty_masklets=False, image_size=1008, image_mean=(0.5, 0.5, 0.5), image_std=(0.5, 0.5, 0.5), compile_model=compile, ) else: # a version without any heuristics for ablation studies model = Sam3VideoInferenceWithInstanceInteractivity( detector=detector, tracker=tracker, score_threshold_detection=0.5, assoc_iou_thresh=0.1, det_nms_thresh=0.1, new_det_thresh=0.7, hotstart_delay=0, hotstart_unmatch_thresh=0, hotstart_dup_thresh=0, suppress_unmatched_only_within_hotstart=True, min_trk_keep_alive=-1, max_trk_keep_alive=30, init_trk_keep_alive=30, suppress_overlapping_based_on_recent_occlusion_threshold=0.7, suppress_det_close_to_boundary=False, fill_hole_area=16, recondition_every_nth_frame=0, masklet_confirmation_enable=False, decrease_trk_keep_alive_for_empty_masklets=False, image_size=1008, image_mean=(0.5, 0.5, 0.5), image_std=(0.5, 0.5, 0.5), compile_model=compile, )
# Load checkpoint if provided if load_from_HF and checkpoint_path is None: checkpoint_path = download_ckpt_from_hf() if checkpoint_path is not None: with g_pathmgr.open(checkpoint_path, "rb") as f: ckpt = torch.load(f, map_location="cpu", weights_only=True) if "model" in ckpt and isinstance(ckpt["model"], dict): ckpt = ckpt["model"]
missing_keys, unexpected_keys = model.load_state_dict( ckpt, strict=strict_state_dict_loading ) if missing_keys: print(f"Missing keys: {missing_keys}") if unexpected_keys: print(f"Unexpected keys: {unexpected_keys}")
model.to(device=device) return model
def build_sam3_video_predictor(*model_args, gpus_to_use=None, **model_kwargs): return Sam3VideoPredictorMultiGPU( *model_args, gpus_to_use=gpus_to_use, **model_kwargs )12345678# Copyright (c) Meta Platforms, Inc. and affiliates. All Rights Reserved
import os
is_enabled = Falseif os.getenv("USE_PERFLIB", "1") == "1": # print("Enabled the use of perflib.\n", end="") is_enabled = True123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899# Copyright (c) Meta Platforms, Inc. and affiliates. All Rights Reserved
import torch
def recursive_fn_factory(fn): def recursive_fn(b): if isinstance(b, dict): return {k: recursive_fn(b[k]) for k in b} if isinstance(b, list): return [recursive_fn(t) for t in b] if isinstance(b, tuple): return tuple(recursive_fn(t) for t in b) if isinstance(b, torch.Tensor): return fn(b) # Yes, writing out an explicit white list of # trivial types is tedious, but so are bugs that # come from not applying fn, when expected to have # applied it. if b is None: return b trivial_types = [bool, int] for t in trivial_types: if isinstance(b, t): return b raise TypeError(f"Unexpected type {type(b)}")
return recursive_fn
recursive_contiguous = recursive_fn_factory(lambda x: x.contiguous())recursive_clone = recursive_fn_factory(torch.clone)
def compile_wrapper( fn, *, mode="max-autotune", fullgraph=True, dynamic=False, name=None): compiled_fn = torch.compile(fn, mode=mode, fullgraph=fullgraph, dynamic=dynamic)
def compiled_fn_wrapper(*args, **kwargs): with torch.autograd.profiler.record_function( f"compiled {fn}" if name is None else name ): cont_args = recursive_contiguous(args) cont_kwargs = recursive_contiguous(kwargs) result = compiled_fn(*cont_args, **cont_kwargs) cloned_result = recursive_clone(result) return cloned_result
return compiled_fn_wrapper
def shape_logging_wrapper(fn, keep_kwargs, enable_logging=False): """ Wraps a function and prints the shapes of all tensor inputs. Only prints when a new combination of shapes is seen. Thread-safe.
Args: fn: Function to wrap enable_logging: Boolean flag to enable/disable logging """ seen_shapes = set()
def get_shape(obj): if isinstance(obj, torch.Tensor): return obj.shape elif isinstance(obj, (list, tuple)): if len(obj) > 1: return tuple(get_shape(x) for x in obj) return get_shape(obj[0]) elif isinstance(obj, dict): return tuple(sorted((k, get_shape(v)) for k, v in obj.items())) else: return type(obj).__name__
def wrapper(*args, **kwargs): shapes = tuple(get_shape(arg) for arg in args) + tuple( (k, get_shape(v)) for k, v in kwargs.items() if isinstance(v, (torch.Tensor, list)) and (len(keep_kwargs) > 0 and k in keep_kwargs) ) if shapes not in seen_shapes: seen_shapes.add(shapes) if enable_logging: print(f"[ShapeLogger] New input shapes for {fn.__qualname__}: {shapes}") return fn(*args, **kwargs)
# Allow toggling the flag at runtime wrapper.enable_logging = enable_logging
def set_logging(enabled=False): nonlocal enable_logging enable_logging = enabled wrapper.enable_logging = enable_logging
wrapper.set_logging = set_logging return wrapper123456789101112131415161718192021222324252627# Copyright (c) Meta Platforms, Inc. and affiliates. All Rights Reserved
import torch
@torch.library.custom_op("flash::flash_attn_func", mutates_args=())def flash_attn_func_op( q: torch.Tensor, k: torch.Tensor, v: torch.Tensor) -> torch.Tensor: from flash_attn_interface import flash_attn_func as fa3
return fa3(q, k, v)
def flash_attn_func(q, k, v): dtype = torch.float8_e4m3fn return flash_attn_func_op(q.to(dtype), k.to(dtype), v.to(dtype)).to(q.dtype)
@flash_attn_func_op.register_fakedef _(q, k, v, **kwargs): # two outputs: # 1. output: (batch, seq_len, num_heads, head_dim) # 2. softmax_lse: (batch, num_heads, seq_len) with dtype=torch.float32 # output needs to be bfloat16, not float8! meta_q = torch.empty_like(q, dtype=torch.bfloat16).contiguous() return meta_q123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869# Copyright (c) Meta Platforms, Inc. and affiliates. All Rights Reserved
import torch
def masks_to_boxes(masks: torch.Tensor, obj_ids: list[int]): with torch.autograd.profiler.record_function("perflib: masks_to_boxes"): # Sanity check based on callsite for replacement assert masks.shape[0] == len(obj_ids) assert masks.dim() == 3
# Based on torchvision masks_to_boxes if masks.numel() == 0: return torch.zeros((0, 4), device=masks.device, dtype=torch.float)
N, H, W = masks.shape device = masks.device y = torch.arange(H, device=device).view(1, H) x = torch.arange(W, device=device).view(1, W)
masks_with_obj = masks != 0 # N, H, W masks_with_obj_x = masks_with_obj.amax( dim=1 ) # N, H (which columns have objects) masks_with_obj_y = masks_with_obj.amax(dim=2) # N, W (which rows have objects) masks_without_obj_x = ~masks_with_obj_x masks_without_obj_y = ~masks_with_obj_y
bounding_boxes_0 = torch.amin( (masks_without_obj_x * W) + (masks_with_obj_x * x), dim=1 ) bounding_boxes_1 = torch.amin( (masks_without_obj_y * H) + (masks_with_obj_y * y), dim=1 ) bounding_boxes_2 = torch.amax(masks_with_obj_x * x, dim=1) bounding_boxes_3 = torch.amax(masks_with_obj_y * y, dim=1)
bounding_boxes = torch.stack( [bounding_boxes_0, bounding_boxes_1, bounding_boxes_2, bounding_boxes_3], dim=1, ).to(dtype=torch.float) assert bounding_boxes.shape == (N, 4) assert bounding_boxes.device == masks.device assert bounding_boxes.dtype == torch.float return bounding_boxes
def mask_iou(pred_masks: torch.Tensor, gt_masks: torch.Tensor) -> torch.Tensor: """ Compute the IoU (Intersection over Union) between predicted masks and ground truth masks. Args: - pred_masks: (N, H, W) bool Tensor, containing binary predicted segmentation masks - gt_masks: (M, H, W) bool Tensor, containing binary ground truth segmentation masks Returns: - ious: (N, M) float Tensor, containing IoUs for each pair of predicted and ground truth masks """ assert pred_masks.dtype == gt_masks.dtype == torch.bool N, H, W = pred_masks.shape M, _, _ = gt_masks.shape
# Flatten masks: (N, 1, H*W) and (1, M, H*W) pred_flat = pred_masks.view(N, 1, H * W) gt_flat = gt_masks.view(1, M, H * W)
# Compute intersection and union: (N, M) intersection = (pred_flat & gt_flat).sum(dim=2).float() union = (pred_flat | gt_flat).sum(dim=2).float() ious = intersection / union.clamp(min=1) return ious # shape: (N, M)12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273747576777879808182838485868788899091# Copyright (c) Meta Platforms, Inc. and affiliates. All Rights Reserved
import logging
import numpy as npimport torch
from sam3.perflib.masks_ops import mask_iou
try: from torch_generic_nms import generic_nms as generic_nms_cuda
GENERIC_NMS_AVAILABLE = Trueexcept ImportError: logging.debug( "Falling back to triton or CPU mask NMS implementation -- please install `torch_generic_nms` via\n\t" 'pip uninstall -y torch_generic_nms; TORCH_CUDA_ARCH_LIST="8.0 9.0" pip install git+https://github.com/ronghanghu/torch_generic_nms' ) GENERIC_NMS_AVAILABLE = False
def nms_masks( pred_probs: torch.Tensor, pred_masks: torch.Tensor, prob_threshold: float, iou_threshold: float,) -> torch.Tensor: """ Args: - pred_probs: (num_det,) float Tensor, containing the score (probability) of each detection - pred_masks: (num_det, H_mask, W_mask) float Tensor, containing the binary segmentation mask of each detection - prob_threshold: float, score threshold to prefilter detections (NMS is performed on detections above threshold) - iou_threshold: float, mask IoU threshold for NMS
Returns: - keep: (num_det,) bool Tensor, indicating whether each detection is kept after score thresholding + NMS """ # prefilter the detections with prob_threshold ("valid" are those above prob_threshold) is_valid = pred_probs > prob_threshold # (num_det,) probs = pred_probs[is_valid] # (num_valid,) masks_binary = pred_masks[is_valid] > 0 # (num_valid, H_mask, W_mask) if probs.numel() == 0: return is_valid # no valid detection, return empty keep mask
ious = mask_iou(masks_binary, masks_binary) # (num_valid, num_valid) kept_inds = generic_nms(ious, probs, iou_threshold)
# valid_inds are the indices among `probs` of valid detections before NMS (or -1 for invalid) valid_inds = torch.where(is_valid, is_valid.cumsum(dim=0) - 1, -1) # (num_det,) keep = torch.isin(valid_inds, kept_inds) # (num_det,) return keep
def generic_nms( ious: torch.Tensor, scores: torch.Tensor, iou_threshold=0.5) -> torch.Tensor: """A generic version of `torchvision.ops.nms` that takes a pairwise IoU matrix."""
assert ious.dim() == 2 and ious.size(0) == ious.size(1) assert scores.dim() == 1 and scores.size(0) == ious.size(0)
if ious.is_cuda: if GENERIC_NMS_AVAILABLE: return generic_nms_cuda(ious, scores, iou_threshold, use_iou_matrix=True) else: from sam3.perflib.triton.nms import nms_triton
return nms_triton(ious, scores, iou_threshold)
return generic_nms_cpu(ious, scores, iou_threshold)
def generic_nms_cpu( ious: torch.Tensor, scores: torch.Tensor, iou_threshold=0.5) -> torch.Tensor: """ A generic version of `torchvision.ops.nms` that takes a pairwise IoU matrix. (CPU implementation based on https://github.com/jwyang/faster-rcnn.pytorch/blob/master/lib/model/nms/nms_cpu.py) """ ious_np = ious.float().detach().cpu().numpy() scores_np = scores.float().detach().cpu().numpy() order = scores_np.argsort()[::-1] kept_inds = [] while order.size > 0: i = order.item(0) kept_inds.append(i) inds = np.where(ious_np[i, order[1:]] <= iou_threshold)[0] order = order[inds + 1]
return torch.tensor(kept_inds, dtype=torch.int64, device=scores.device)1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859# Copyright (c) Meta Platforms, Inc. and affiliates. All Rights Reserved
import os
import numpy as npimport pytestimport torchfrom PIL import Imagefrom sam3.perflib.masks_ops import masks_to_boxes
class TestMasksToBoxes: def test_masks_box(self): def masks_box_check(masks, expected, atol=1e-4): out = masks_to_boxes(masks, [1 for _ in range(masks.shape[0])]) assert out.dtype == torch.float print("out: ", out) print("expected: ", expected) torch.testing.assert_close( out, expected, rtol=0.0, check_dtype=True, atol=atol )
# Check for int type boxes. def _get_image(): assets_directory = os.path.join( os.path.dirname(os.path.abspath(__file__)), "assets" ) mask_path = os.path.join(assets_directory, "masks.tiff") image = Image.open(mask_path) return image
def _create_masks(image, masks): for index in range(image.n_frames): image.seek(index) frame = np.array(image) masks[index] = torch.tensor(frame)
return masks
expected = torch.tensor( [ [127, 2, 165, 40], [2, 50, 44, 92], [56, 63, 98, 100], [139, 68, 175, 104], [160, 112, 198, 145], [49, 138, 99, 182], [108, 148, 152, 213], ], dtype=torch.float, )
image = _get_image() for dtype in [torch.float16, torch.float32, torch.float64]: masks = torch.zeros( (image.n_frames, image.height, image.width), dtype=dtype ) masks = _create_masks(image, masks) masks_box_check(masks, expected)123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468# Copyright (c) Meta Platforms, Inc. and affiliates. All Rights Reservedimport math
import torchimport tritonimport triton.language as tl
@triton.jitdef _any_combine(a, b): return a | b
@triton.jitdef tl_any(a, dim=0): return tl.reduce(a, dim, _any_combine)
# ==============================================================================# ## Phase 1: Initialization Kernel# ==============================================================================# Each foreground pixel (value > 0) gets a unique label equal to its# linear index. Background pixels (value == 0) get a sentinel label of -1.# Note that the indexing is done across batch boundaries for simplicity# (i.e., the first pixel of image 1 gets label H*W, etc.)
@triton.jitdef _init_labels_kernel( input_ptr, labels_ptr, numel: tl.constexpr, BLOCK_SIZE: tl.constexpr): pid = tl.program_id(0) offsets = pid * BLOCK_SIZE + tl.arange(0, BLOCK_SIZE) mask = offsets < numel input_values = tl.load(input_ptr + offsets, mask=mask, other=0)
indices = tl.where((input_values != 0), offsets, -1) tl.store(labels_ptr + offsets, indices, mask=mask)
# ==============================================================================# ## Phase 2: Local merging# ==============================================================================# Each pixel tries to merge with its 8-connected neighbors (up, down, left, right)# if they have the same value. This is done using a disjoint-set union operation.
@triton.jitdef find(labels_ptr, indices, mask): current_pids = indices
# 'is_done' tracks lanes that have finished their work. # A lane is initially "done" if it's not active (mask is False). is_done = ~mask
# Loop as long as there is at least one lane that is NOT done. while tl_any(~is_done): # The work_mask is for lanes that are still active and seeking their root. work_mask = ~is_done parents = tl.load(labels_ptr + current_pids, mask=work_mask, other=-1) # A lane is now done if its parent is itself (it's a root) # or if it hits a -1 sentinel (a safe exit condition). is_root = parents == current_pids is_sentinel = parents == -1 is_done |= is_root | is_sentinel
# For lanes that are not yet done, update their pid to their parent to continue traversal. current_pids = tl.where(is_done, current_pids, parents) # We could add the following line to do path compression, but experimentally it's slower # tl.atomic_min(labels_ptr + indices, current_pids, mask=mask) return current_pids
@triton.jitdef union(labels_ptr, a, b, process_mask): # This function implements a disjoint-set union # As an invariant, we use the fact that the roots have the lower id. That helps parallelization # However, that is not sufficient by itself. Suppose two threads want to do union(0,2) and union(1,2) at the same time # Then if we do a naive atomic_min, 0 and 1 will compete to be the new parent of 2 and min(0, 1) will win. # However, 1 still needs to be merged with the new {0, 2} component. # To ensure that merge is also done, we need to detect whether the merge was successful, and if not retry until it is
current_a = a current_b = b
final_root = a # A mask to track which lanes have successfully completed their union. done_mask = ~process_mask # tl.zeros_like(a) == 1 # Init with all False
while tl_any(~done_mask): # Define the mask for lanes that still need work in this iteration work_mask = process_mask & ~done_mask
# Find the roots for the current a and b values in the active lanes root_a = find(labels_ptr, current_a, work_mask) tl.debug_barrier() root_b = find(labels_ptr, current_b, work_mask)
# 7. Merge logic # If roots are already the same, the sets are already merged. Mark as done. are_equal = root_a == root_b final_root = tl.where(are_equal & work_mask & ~done_mask, root_a, final_root) done_mask |= are_equal & work_mask
# Define masks for the two merge cases (a < b or b < a) a_is_smaller = root_a < root_b
# Case 1: root_a < root_b. Attempt to set parent[root_b] = root_a merge_mask_a_smaller = work_mask & a_is_smaller & ~are_equal ptr_b = labels_ptr + root_b old_val_b = tl.atomic_min(ptr_b, root_a, mask=merge_mask_a_smaller)
# A lane is done if its atomic op was successful (old value was what we expected) success_b = old_val_b == root_b final_root = tl.where(success_b & work_mask & ~done_mask, root_a, final_root) done_mask |= success_b & merge_mask_a_smaller
# *** Crucial Retry Logic *** # If the update failed (old_val_b != root_b), another thread interfered. # We update `current_b` to this new root (`old_val_b`) and will retry in the next loop iteration. current_b = tl.where(success_b | ~merge_mask_a_smaller, current_b, old_val_b)
# Case 2: root_b < root_a. Attempt to set parent[root_a] = root_b merge_mask_b_smaller = work_mask & ~a_is_smaller & ~are_equal ptr_a = labels_ptr + root_a old_val_a = tl.atomic_min(ptr_a, root_b, mask=merge_mask_b_smaller)
success_a = old_val_a == root_a final_root = tl.where(success_a & work_mask & ~done_mask, root_b, final_root) done_mask |= success_a & merge_mask_b_smaller
# *** Crucial Retry Logic *** # Similarly, update `current_a` if the atomic operation failed. current_a = tl.where(success_a | ~merge_mask_b_smaller, current_a, old_val_a)
return final_root
@triton.jitdef _merge_helper( input_ptr, labels_ptr, base_offset, offsets_h, offsets_w, mask_2d, valid_current, current_values, current_labels, H, W, dx: tl.constexpr, dy: tl.constexpr,): # Helper functions to compute merge with a specific neighbor offset (dx, dy)
neighbor_h = offsets_h + dy neighbor_w = offsets_w + dx # Proper bounds checking: all four bounds must be satisfied mask_n = ( mask_2d & (neighbor_h[:, None] >= 0) & (neighbor_h[:, None] < H) & (neighbor_w[None, :] >= 0) & (neighbor_w[None, :] < W) )
offsets_neighbor = neighbor_h[:, None] * W + neighbor_w[None, :] neighbor_values = tl.load( input_ptr + base_offset + offsets_neighbor, mask=mask_n, other=-1 )
mask_n = tl.ravel(mask_n) neighbor_labels = tl.load( labels_ptr + tl.ravel(base_offset + offsets_neighbor), mask=mask_n, other=-1 )
to_merge = ( mask_n & (neighbor_labels != -1) & tl.ravel(current_values == neighbor_values) ) valid_write = valid_current & to_merge
# returns new parents for the pixels that were merged (otherwise keeps current labels) return tl.where( valid_write, union(labels_ptr, current_labels, neighbor_labels, valid_write), current_labels, )
@triton.autotune( configs=[ triton.Config( {"BLOCK_SIZE_H": 4, "BLOCK_SIZE_W": 16}, num_stages=1, num_warps=2 ), triton.Config( {"BLOCK_SIZE_H": 4, "BLOCK_SIZE_W": 32}, num_stages=2, num_warps=4 ), ], key=["H", "W"], restore_value=["labels_ptr"],)@triton.jitdef _local_prop_kernel( labels_ptr, input_ptr, H: tl.constexpr, W: tl.constexpr, BLOCK_SIZE_H: tl.constexpr, BLOCK_SIZE_W: tl.constexpr,): # This is the meat of the Phase 2 to do local merging # It will be launched with a 2D grid: # - dim 0: batch index # - dim 1: block index over HxW image (2D tiling) pid_b = tl.program_id(0) pid_hw = tl.program_id(1)
# Calculate offsets for the core block offsets_h = (pid_hw // tl.cdiv(W, BLOCK_SIZE_W)) * BLOCK_SIZE_H + tl.arange( 0, BLOCK_SIZE_H ) offsets_w = (pid_hw % tl.cdiv(W, BLOCK_SIZE_W)) * BLOCK_SIZE_W + tl.arange( 0, BLOCK_SIZE_W )
base_offset = pid_b * H * W offsets_2d = offsets_h[:, None] * W + offsets_w[None, :] mask_2d = (offsets_h[:, None] < H) & (offsets_w[None, :] < W) mask_1d = tl.ravel(mask_2d)
# Load the current labels for the block - these are parent pointers current_labels = tl.load( labels_ptr + tl.ravel(base_offset + offsets_2d), mask=mask_1d, other=-1 ) current_values = tl.load( input_ptr + base_offset + offsets_2d, mask=mask_2d, other=-1 ) valid_current = mask_1d & (current_labels != -1)
# Horizontal merge current_labels = _merge_helper( input_ptr, labels_ptr, base_offset, offsets_h, offsets_w, mask_2d, valid_current, current_values, current_labels, H, W, -1, 0, ) # Vertical merge current_labels = _merge_helper( input_ptr, labels_ptr, base_offset, offsets_h, offsets_w, mask_2d, valid_current, current_values, current_labels, H, W, 0, -1, ) # Diagonal merges current_labels = _merge_helper( input_ptr, labels_ptr, base_offset, offsets_h, offsets_w, mask_2d, valid_current, current_values, current_labels, H, W, -1, -1, ) current_labels = _merge_helper( input_ptr, labels_ptr, base_offset, offsets_h, offsets_w, mask_2d, valid_current, current_values, current_labels, H, W, -1, 1, )
# This actually does some path compression, in a lightweight but beneficial way tl.atomic_min( labels_ptr + tl.ravel(base_offset + offsets_2d), current_labels, mask=mask_1d )
# ==============================================================================# ## Phase 3: Pointer Jumping Kernel# ==============================================================================# This kernel performs pointer jumping to ensure that all pixels point directly to their root labels.# This is done in a loop until convergence.
@triton.jitdef _pointer_jump_kernel( labels_in_ptr, labels_out_ptr, numel: tl.constexpr, BLOCK_SIZE: tl.constexpr): """ Pointer jumping kernel with double buffering to avoid race conditions. Reads from labels_in_ptr and writes to labels_out_ptr. """ # This kernel is launched with a 1D grid, and does not care about batching explicitly. # By construction, the labels are global indices across the batch, and we never perform # cross-batch merges, so this is safe.
pid = tl.program_id(0) offsets = pid * BLOCK_SIZE + tl.arange(0, BLOCK_SIZE) mask = offsets < numel
# Load current labels from input buffer current_labels = tl.load(labels_in_ptr + offsets, mask=mask, other=-1) valid_mask = mask & (current_labels != -1)
# A mask to track which lanes have successfully completed their union. done_mask = ~valid_mask while tl_any(~(done_mask | ~valid_mask)): parent_labels = tl.load( labels_in_ptr + current_labels, mask=valid_mask, other=-1 )
are_equal = current_labels == parent_labels done_mask |= are_equal & valid_mask
current_labels = tl.where( ~done_mask, tl.minimum(current_labels, parent_labels), current_labels )
# Write to output buffer (safe because we're not reading from it) tl.store(labels_out_ptr + offsets, current_labels, mask=mask)
# ==============================================================================# ## Phase 4: Kernels for Computing Component Sizes# ==============================================================================
# Step 4.1: Count occurrences of each root label using atomic adds.@triton.jitdef _count_labels_kernel(labels_ptr, sizes_ptr, numel, BLOCK_SIZE: tl.constexpr): pid = tl.program_id(0) offsets = pid * BLOCK_SIZE + tl.arange(0, BLOCK_SIZE) mask = offsets < numel
# Load the final, converged labels labels = tl.load(labels_ptr + offsets, mask=mask, other=-1) valid_mask = mask & (labels != -1)
# Atomically increment the counter for each label. This builds a histogram. tl.atomic_add(sizes_ptr + labels, 1, mask=valid_mask)
# Step 4.2: Broadcast the computed sizes back to the output tensor.@triton.jitdef _broadcast_sizes_kernel( labels_ptr, sizes_ptr, out_ptr, numel, BLOCK_SIZE: tl.constexpr): pid = tl.program_id(0) offsets = pid * BLOCK_SIZE + tl.arange(0, BLOCK_SIZE) mask = offsets < numel
# Load the final labels labels = tl.load(labels_ptr + offsets, mask=mask, other=-1) valid_mask = mask & (labels != -1)
# Look up the size for each label from the histogram component_sizes = tl.load(sizes_ptr + labels, mask=valid_mask, other=0)
# Write the size to the final output tensor. Background pixels get size 0. tl.store(out_ptr + offsets, component_sizes, mask=mask)
def connected_components_triton(input_tensor: torch.Tensor): """ Computes connected components labeling on a batch of 2D integer tensors using Triton.
Args: input_tensor (torch.Tensor): A BxHxW integer tensor or Bx1xHxW. Non-zero values are considered foreground. Bool tensor also accepted
Returns: Tuple[torch.Tensor, int]: A tuple containing: - A BxHxW output tensor with dense labels. Background is 0. - A BxHxW tensor with the size of the connected component for each pixel. """ assert ( input_tensor.is_cuda and input_tensor.is_contiguous() ), "Input tensor must be a contiguous CUDA tensor." out_shape = input_tensor.shape if input_tensor.dim() == 4 and input_tensor.shape[1] == 1: input_tensor = input_tensor.squeeze(1) else: assert ( input_tensor.dim() == 3 ), "Input tensor must be (B, H, W) or (B, 1, H, W)."
B, H, W = input_tensor.shape numel = B * H * W device = input_tensor.device
# --- Allocate Tensors --- labels = torch.empty_like(input_tensor, dtype=torch.int32) output = torch.empty_like(input_tensor, dtype=torch.int32)
# --- Phase 1 --- BLOCK_SIZE = 256 grid_init = (triton.cdiv(numel, BLOCK_SIZE),) _init_labels_kernel[grid_init]( input_tensor, labels, numel, BLOCK_SIZE=BLOCK_SIZE, )
# --- Phase 2 --- grid_local_prop = lambda meta: ( B, triton.cdiv(H, meta["BLOCK_SIZE_H"]) * triton.cdiv(W, meta["BLOCK_SIZE_W"]), ) _local_prop_kernel[grid_local_prop](labels, input_tensor, H, W)
# --- Phase 3 --- BLOCK_SIZE = 256 grid_jump = lambda meta: (triton.cdiv(numel, meta["BLOCK_SIZE"]),) _pointer_jump_kernel[grid_jump](labels, output, numel, BLOCK_SIZE=BLOCK_SIZE)
# --- Phase 4 --- # Allocate tensor to store the final output sizes component_sizes_out = torch.empty_like(input_tensor, dtype=torch.int32)
# Allocate a temporary 1D tensor to act as the histogram # Size is numel because labels can be up to numel-1 sizes_histogram = torch.zeros(numel, dtype=torch.int32, device=device)
# 4.1: Count the occurrences of each label grid_count = (triton.cdiv(numel, BLOCK_SIZE),) _count_labels_kernel[grid_count]( output, sizes_histogram, numel, BLOCK_SIZE=BLOCK_SIZE )
# 2.2: Broadcast the counts to the final output tensor grid_broadcast = (triton.cdiv(numel, BLOCK_SIZE),) _broadcast_sizes_kernel[grid_broadcast]( output, sizes_histogram, component_sizes_out, numel, BLOCK_SIZE=BLOCK_SIZE ) return output.view(out_shape) + 1, component_sizes_out.view(out_shape)123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243# Copyright (c) Meta Platforms, Inc. and affiliates. All Rights Reserved
from typing import Any, Optional, Tuple, Type
import numpy as npimport torchfrom torch import nn
from .common import LayerNorm2d
class PromptEncoder(nn.Module): def __init__( self, embed_dim: int, image_embedding_size: Tuple[int, int], input_image_size: Tuple[int, int], mask_in_chans: int, activation: Type[nn.Module] = nn.GELU, ) -> None: """ Encodes prompts for input to SAM's mask decoder.
Arguments: embed_dim (int): The prompts' embedding dimension image_embedding_size (tuple(int, int)): The spatial size of the image embedding, as (H, W). input_image_size (int): The padded size of the image as input to the image encoder, as (H, W). mask_in_chans (int): The number of hidden channels used for encoding input masks. activation (nn.Module): The activation to use when encoding input masks. """ super().__init__() self.embed_dim = embed_dim self.input_image_size = input_image_size self.image_embedding_size = image_embedding_size self.pe_layer = PositionEmbeddingRandom(embed_dim // 2)
self.num_point_embeddings: int = 4 # pos/neg point + 2 box corners point_embeddings = [ nn.Embedding(1, embed_dim) for i in range(self.num_point_embeddings) ] self.point_embeddings = nn.ModuleList(point_embeddings) self.not_a_point_embed = nn.Embedding(1, embed_dim)
self.mask_input_size = ( 4 * image_embedding_size[0], 4 * image_embedding_size[1], ) self.mask_downscaling = nn.Sequential( nn.Conv2d(1, mask_in_chans // 4, kernel_size=2, stride=2), LayerNorm2d(mask_in_chans // 4), activation(), nn.Conv2d(mask_in_chans // 4, mask_in_chans, kernel_size=2, stride=2), LayerNorm2d(mask_in_chans), activation(), nn.Conv2d(mask_in_chans, embed_dim, kernel_size=1), ) self.no_mask_embed = nn.Embedding(1, embed_dim)
def get_dense_pe(self) -> torch.Tensor: """ Returns the positional encoding used to encode point prompts, applied to a dense set of points the shape of the image encoding.
Returns: torch.Tensor: Positional encoding with shape 1x(embed_dim)x(embedding_h)x(embedding_w) """ return self.pe_layer(self.image_embedding_size).unsqueeze(0)
def _embed_points( self, points: torch.Tensor, labels: torch.Tensor, pad: bool, ) -> torch.Tensor: """Embeds point prompts.""" points = points + 0.5 # Shift to center of pixel if pad: padding_point = torch.zeros((points.shape[0], 1, 2), device=points.device) padding_label = -torch.ones((labels.shape[0], 1), device=labels.device) points = torch.cat([points, padding_point], dim=1) labels = torch.cat([labels, padding_label], dim=1) point_embedding = self.pe_layer.forward_with_coords( points, self.input_image_size )
point_embedding = torch.where( (labels == -1).unsqueeze(-1), torch.zeros_like(point_embedding) + self.not_a_point_embed.weight, point_embedding, ) point_embedding = torch.where( (labels == 0).unsqueeze(-1), point_embedding + self.point_embeddings[0].weight, point_embedding, ) point_embedding = torch.where( (labels == 1).unsqueeze(-1), point_embedding + self.point_embeddings[1].weight, point_embedding, ) point_embedding = torch.where( (labels == 2).unsqueeze(-1), point_embedding + self.point_embeddings[2].weight, point_embedding, ) point_embedding = torch.where( (labels == 3).unsqueeze(-1), point_embedding + self.point_embeddings[3].weight, point_embedding, ) return point_embedding
def _embed_boxes(self, boxes: torch.Tensor) -> torch.Tensor: """Embeds box prompts.""" boxes = boxes + 0.5 # Shift to center of pixel coords = boxes.reshape(-1, 2, 2) corner_embedding = self.pe_layer.forward_with_coords( coords, self.input_image_size ) corner_embedding[:, 0, :] += self.point_embeddings[2].weight corner_embedding[:, 1, :] += self.point_embeddings[3].weight return corner_embedding
def _embed_masks(self, masks: torch.Tensor) -> torch.Tensor: """Embeds mask inputs.""" mask_embedding = self.mask_downscaling(masks) return mask_embedding
def _get_batch_size( self, points: Optional[Tuple[torch.Tensor, torch.Tensor]], boxes: Optional[torch.Tensor], masks: Optional[torch.Tensor], ) -> int: """ Gets the batch size of the output given the batch size of the input prompts. """ if points is not None: return points[0].shape[0] elif boxes is not None: return boxes.shape[0] elif masks is not None: return masks.shape[0] else: return 1
def _get_device(self) -> torch.device: return self.point_embeddings[0].weight.device
def forward( self, points: Optional[Tuple[torch.Tensor, torch.Tensor]], boxes: Optional[torch.Tensor], masks: Optional[torch.Tensor], ) -> Tuple[torch.Tensor, torch.Tensor]: """ Embeds different types of prompts, returning both sparse and dense embeddings.
Arguments: points (tuple(torch.Tensor, torch.Tensor) or none): point coordinates and labels to embed. boxes (torch.Tensor or none): boxes to embed masks (torch.Tensor or none): masks to embed
Returns: torch.Tensor: sparse embeddings for the points and boxes, with shape BxNx(embed_dim), where N is determined by the number of input points and boxes. torch.Tensor: dense embeddings for the masks, in the shape Bx(embed_dim)x(embed_H)x(embed_W) """ bs = self._get_batch_size(points, boxes, masks) sparse_embeddings = torch.empty( (bs, 0, self.embed_dim), device=self._get_device() ) if points is not None: coords, labels = points point_embeddings = self._embed_points(coords, labels, pad=(boxes is None)) sparse_embeddings = torch.cat([sparse_embeddings, point_embeddings], dim=1) if boxes is not None: box_embeddings = self._embed_boxes(boxes) sparse_embeddings = torch.cat([sparse_embeddings, box_embeddings], dim=1)
if masks is not None: dense_embeddings = self._embed_masks(masks) else: dense_embeddings = self.no_mask_embed.weight.reshape(1, -1, 1, 1).expand( bs, -1, self.image_embedding_size[0], self.image_embedding_size[1] )
return sparse_embeddings, dense_embeddings
class PositionEmbeddingRandom(nn.Module): """ Positional encoding using random spatial frequencies. """
def __init__(self, num_pos_feats: int = 64, scale: Optional[float] = None) -> None: super().__init__() if scale is None or scale <= 0.0: scale = 1.0 self.register_buffer( "positional_encoding_gaussian_matrix", scale * torch.randn((2, num_pos_feats)), )
def _pe_encoding(self, coords: torch.Tensor) -> torch.Tensor: """Positionally encode points that are normalized to [0,1].""" # assuming coords are in [0, 1]^2 square and have d_1 x ... x d_n x 2 shape coords = 2 * coords - 1 coords = coords @ self.positional_encoding_gaussian_matrix coords = 2 * np.pi * coords # outputs d_1 x ... x d_n x C shape return torch.cat([torch.sin(coords), torch.cos(coords)], dim=-1)
def forward(self, size: Tuple[int, int]) -> torch.Tensor: """Generate positional encoding for a grid of the specified size.""" h, w = size device: Any = self.positional_encoding_gaussian_matrix.device grid = torch.ones((h, w), device=device, dtype=torch.float32) y_embed = grid.cumsum(dim=0) - 0.5 x_embed = grid.cumsum(dim=1) - 0.5 y_embed = y_embed / h x_embed = x_embed / w
pe = self._pe_encoding(torch.stack([x_embed, y_embed], dim=-1)) return pe.permute(2, 0, 1) # C x H x W
def forward_with_coords( self, coords_input: torch.Tensor, image_size: Tuple[int, int] ) -> torch.Tensor: """Positionally encode points that are not normalized to [0,1].""" coords = coords_input.clone() coords[:, :, 0] = coords[:, :, 0] / image_size[1] coords[:, :, 1] = coords[:, :, 1] / image_size[0] return self._pe_encoding(coords.to(torch.float)) # B x N x C123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279# @package _global_defaults: - _self_
# This config is the base configuration for all evaluations. Amongst other things, it defines:# - the model# - the image transforms# - the post processors# - cluster configuration (only relevant for slurm-based evals, ignored otherwise)## Most of the parameters should be kept as-is. The main modifications you may want to make are:# - the cluster configuration, to adjust partitions/qos to your system# - the flag gather_pred_via_filesys if you ram is tight# - num_val_workers if your number of cores is small (should be roughly number of cores / number of gpus)# - the paths below
# ============================================================================# Paths Configuration (Chage this to your own paths)# ============================================================================paths: # If you leave the checkpoint path to null, the model will be downloaded from hugging-face. Otherwise provide a path checkpoint_path: null # the experiments will be subfolders of this base_experiment_log_dir: <YOUR EXPERIMENET LOG_DIR>
# base path to the annotation folder for gold (refer to the readmes on how to download) base_annotation_path: <YOUR_GOLD_GT_DIR>
# base path to the annotation folder for silver (refer to the readmes on how to download) base_annotation_path_silver: <YOUR_SILVER_GT_DIR>
# path to the metaclip images, used for SA-Co gold (refer to the readme for instructions). Can be null if you don't intend on evaluating on this dataset. metaclip_img_path: <YOUR_METACLIP_IMG_DIR>
# path to the sa1b images, used for SA-Co gold (refer to the readme for instructions). Can be null if you don't intend on evaluating on this dataset. sa1b_img_path: <YOUR_SA1B_IMG_DIR>
# path to the SA-Co/silver images silver_img_path: <YOUR_SILVER_IMG_DIR>
bpe_path: <BPE_PATH> # This should be under assets/bpe_simple_vocab_16e6.txt.gz
# ============================================================================# Different helper parameters and functions# ============================================================================scratch:
use_presence_eval: True
base_val_transform: - _target_: sam3.train.transforms.basic_for_api.ComposeAPI transforms: ######## transforms for validation (begin) ######## - _target_: sam3.train.transforms.basic_for_api.RandomResizeAPI sizes: ${scratch.resolution} # originally `resolution: 1024` max_size: _target_: sam3.train.transforms.basic.get_random_resize_max_size size: ${scratch.resolution} # originally `resolution: 1024` square: true consistent_transform: False ######## transforms for validation (end) ######## - _target_: sam3.train.transforms.basic_for_api.ToTensorAPI - _target_: sam3.train.transforms.basic_for_api.NormalizeAPI mean: ${scratch.val_norm_mean} std: ${scratch.val_norm_std}
loss: null
# Model parameters d_model: 256 input_box_embedding_dim: ${add:${scratch.d_model},2}
# Box processing original_box_postprocessor: _target_: sam3.eval.postprocessors.PostProcessImage max_dets_per_img: -1 # infinite detections use_original_ids: true use_original_sizes_box: true use_presence: ${scratch.use_presence_eval}
box_postprocessor: _target_: sam3.eval.postprocessors.PostProcessImage max_dets_per_img: -1 #infinite detections use_original_ids: false use_original_sizes_box: false use_presence: ${scratch.use_presence_eval}
box_postprocessor_thresholded: _target_: sam3.eval.postprocessors.PostProcessImage max_dets_per_img: -1 #infinite detections use_original_ids: false use_original_sizes_box: false detection_threshold: 0.3 use_presence: ${scratch.use_presence_eval}
mask_postprocessor_thresholded: _target_: sam3.eval.postprocessors.PostProcessImage max_dets_per_img: -1 #infinite detections iou_type: "segm" use_original_ids: false use_original_sizes_box: false use_original_sizes_mask: true convert_mask_to_rle: True detection_threshold: 0.3 use_presence: ${scratch.use_presence_eval}
# Image processing parameters resolution: 1008 max_ann_per_img: 200
# Normalization parameters train_norm_mean: [0.5, 0.5, 0.5] train_norm_std: [0.5, 0.5, 0.5] val_norm_mean: [0.5, 0.5, 0.5] val_norm_std: [0.5, 0.5, 0.5]
# Training parameters train_batch_size: 1 val_batch_size: 1 num_train_workers: 0 num_val_workers: 10 # change this depending on the number of cpu cores available max_data_epochs: 20 target_epoch_size: 1500 hybrid_repeats: 1 context_length: 2
# All reduce - this controls how the predictions are sent back to node 0. # If you have a lot of ram, CPU gather is faster. Otherwise, we provide a fallback through filesystem (eg NFS) # Switch to true if you get cpu ooms during gather. gather_pred_via_filesys: false
# Learning rate and scheduler parameters (unused for eval) lr_scale: 0.1 lr_transformer: ${times:8e-4,${scratch.lr_scale}} lr_vision_backbone: ${times:2.5e-4,${scratch.lr_scale}} lr_language_backbone: ${times:5e-5,${scratch.lr_scale}} lrd_vision_backbone: 0.9 # (lower for in-domain adn higher for ood) wd: 0.1 scheduler_timescale: 20 scheduler_warmup: 20 scheduler_cooldown: 20
# ============================================================================# Trainer Configuration# ============================================================================
trainer: _target_: sam3.train.trainer.Trainer skip_saving_ckpts: true empty_gpu_mem_cache_after_eval: True skip_first_val: True max_epochs: ${scratch.max_data_epochs} accelerator: cuda seed_value: 123 val_epoch_freq: 10 mode: val
distributed: backend: nccl find_unused_parameters: True gradient_as_bucket_view: True
loss: all: _target_: sam3.train.loss.sam3_loss.DummyLoss default: _target_: sam3.train.loss.sam3_loss.DummyLoss
data: train: null val: null
model: _target_: sam3.model_builder.build_sam3_image_model bpe_path: ${paths.bpe_path} device: cpus eval_mode: true enable_segmentation: true # Warning: Enable this if using segmentation. checkpoint_path: ${paths.checkpoint_path}
meters: val: null
optim: amp: enabled: True amp_dtype: bfloat16
optimizer: _target_: torch.optim.AdamW
gradient_clip: _target_: sam3.train.optim.optimizer.GradientClipper max_norm: 0.1 norm_type: 2
param_group_modifiers: - _target_: sam3.train.optim.optimizer.layer_decay_param_modifier _partial_: True layer_decay_value: ${scratch.lrd_vision_backbone} apply_to: 'backbone.vision_backbone.trunk' overrides: - pattern: '*pos_embed*' value: 1.0
options: lr: - scheduler: # transformer and class_embed _target_: sam3.train.optim.schedulers.InverseSquareRootParamScheduler base_lr: ${scratch.lr_transformer} timescale: ${scratch.scheduler_timescale} warmup_steps: ${scratch.scheduler_warmup} cooldown_steps: ${scratch.scheduler_cooldown} - scheduler: _target_: sam3.train.optim.schedulers.InverseSquareRootParamScheduler base_lr: ${scratch.lr_vision_backbone} timescale: ${scratch.scheduler_timescale} warmup_steps: ${scratch.scheduler_warmup} cooldown_steps: ${scratch.scheduler_cooldown} param_names: - 'backbone.vision_backbone.*' - scheduler: _target_: sam3.train.optim.schedulers.InverseSquareRootParamScheduler base_lr: ${scratch.lr_language_backbone} timescale: ${scratch.scheduler_timescale} warmup_steps: ${scratch.scheduler_warmup} cooldown_steps: ${scratch.scheduler_cooldown} param_names: - 'backbone.language_backbone.*'
weight_decay: - scheduler: _target_: fvcore.common.param_scheduler.ConstantParamScheduler value: ${scratch.wd} - scheduler: _target_: fvcore.common.param_scheduler.ConstantParamScheduler value: 0.0 param_names: - '*bias*' module_cls_names: ['torch.nn.LayerNorm']
checkpoint: save_dir: ${launcher.experiment_log_dir}/checkpoints save_freq: 0 # 0 only last checkpoint is saved.
logging: tensorboard_writer: _target_: sam3.train.utils.logger.make_tensorboard_logger log_dir: ${launcher.experiment_log_dir}/tensorboard flush_secs: 120 should_log: True wandb_writer: null log_dir: ${launcher.experiment_log_dir}/logs/ log_freq: 10
# ============================================================================# Launcher and Submitit Configuration# ============================================================================
launcher: num_nodes: 4 gpus_per_node: 8 experiment_log_dir: ${paths.experiment_log_dir} multiprocessing_context: forkserver
submitit: account: null # Add your SLURM account if use_cluster == 1 partition: null qos: null # Add your QoS if use_cluster == 1 timeout_hour: 72 use_cluster: True cpus_per_task: 10 port_range: [10000, 65000] constraint: null123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566# @package _global_defaults: - /configs/eval_base.yaml - _self_
# ============================================================================# Paths Configuration (you can override here, but it shouldn't require further changes if eval_base.yaml is correct# ============================================================================paths: experiment_log_dir: ${paths.base_experiment_log_dir}/gold_attributes/ coco_gt: ${paths.base_annotation_path}/gold_attributes_merged_a_release_test.json coco_gts: - ${paths.base_annotation_path}/gold_attributes_merged_a_release_test.json - ${paths.base_annotation_path}/gold_attributes_merged_b_release_test.json - ${paths.base_annotation_path}/gold_attributes_merged_c_release_test.json
# ============================================================================# Trainer Configuration# ============================================================================
trainer: data: val: _target_: sam3.train.data.torch_dataset.TorchDataset dataset: _target_: sam3.train.data.sam3_image_dataset.Sam3ImageDataset coco_json_loader: _target_: sam3.train.data.coco_json_loaders.SAM3_EVAL_API_FROM_JSON_NP _partial_: true img_folder: ${paths.metaclip_img_path} ann_file: ${paths.coco_gt} transforms: ${scratch.base_val_transform} max_ann_per_img: 100000 multiplier: 1 training: false
shuffle: False batch_size: ${scratch.val_batch_size} num_workers: ${scratch.num_val_workers} pin_memory: False drop_last: False collate_fn: _target_: sam3.train.data.collator.collate_fn_api _partial_: true repeats: ${scratch.hybrid_repeats} dict_key: gold_attributes
meters: val: gold_attributes: # this key matches the "dict_key" in the dataloader's collate function cgf1: _target_: sam3.eval.coco_writer.PredictionDumper iou_type: "segm" dump_dir: ${launcher.experiment_log_dir}/dumps/gold_attributes merge_predictions: True postprocessor: ${scratch.mask_postprocessor_thresholded} gather_pred_via_filesys: ${scratch.gather_pred_via_filesys} maxdets: 1000000 # no limit pred_file_evaluators: - _target_: sam3.eval.cgf1_eval.CGF1Evaluator gt_path: ${paths.coco_gts} iou_type: "bbox" - _target_: sam3.eval.cgf1_eval.CGF1Evaluator gt_path: ${paths.coco_gts} iou_type: "segm"123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566# @package _global_defaults: - /configs/eval_base.yaml - _self_
# ============================================================================# Paths Configuration (you can override here, but it shouldn't require further changes if eval_base.yaml is correct# ============================================================================paths: experiment_log_dir: ${paths.base_experiment_log_dir}/gold_metaclip_nps/ coco_gt: ${paths.base_annotation_path}/gold_metaclip_merged_a_release_test.json coco_gts: - ${paths.base_annotation_path}/gold_metaclip_merged_a_release_test.json - ${paths.base_annotation_path}/gold_metaclip_merged_b_release_test.json - ${paths.base_annotation_path}/gold_metaclip_merged_c_release_test.json
# ============================================================================# Trainer Configuration# ============================================================================
trainer: data: val: _target_: sam3.train.data.torch_dataset.TorchDataset dataset: _target_: sam3.train.data.sam3_image_dataset.Sam3ImageDataset coco_json_loader: _target_: sam3.train.data.coco_json_loaders.SAM3_EVAL_API_FROM_JSON_NP _partial_: true img_folder: ${paths.metaclip_img_path} ann_file: ${paths.coco_gt} transforms: ${scratch.base_val_transform} max_ann_per_img: 100000 multiplier: 1 training: false
shuffle: False batch_size: ${scratch.val_batch_size} num_workers: ${scratch.num_val_workers} pin_memory: False drop_last: False collate_fn: _target_: sam3.train.data.collator.collate_fn_api _partial_: true repeats: ${scratch.hybrid_repeats} dict_key: gold_metaclip_nps
meters: val: gold_metaclip_nps: # this key matches the "dict_key" in the dataloader's collate function cgf1: _target_: sam3.eval.coco_writer.PredictionDumper iou_type: "segm" dump_dir: ${launcher.experiment_log_dir}/dumps/gold_metaclip_nps merge_predictions: True postprocessor: ${scratch.mask_postprocessor_thresholded} gather_pred_via_filesys: ${scratch.gather_pred_via_filesys} maxdets: 1000000 # no limit pred_file_evaluators: - _target_: sam3.eval.cgf1_eval.CGF1Evaluator gt_path: ${paths.coco_gts} iou_type: "bbox" - _target_: sam3.eval.cgf1_eval.CGF1Evaluator gt_path: ${paths.coco_gts} iou_type: "segm"123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253# @package _global_defaults: - _self_
# ============================================================================# Paths Configuration (Chage this to your own paths)# ============================================================================# python sam3/train/train.py -c configs/odinw_text_only.yaml --use-cluster 1 --partition ${PARTITION} --account ${ACCOUNT} --qos ${QoS}
paths: odinw_data_root: <YOUR_DATA_DIR> experiment_log_dir: <YOUR EXPERIMENET LOG_DIR> bpe_path: <BPE_PATH> # This should be under assets/bpe_simple_vocab_16e6.txt.gz
supercategory_tuple: ${all_odinw_supercategories.${string:${submitit.job_array.task_index}}}# Validation transforms pipelineval_transforms: - _target_: sam3.train.transforms.basic_for_api.ComposeAPI transforms: - _target_: sam3.train.transforms.basic_for_api.RandomResizeAPI sizes: ${scratch.resolution} max_size: _target_: sam3.train.transforms.basic.get_random_resize_max_size size: ${scratch.resolution} square: true consistent_transform: False - _target_: sam3.train.transforms.basic_for_api.ToTensorAPI - _target_: sam3.train.transforms.basic_for_api.NormalizeAPI mean: ${scratch.val_norm_mean} std: ${scratch.val_norm_std}
# ============================================================================# Different helper parameters and functions# ============================================================================scratch: enable_segmentation: True # Box processing use_presence_eval: True original_box_postprocessor: _target_: sam3.eval.postprocessors.PostProcessImage max_dets_per_img: -1 # infinite detections use_original_ids: true use_original_sizes_box: true use_presence: ${scratch.use_presence_eval}
# Image processing parameters resolution: 1008 # Normalization parameters val_norm_mean: [0.5, 0.5, 0.5] val_norm_std: [0.5, 0.5, 0.5]
# Training parameters val_batch_size: 2 num_val_workers: 0 gather_pred_via_filesys: false
# ============================================================================# Trainer Configuration# ============================================================================
trainer: _target_: sam3.train.trainer.Trainer skip_saving_ckpts: true empty_gpu_mem_cache_after_eval: True max_epochs: 1 accelerator: cuda seed_value: 123 mode: val
distributed: backend: nccl find_unused_parameters: True gradient_as_bucket_view: True
loss: default: _target_: sam3.train.loss.sam3_loss.DummyLoss
data: val: _target_: sam3.train.data.torch_dataset.TorchDataset dataset: _target_: sam3.train.data.sam3_image_dataset.Sam3ImageDataset coco_json_loader: _target_: sam3.train.data.coco_json_loaders.COCO_FROM_JSON prompts: ${odinw35_prompts.${supercategory_tuple.name}} include_negatives: true category_chunk_size: 20 # Note: Since we are doing AP +ve we need to include all categories! _partial_: true img_folder: ${paths.odinw_data_root}/${supercategory_tuple.val.img_folder} ann_file: _target_: sam3.eval.coco_reindex.reindex_coco_to_temp input_json_path: ${paths.odinw_data_root}/${supercategory_tuple.val.json} transforms: ${val_transforms} max_ann_per_img: 100000 multiplier: 1 training: false
shuffle: False batch_size: ${scratch.val_batch_size} num_workers: ${scratch.num_val_workers} pin_memory: False drop_last: False collate_fn: _target_: sam3.train.data.collator.collate_fn_api _partial_: true repeats: 1 dict_key: odinw35
model: _target_: sam3.model_builder.build_sam3_image_model bpe_path: ${paths.bpe_path} device: cpus eval_mode: true # Set to false if training enable_segmentation: ${scratch.enable_segmentation} # Warning: Enable this if using segmentation.
meters: val: odinw35: detection: _target_: sam3.eval.coco_writer.PredictionDumper iou_type: "bbox" dump_dir: ${launcher.experiment_log_dir}/dumps/roboflow/${supercategory_tuple.name} merge_predictions: True postprocessor: ${scratch.original_box_postprocessor} gather_pred_via_filesys: ${scratch.gather_pred_via_filesys} maxdets: 100 pred_file_evaluators: - _target_: sam3.eval.coco_eval_offline.CocoEvaluatorOfflineWithPredFileEvaluators gt_path: _target_: sam3.eval.coco_reindex.reindex_coco_to_temp input_json_path: ${paths.odinw_data_root}/${supercategory_tuple.val.json} tide: False iou_type: "bbox" positive_split: true
checkpoint: save_dir: ${launcher.experiment_log_dir}/checkpoints save_freq: 0 # 0 only last checkpoint is saved.
logging: tensorboard_writer: _target_: sam3.train.utils.logger.make_tensorboard_logger log_dir: ${launcher.experiment_log_dir}/tensorboard flush_secs: 120 should_log: True wandb_writer: null log_dir: ${launcher.experiment_log_dir}/logs/${supercategory_tuple.name} log_freq: 10
# ============================================================================# Launcher and Submitit Configuration# ============================================================================
launcher: num_nodes: 1 gpus_per_node: 2 experiment_log_dir: ${paths.experiment_log_dir} multiprocessing_context: forkserver
submitit: account: null partition: null qos: null timeout_hour: 72 use_cluster: True cpus_per_task: 10 port_range: [10000, 65000] constraint: null
job_array: num_tasks: 13 task_index: 0
# ============================================================================# ODinW13 Supercategories# ============================================================================
all_odinw_supercategories: - name: AerialMaritimeDrone_large val: img_folder: AerialMaritimeDrone/large/test/ json: AerialMaritimeDrone/large/test/annotations_without_background.json - name: Aquarium val: img_folder: Aquarium/Aquarium Combined.v2-raw-1024.coco/test/ json: Aquarium/Aquarium Combined.v2-raw-1024.coco/test/annotations_without_background.json - name: CottontailRabbits val: img_folder: CottontailRabbits/test/ json: CottontailRabbits/test/annotations_without_background.json - name: EgoHands_generic val: img_folder: EgoHands/generic/test/ json: EgoHands/generic/test/annotations_without_background.json - name: NorthAmericaMushrooms val: img_folder: NorthAmericaMushrooms/North American Mushrooms.v1-416x416.coco/test/ json: NorthAmericaMushrooms/North American Mushrooms.v1-416x416.coco/test/annotations_without_background.json - name: Packages val: img_folder: Packages/Raw/test/ json: Packages/Raw/test/annotations_without_background.json - name: PascalVOC val: img_folder: PascalVOC/valid/ json: PascalVOC/valid/annotations_without_background.json - name: Raccoon val: img_folder: Raccoon/Raccoon.v2-raw.coco/test/ json: Raccoon/Raccoon.v2-raw.coco/test/annotations_without_background.json - name: ShellfishOpenImages val: img_folder: ShellfishOpenImages/raw/test/ json: ShellfishOpenImages/raw/test/annotations_without_background.json - name: VehiclesOpenImages val: img_folder: VehiclesOpenImages/416x416/test/ json: VehiclesOpenImages/416x416/test/annotations_without_background.json - name: pistols val: img_folder: pistols/export/ json: pistols/export/test_annotations_without_background.json - name: pothole val: img_folder: pothole/test/ json: pothole/test/annotations_without_background.json - name: thermalDogsAndPeople val: img_folder: thermalDogsAndPeople/test/ json: thermalDogsAndPeople/test/annotations_without_background.json
odinw35_prompts: AerialMaritimeDrone_large: '[{"id": 1, "name": "boat", "supercategory": "movable-objects"}, {"id": 2, "name": "car", "supercategory": "movable-objects"}, {"id": 3, "name": "dock", "supercategory": "movable-objects"}, {"id": 4, "name": "jet ski", "supercategory": "movable-objects"}, {"id": 5, "name": "boat lift", "supercategory": "movable-objects"}]' Aquarium: null CottontailRabbits: null EgoHands_generic: null NorthAmericaMushrooms: '[{''id'': 1, ''name'': ''chicken of the woods'', ''supercategory'': ''mushroom''}, {''id'': 2, ''name'': ''chanterelle'', ''supercategory'': ''mushroom''}]' Packages: null PascalVOC: null Raccoon: null ShellfishOpenImages: null VehiclesOpenImages: null pistols: null pothole: null thermalDogsAndPeople: null123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256# @package _global_defaults: - _self_
# ============================================================================# Paths Configuration (Chage this to your own paths)# ============================================================================# python sam3/train/train.py -c configs/odinw_text_only.yaml --use-cluster 1 --partition ${PARTITION} --account ${ACCOUNT} --qos ${QoS}
paths: odinw_data_root: <YOUR_DATA_DIR> experiment_log_dir: <YOUR EXPERIMENET LOG_DIR> bpe_path: <BPE_PATH> # This should be under assets/bpe_simple_vocab_16e6.txt.gz
supercategory_tuple: ${all_odinw_supercategories.${string:${submitit.job_array.task_index}}}# Validation transforms pipelineval_transforms: - _target_: sam3.train.transforms.basic_for_api.ComposeAPI transforms: - _target_: sam3.train.transforms.basic_for_api.RandomResizeAPI sizes: ${scratch.resolution} max_size: _target_: sam3.train.transforms.basic.get_random_resize_max_size size: ${scratch.resolution} square: true consistent_transform: False - _target_: sam3.train.transforms.basic_for_api.ToTensorAPI - _target_: sam3.train.transforms.basic_for_api.NormalizeAPI mean: ${scratch.val_norm_mean} std: ${scratch.val_norm_std} - _target_: sam3.train.transforms.filter_query_transforms.TextQueryToVisual keep_text_queries: false # Note: set this to false if you only want visual probability: 1.0 # always
# ============================================================================# Different helper parameters and functions# ============================================================================scratch: enable_segmentation: True # Box processing use_presence_eval: True original_box_postprocessor: _target_: sam3.eval.postprocessors.PostProcessImage max_dets_per_img: -1 # infinite detections use_original_ids: true use_original_sizes_box: true use_presence: ${scratch.use_presence_eval}
# Image processing parameters resolution: 1008 # Normalization parameters val_norm_mean: [0.5, 0.5, 0.5] val_norm_std: [0.5, 0.5, 0.5]
# Training parameters val_batch_size: 2 num_val_workers: 0 gather_pred_via_filesys: false
# ============================================================================# Trainer Configuration# ============================================================================
trainer: _target_: sam3.train.trainer.Trainer skip_saving_ckpts: true empty_gpu_mem_cache_after_eval: True max_epochs: 1 accelerator: cuda seed_value: 123 mode: val
distributed: backend: nccl find_unused_parameters: True gradient_as_bucket_view: True
loss: default: _target_: sam3.train.loss.sam3_loss.DummyLoss
data: val: _target_: sam3.train.data.torch_dataset.TorchDataset dataset: _target_: sam3.train.data.sam3_image_dataset.Sam3ImageDataset coco_json_loader: _target_: sam3.train.data.coco_json_loaders.COCO_FROM_JSON prompts: ${odinw35_prompts.${supercategory_tuple.name}} include_negatives: true category_chunk_size: 20 # Note: Since we are doing AP +ve we need to include all categories! _partial_: true img_folder: ${paths.odinw_data_root}/${supercategory_tuple.val.img_folder} ann_file: _target_: sam3.eval.coco_reindex.reindex_coco_to_temp input_json_path: ${paths.odinw_data_root}/${supercategory_tuple.val.json} transforms: ${val_transforms} max_ann_per_img: 100000 multiplier: 1 training: false
shuffle: False batch_size: ${scratch.val_batch_size} num_workers: ${scratch.num_val_workers} pin_memory: False drop_last: False collate_fn: _target_: sam3.train.data.collator.collate_fn_api _partial_: true repeats: 1 dict_key: odinw35
model: _target_: sam3.model_builder.build_sam3_image_model bpe_path: ${paths.bpe_path} device: cpus eval_mode: true # Set to false if training enable_segmentation: ${scratch.enable_segmentation} # Warning: Enable this if using segmentation.
meters: val: odinw35: detection: _target_: sam3.eval.coco_writer.PredictionDumper iou_type: "bbox" dump_dir: ${launcher.experiment_log_dir}/dumps/roboflow/${supercategory_tuple.name} merge_predictions: True postprocessor: ${scratch.original_box_postprocessor} gather_pred_via_filesys: ${scratch.gather_pred_via_filesys} maxdets: 100 pred_file_evaluators: - _target_: sam3.eval.coco_eval_offline.CocoEvaluatorOfflineWithPredFileEvaluators gt_path: _target_: sam3.eval.coco_reindex.reindex_coco_to_temp input_json_path: ${paths.odinw_data_root}/${supercategory_tuple.val.json} tide: False iou_type: "bbox" positive_split: true
checkpoint: save_dir: ${launcher.experiment_log_dir}/checkpoints save_freq: 0 # 0 only last checkpoint is saved.
logging: tensorboard_writer: _target_: sam3.train.utils.logger.make_tensorboard_logger log_dir: ${launcher.experiment_log_dir}/tensorboard flush_secs: 120 should_log: True wandb_writer: null log_dir: ${launcher.experiment_log_dir}/logs/${supercategory_tuple.name} log_freq: 10
# ============================================================================# Launcher and Submitit Configuration# ============================================================================
launcher: num_nodes: 1 gpus_per_node: 2 experiment_log_dir: ${paths.experiment_log_dir} multiprocessing_context: forkserver
submitit: account: null partition: null qos: null timeout_hour: 72 use_cluster: True cpus_per_task: 10 port_range: [10000, 65000] constraint: null
job_array: num_tasks: 13 task_index: 0
# ============================================================================# ODinW13 Supercategories# ============================================================================
all_odinw_supercategories: - name: AerialMaritimeDrone_large val: img_folder: AerialMaritimeDrone/large/test/ json: AerialMaritimeDrone/large/test/annotations_without_background.json - name: Aquarium val: img_folder: Aquarium/Aquarium Combined.v2-raw-1024.coco/test/ json: Aquarium/Aquarium Combined.v2-raw-1024.coco/test/annotations_without_background.json - name: CottontailRabbits val: img_folder: CottontailRabbits/test/ json: CottontailRabbits/test/annotations_without_background.json - name: EgoHands_generic val: img_folder: EgoHands/generic/test/ json: EgoHands/generic/test/annotations_without_background.json - name: NorthAmericaMushrooms val: img_folder: NorthAmericaMushrooms/North American Mushrooms.v1-416x416.coco/test/ json: NorthAmericaMushrooms/North American Mushrooms.v1-416x416.coco/test/annotations_without_background.json - name: Packages val: img_folder: Packages/Raw/test/ json: Packages/Raw/test/annotations_without_background.json - name: PascalVOC val: img_folder: PascalVOC/valid/ json: PascalVOC/valid/annotations_without_background.json - name: Raccoon val: img_folder: Raccoon/Raccoon.v2-raw.coco/test/ json: Raccoon/Raccoon.v2-raw.coco/test/annotations_without_background.json - name: ShellfishOpenImages val: img_folder: ShellfishOpenImages/raw/test/ json: ShellfishOpenImages/raw/test/annotations_without_background.json - name: VehiclesOpenImages val: img_folder: VehiclesOpenImages/416x416/test/ json: VehiclesOpenImages/416x416/test/annotations_without_background.json - name: pistols val: img_folder: pistols/export/ json: pistols/export/test_annotations_without_background.json - name: pothole val: img_folder: pothole/test/ json: pothole/test/annotations_without_background.json - name: thermalDogsAndPeople val: img_folder: thermalDogsAndPeople/test/ json: thermalDogsAndPeople/test/annotations_without_background.json
odinw35_prompts: AerialMaritimeDrone_large: '[{"id": 1, "name": "boat", "supercategory": "movable-objects"}, {"id": 2, "name": "car", "supercategory": "movable-objects"}, {"id": 3, "name": "dock", "supercategory": "movable-objects"}, {"id": 4, "name": "jet ski", "supercategory": "movable-objects"}, {"id": 5, "name": "boat lift", "supercategory": "movable-objects"}]' Aquarium: null CottontailRabbits: null EgoHands_generic: null NorthAmericaMushrooms: '[{''id'': 1, ''name'': ''chicken of the woods'', ''supercategory'': ''mushroom''}, {''id'': 2, ''name'': ''chanterelle'', ''supercategory'': ''mushroom''}]' Packages: null PascalVOC: null Raccoon: null ShellfishOpenImages: null VehiclesOpenImages: null pistols: null pothole: null thermalDogsAndPeople: null123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539# @package _global_defaults: - _self_
# ============================================================================# Paths Configuration (Chage this to your own paths)# ============================================================================paths: roboflow_vl_100_root: <YOUR_DATASET_DIR> experiment_log_dir: <YOUR EXPERIMENET LOG_DIR> bpe_path: <BPE_PATH> # This should be under assets/bpe_simple_vocab_16e6.txt.gz
# Roboflow dataset configurationroboflow_train: num_images: 100 # Note: This is the number of images used for training. If null, all images are used. supercategory: ${all_roboflow_supercategories.${string:${submitit.job_array.task_index}}}
# Training transforms pipeline train_transforms: - _target_: sam3.train.transforms.basic_for_api.ComposeAPI transforms: - _target_: sam3.train.transforms.filter_query_transforms.FlexibleFilterFindGetQueries query_filter: _target_: sam3.train.transforms.filter_query_transforms.FilterCrowds - _target_: sam3.train.transforms.point_sampling.RandomizeInputBbox box_noise_std: 0.1 box_noise_max: 20 - _target_: sam3.train.transforms.segmentation.DecodeRle - _target_: sam3.train.transforms.basic_for_api.RandomResizeAPI sizes: _target_: sam3.train.transforms.basic.get_random_resize_scales size: ${scratch.resolution} min_size: 480 rounded: false max_size: _target_: sam3.train.transforms.basic.get_random_resize_max_size size: ${scratch.resolution} square: true consistent_transform: ${scratch.consistent_transform} - _target_: sam3.train.transforms.basic_for_api.PadToSizeAPI size: ${scratch.resolution} consistent_transform: ${scratch.consistent_transform} - _target_: sam3.train.transforms.basic_for_api.ToTensorAPI - _target_: sam3.train.transforms.filter_query_transforms.FlexibleFilterFindGetQueries query_filter: _target_: sam3.train.transforms.filter_query_transforms.FilterEmptyTargets - _target_: sam3.train.transforms.basic_for_api.NormalizeAPI mean: ${scratch.train_norm_mean} std: ${scratch.train_norm_std} - _target_: sam3.train.transforms.filter_query_transforms.FlexibleFilterFindGetQueries query_filter: _target_: sam3.train.transforms.filter_query_transforms.FilterEmptyTargets - _target_: sam3.train.transforms.filter_query_transforms.FlexibleFilterFindGetQueries query_filter: _target_: sam3.train.transforms.filter_query_transforms.FilterFindQueriesWithTooManyOut max_num_objects: ${scratch.max_ann_per_img}
# Validation transforms pipeline val_transforms: - _target_: sam3.train.transforms.basic_for_api.ComposeAPI transforms: - _target_: sam3.train.transforms.basic_for_api.RandomResizeAPI sizes: ${scratch.resolution} max_size: _target_: sam3.train.transforms.basic.get_random_resize_max_size size: ${scratch.resolution} square: true consistent_transform: False - _target_: sam3.train.transforms.basic_for_api.ToTensorAPI - _target_: sam3.train.transforms.basic_for_api.NormalizeAPI mean: ${scratch.train_norm_mean} std: ${scratch.train_norm_std}
# loss config (no mask loss) loss: _target_: sam3.train.loss.sam3_loss.Sam3LossWrapper matcher: ${scratch.matcher} o2m_weight: 2.0 o2m_matcher: _target_: sam3.train.matcher.BinaryOneToManyMatcher alpha: 0.3 threshold: 0.4 topk: 4 use_o2m_matcher_on_o2m_aux: false # Another option is true loss_fns_find: - _target_: sam3.train.loss.loss_fns.Boxes weight_dict: loss_bbox: 5.0 loss_giou: 2.0 - _target_: sam3.train.loss.loss_fns.IABCEMdetr weak_loss: False weight_dict: loss_ce: 20.0 # Another option is 100.0 presence_loss: 20.0 pos_weight: 10.0 # Another option is 5.0 alpha: 0.25 gamma: 2 use_presence: True # Change pos_focal: false pad_n_queries: 200 pad_scale_pos: 1.0
loss_fn_semantic_seg: null scale_by_find_batch_size: ${scratch.scale_by_find_batch_size}
# NOTE: Loss to be used for training in case of segmentation # loss: # _target_: sam3.train.loss.sam3_loss.Sam3LossWrapper # matcher: ${scratch.matcher} # o2m_weight: 2.0 # o2m_matcher: # _target_: sam3.train.matcher.BinaryOneToManyMatcher # alpha: 0.3 # threshold: 0.4 # topk: 4 # use_o2m_matcher_on_o2m_aux: false # loss_fns_find: # - _target_: sam3.train.loss.loss_fns.Boxes # weight_dict: # loss_bbox: 5.0 # loss_giou: 2.0 # - _target_: sam3.train.loss.loss_fns.IABCEMdetr # weak_loss: False # weight_dict: # loss_ce: 20.0 # Another option is 100.0 # presence_loss: 20.0 # pos_weight: 10.0 # Another option is 5.0 # alpha: 0.25 # gamma: 2 # use_presence: True # Change # pos_focal: false # pad_n_queries: 200 # pad_scale_pos: 1.0 # - _target_: sam3.train.loss.loss_fns.Masks # focal_alpha: 0.25 # focal_gamma: 2.0 # weight_dict: # loss_mask: 200.0 # loss_dice: 10.0 # compute_aux: false # loss_fn_semantic_seg: # _target_: sam3.losses.loss_fns.SemanticSegCriterion # presence_head: True # presence_loss: False # Change # focal: True # focal_alpha: 0.6 # focal_gamma: 2.0 # downsample: False # weight_dict: # loss_semantic_seg: 20.0 # loss_semantic_presence: 1.0 # loss_semantic_dice: 30.0 # scale_by_find_batch_size: ${scratch.scale_by_find_batch_size}
# ============================================================================# Different helper parameters and functions# ============================================================================scratch: enable_segmentation: False # NOTE: This is the number of queries used for segmentation # Model parameters d_model: 256 pos_embed: _target_: sam3.model.position_encoding.PositionEmbeddingSine num_pos_feats: ${scratch.d_model} normalize: true scale: null temperature: 10000
# Box processing use_presence_eval: True original_box_postprocessor: _target_: sam3.eval.postprocessors.PostProcessImage max_dets_per_img: -1 # infinite detections use_original_ids: true use_original_sizes_box: true use_presence: ${scratch.use_presence_eval}
# Matcher configuration matcher: _target_: sam3.train.matcher.BinaryHungarianMatcherV2 focal: true # with `focal: true` it is equivalent to BinaryFocalHungarianMatcher cost_class: 2.0 cost_bbox: 5.0 cost_giou: 2.0 alpha: 0.25 gamma: 2 stable: False scale_by_find_batch_size: True
# Image processing parameters resolution: 1008 consistent_transform: False max_ann_per_img: 200
# Normalization parameters train_norm_mean: [0.5, 0.5, 0.5] train_norm_std: [0.5, 0.5, 0.5] val_norm_mean: [0.5, 0.5, 0.5] val_norm_std: [0.5, 0.5, 0.5]
# Training parameters num_train_workers: 10 num_val_workers: 0 max_data_epochs: 20 target_epoch_size: 1500 hybrid_repeats: 1 context_length: 2 gather_pred_via_filesys: false
# Learning rate and scheduler parameters lr_scale: 0.1 lr_transformer: ${times:8e-4,${scratch.lr_scale}} lr_vision_backbone: ${times:2.5e-4,${scratch.lr_scale}} lr_language_backbone: ${times:5e-5,${scratch.lr_scale}} lrd_vision_backbone: 0.9 wd: 0.1 scheduler_timescale: 20 scheduler_warmup: 20 scheduler_cooldown: 20
val_batch_size: 1 collate_fn_val: _target_: sam3.train.data.collator.collate_fn_api _partial_: true repeats: ${scratch.hybrid_repeats} dict_key: roboflow100 with_seg_masks: ${scratch.enable_segmentation} # Note: Set this to true if using segmentation masks!
gradient_accumulation_steps: 1 train_batch_size: 1 collate_fn: _target_: sam3.train.data.collator.collate_fn_api _partial_: true repeats: ${scratch.hybrid_repeats} dict_key: all with_seg_masks: ${scratch.enable_segmentation} # Note: Set this to true if using segmentation masks!
# ============================================================================# Trainer Configuration# ============================================================================
trainer:
_target_: sam3.train.trainer.Trainer skip_saving_ckpts: true empty_gpu_mem_cache_after_eval: True skip_first_val: True max_epochs: 20 accelerator: cuda seed_value: 123 val_epoch_freq: 10 mode: train gradient_accumulation_steps: ${scratch.gradient_accumulation_steps}
distributed: backend: nccl find_unused_parameters: True gradient_as_bucket_view: True
loss: all: ${roboflow_train.loss} default: _target_: sam3.train.loss.sam3_loss.DummyLoss
data: train: _target_: sam3.train.data.torch_dataset.TorchDataset dataset: _target_: sam3.train.data.sam3_image_dataset.Sam3ImageDataset limit_ids: ${roboflow_train.num_images} transforms: ${roboflow_train.train_transforms} load_segmentation: ${scratch.enable_segmentation} max_ann_per_img: 500000 multiplier: 1 max_train_queries: 50000 max_val_queries: 50000 training: true use_caching: False img_folder: ${paths.roboflow_vl_100_root}/${roboflow_train.supercategory}/train/ ann_file: ${paths.roboflow_vl_100_root}/${roboflow_train.supercategory}/train/_annotations.coco.json
shuffle: True batch_size: ${scratch.train_batch_size} num_workers: ${scratch.num_train_workers} pin_memory: True drop_last: True collate_fn: ${scratch.collate_fn}
val: _target_: sam3.train.data.torch_dataset.TorchDataset dataset: _target_: sam3.train.data.sam3_image_dataset.Sam3ImageDataset load_segmentation: ${scratch.enable_segmentation} coco_json_loader: _target_: sam3.train.data.coco_json_loaders.COCO_FROM_JSON include_negatives: true category_chunk_size: 2 # Note: You can increase this based on the memory of your GPU. _partial_: true img_folder: ${paths.roboflow_vl_100_root}/${roboflow_train.supercategory}/test/ ann_file: ${paths.roboflow_vl_100_root}/${roboflow_train.supercategory}/test/_annotations.coco.json transforms: ${roboflow_train.val_transforms} max_ann_per_img: 100000 multiplier: 1 training: false
shuffle: False batch_size: ${scratch.val_batch_size} num_workers: ${scratch.num_val_workers} pin_memory: True drop_last: False collate_fn: ${scratch.collate_fn_val}
model: _target_: sam3.model_builder.build_sam3_image_model bpe_path: ${paths.bpe_path} device: cpus eval_mode: false enable_segmentation: ${scratch.enable_segmentation} # Warning: Enable this if using segmentation.
meters: val: roboflow100: detection: _target_: sam3.eval.coco_writer.PredictionDumper iou_type: "bbox" dump_dir: ${launcher.experiment_log_dir}/dumps/roboflow/${roboflow_train.supercategory} merge_predictions: True postprocessor: ${scratch.original_box_postprocessor} gather_pred_via_filesys: ${scratch.gather_pred_via_filesys} maxdets: 100 pred_file_evaluators: - _target_: sam3.eval.coco_eval_offline.CocoEvaluatorOfflineWithPredFileEvaluators gt_path: ${paths.roboflow_vl_100_root}/${roboflow_train.supercategory}/test/_annotations.coco.json tide: False iou_type: "bbox"
optim: amp: enabled: True amp_dtype: bfloat16
optimizer: _target_: torch.optim.AdamW
gradient_clip: _target_: sam3.train.optim.optimizer.GradientClipper max_norm: 0.1 norm_type: 2
param_group_modifiers: - _target_: sam3.train.optim.optimizer.layer_decay_param_modifier _partial_: True layer_decay_value: ${scratch.lrd_vision_backbone} apply_to: 'backbone.vision_backbone.trunk' overrides: - pattern: '*pos_embed*' value: 1.0
options: lr: - scheduler: # transformer and class_embed _target_: sam3.train.optim.schedulers.InverseSquareRootParamScheduler base_lr: ${scratch.lr_transformer} timescale: ${scratch.scheduler_timescale} warmup_steps: ${scratch.scheduler_warmup} cooldown_steps: ${scratch.scheduler_cooldown} - scheduler: _target_: sam3.train.optim.schedulers.InverseSquareRootParamScheduler base_lr: ${scratch.lr_vision_backbone} timescale: ${scratch.scheduler_timescale} warmup_steps: ${scratch.scheduler_warmup} cooldown_steps: ${scratch.scheduler_cooldown} param_names: - 'backbone.vision_backbone.*' - scheduler: _target_: sam3.train.optim.schedulers.InverseSquareRootParamScheduler base_lr: ${scratch.lr_language_backbone} timescale: ${scratch.scheduler_timescale} warmup_steps: ${scratch.scheduler_warmup} cooldown_steps: ${scratch.scheduler_cooldown} param_names: - 'backbone.language_backbone.*'
weight_decay: - scheduler: _target_: fvcore.common.param_scheduler.ConstantParamScheduler value: ${scratch.wd} - scheduler: _target_: fvcore.common.param_scheduler.ConstantParamScheduler value: 0.0 param_names: - '*bias*' module_cls_names: ['torch.nn.LayerNorm']
checkpoint: save_dir: ${launcher.experiment_log_dir}/checkpoints save_freq: 0 # 0 only last checkpoint is saved.
logging: tensorboard_writer: _target_: sam3.train.utils.logger.make_tensorboard_logger log_dir: ${launcher.experiment_log_dir}/tensorboard flush_secs: 120 should_log: True wandb_writer: null log_dir: ${launcher.experiment_log_dir}/logs/${roboflow_train.supercategory} log_freq: 10
# ============================================================================# Launcher and Submitit Configuration# ============================================================================
launcher: num_nodes: 1 gpus_per_node: 2 experiment_log_dir: ${paths.experiment_log_dir} multiprocessing_context: forkserver
submitit: account: null partition: null qos: null timeout_hour: 72 use_cluster: True cpus_per_task: 10 port_range: [10000, 65000] constraint: null # Uncomment for job array configuration job_array: num_tasks: 100 task_index: 0
# ============================================================================# Available Roboflow Supercategories (for reference)# ============================================================================
all_roboflow_supercategories: - -grccs - zebrasatasturias - cod-mw-warzone - canalstenosis - label-printing-defect-version-2 - new-defects-in-wood - orionproducts - aquarium-combined - varroa-mites-detection--test-set - clashroyalechardetector - stomata-cells - halo-infinite-angel-videogame - pig-detection - urine-analysis1 - aerial-sheep - orgharvest - actions - mahjong - liver-disease - needle-base-tip-min-max - wheel-defect-detection - aircraft-turnaround-dataset - xray - wildfire-smoke - spinefrxnormalvindr - ufba-425 - speech-bubbles-detection - train - pill - truck-movement - car-logo-detection - inbreast - sea-cucumbers-new-tiles - uavdet-small - penguin-finder-seg - aerial-airport - bibdetection - taco-trash-annotations-in-context - bees - recode-waste - screwdetectclassification - wine-labels - aerial-cows - into-the-vale - gwhd2021 - lacrosse-object-detection - defect-detection - dataconvert - x-ray-id - ball - tube - 2024-frc - crystal-clean-brain-tumors-mri-dataset - grapes-5 - human-detection-in-floods - buoy-onboarding - apoce-aerial-photographs-for-object-detection-of-construction-equipment - l10ul502 - floating-waste - deeppcb - ism-band-packet-detection - weeds4 - invoice-processing - thermal-cheetah - tomatoes-2 - marine-sharks - peixos-fish - sssod - aerial-pool - countingpills - asphaltdistressdetection - roboflow-trained-dataset - everdaynew - underwater-objects - soda-bottles - dentalai - jellyfish - deepfruits - activity-diagrams - circuit-voltages - all-elements - macro-segmentation - exploratorium-daphnia - signatures - conveyor-t-shirts - fruitjes - grass-weeds - infraredimageofpowerequipment - 13-lkc01 - wb-prova - flir-camera-objects - paper-parts - football-player-detection - trail-camera - smd-components - water-meter - nih-xray - the-dreidel-project - electric-pylon-detection-in-rsi - cable-damagesource_code/sam3/assets/veval/toy_gt_and_pred/toy_saco_veval_sav_test_eval_res.jsonAdded+1
source_code/sam3/examples/saco_gold_silver_eval_example.ipynbAdded
source_code/sam3/examples/saco_veval_vis_example.ipynbAdded+269
source_code/sam3/examples/sam3_for_sam1_task_example.ipynbAdded+846
source_code/sam3/examples/sam3_image_interactive.ipynbAdded+757
source_code/sam3/examples/sam3_image_predictor_example.ipynbAdded
source_code/sam3/medsam3_brats/train_sam3_video_lora_ddp.pyAdded+689
source_code/sam3/sam3.egg-info/SOURCES.txtAdded+51
source_code/sam3/sam3/agent/__init__.pyAdded+1
source_code/sam3/sam3/agent/client_llm.pyAdded+205
source_code/sam3/sam3/agent/client_sam3.pyAdded+138
source_code/sam3/sam3/agent/helpers/__init__.pyAdded+1
source_code/sam3/sam3/agent/helpers/memory.pyAdded+87
source_code/sam3/sam3/agent/system_prompts/system_prompt.txtAdded+242
source_code/sam3/sam3/agent/system_prompts/system_prompt_iterative_checking.txtAdded+26
source_code/sam3/sam3/eval/cgf1_eval.pyAdded+703
source_code/sam3/sam3/eval/conversion_util.pyAdded+211
source_code/sam3/sam3/eval/hota_eval_toolkit/run_ytvis_eval.pyAdded+114
source_code/sam3/sam3/eval/hota_eval_toolkit/trackeval/datasets/_base_dataset.pyAdded+379
source_code/sam3/sam3/eval/hota_eval_toolkit/trackeval/metrics/__init__.pyAdded+4
source_code/sam3/sam3/eval/postprocessors.pyAdded+648
source_code/sam3/sam3/eval/saco_veval_evaluators.pyAdded+838
source_code/sam3/sam3/eval/teta_eval_toolkit/_timing.pyAdded+69
source_code/sam3/sam3/eval/teta_eval_toolkit/datasets/tao.pyAdded+659
source_code/sam3/sam3/eval/teta_eval_toolkit/eval.pyAdded+275
source_code/sam3/sam3/eval/teta_eval_toolkit/metrics/_base_metric.pyAdded+148
source_code/sam3/sam3/eval/ytvis_eval.pyAdded+411
source_code/sam3/sam3/model/act_ckpt_utils.pyAdded+114
source_code/sam3/sam3/model/encoder.pyAdded+594
source_code/sam3/sam3/model/maskformer_segmentation.pyAdded+323
source_code/sam3/sam3/model/sam1_task_predictor.pyAdded+458
source_code/sam3/sam3/model/sam3_image_processor.pyAdded+222
source_code/sam3/sam3/model/sam3_tracker_utils.pyAdded+427
source_code/sam3/sam3/model/sam3_tracking_predictor.pyAdded+1368
source_code/sam3/sam3/model/sam3_video_inference.pyAdded+1709
source_code/sam3/sam3/model_builder.pyAdded+793
source_code/sam3/sam3/perflib/__init__.pyAdded+8
source_code/sam3/sam3/perflib/compile.pyAdded+99
source_code/sam3/sam3/perflib/fa3.pyAdded+27
source_code/sam3/sam3/perflib/masks_ops.pyAdded+69
source_code/sam3/sam3/perflib/nms.pyAdded+91
source_code/sam3/sam3/perflib/tests/tests.pyAdded+59
source_code/sam3/sam3/perflib/triton/connected_components.pyAdded+468
source_code/sam3/sam3/sam/prompt_encoder.pyAdded+243
source_code/sam3/sam3/train/configs/eval_base.yamlAdded+279
source_code/sam3/sam3/train/configs/gold_image_evals/sam3_gold_image_attributes.yamlAdded+66
source_code/sam3/sam3/train/configs/gold_image_evals/sam3_gold_image_metaclip_nps.yamlAdded+66
source_code/sam3/sam3/train/configs/odinw13/odinw_text_only_positive.yamlAdded+253
source_code/sam3/sam3/train/configs/odinw13/odinw_visual_only.yamlAdded+256
source_code/sam3/sam3/train/configs/roboflow_v100/roboflow_v100_full_ft_100_images.yamlAdded+539