Add files using upload-large-folder tool
Browse files- benchmarks/VGMED/image_folder/SAMed2D_v1/pet/masks/pet_00--autoPET--PETCT_04a4e1c874_11-18-2001-NA-PET-CT_Ganzkoerper__primaer_mit_KM-96019--x_0187--0000_000.png +3 -0
- benchmarks/VGMED/image_folder/SAMed2D_v1/pet/masks/pet_00--autoPET--PETCT_2b60c8135a_12-09-2005-NA-PET-CT_Ganzkoerper__primaer_mit_KM-49696--x_0211--0000_001.png +3 -0
- benchmarks/VGMED/image_folder/SAMed2D_v1/pet/masks/pet_00--autoPET--PETCT_2b60c8135a_12-09-2005-NA-PET-CT_Ganzkoerper__primaer_mit_KM-49696--y_0164--0000_018.png +3 -0
- benchmarks/VGMED/image_folder/SAMed2D_v1/pet/masks/pet_00--autoPET--PETCT_4c75fa4a5d_04-19-2001-NA-PET-CT_Ganzkoerper__primaer_mit_KM-33664--y_0208--0000_000.png +3 -0
- benchmarks/VGMED/image_folder/SAMed2D_v1/pet/masks/pet_00--autoPET--PETCT_53a0610615_07-14-2001-NA-PET-CT_Ganzkoerper__primaer_mit_KM-95772--z_0180--0000_000.png +3 -0
- benchmarks/VGMED/image_folder/SAMed2D_v1/pet/masks/pet_00--autoPET--PETCT_5ac322455f_05-26-2003-NA-PET-CT_Ganzkoerper__primaer_mit_KM-53199--x_0127--0000_000.png +3 -0
- benchmarks/VGMED/image_folder/SAMed2D_v1/pet/masks/pet_00--autoPET--PETCT_685d7c09b5_12-23-2000-NA-PET-CT_Ganzkoerper__primaer_mit_KM-22883--x_0224--0000_000.png +3 -0
- benchmarks/VGMED/image_folder/SAMed2D_v1/pet/masks/pet_00--autoPET--PETCT_9afd440677_03-17-2003-NA-PET-CT_Ganzkoerper__primaer_mit_KM-70730--x_0195--0000_000.png +3 -0
- benchmarks/VGMED/image_folder/SAMed2D_v1/pet/masks/pet_00--autoPET--PETCT_aa27cb9156_12-14-2003-NA-PET-CT_Ganzkoerper__primaer_mit_KM-81079--y_0209--0000_004.png +3 -0
- 之前的代码版本/这一版注意力有问题/HuatuoGPT-Vision/MedSAM3/sam3/model/box_ops.py +217 -0
- 之前的代码版本/这一版注意力有问题/HuatuoGPT-Vision/MedSAM3/sam3/model/io_utils.py +709 -0
- 之前的代码版本/这一版注意力有问题/HuatuoGPT-Vision/MedSAM3/sam3/model/maskformer_segmentation.py +323 -0
- 之前的代码版本/这一版注意力有问题/HuatuoGPT-Vision/MedSAM3/sam3/model/memory.py +201 -0
- 之前的代码版本/这一版注意力有问题/HuatuoGPT-Vision/MedSAM3/sam3/model/necks.py +125 -0
- 之前的代码版本/这一版注意力有问题/HuatuoGPT-Vision/MedSAM3/sam3/model/sam3_image.py +883 -0
- 之前的代码版本/这一版注意力有问题/HuatuoGPT-Vision/MedSAM3/sam3/model/sam3_tracker_utils.py +427 -0
- 之前的代码版本/这一版注意力有问题/HuatuoGPT-Vision/MedSAM3/sam3/model/sam3_tracking_predictor.py +1368 -0
- 之前的代码版本/这一版注意力有问题/HuatuoGPT-Vision/MedSAM3/sam3/model/sam3_video_base.py +1767 -0
- 之前的代码版本/这一版注意力有问题/HuatuoGPT-Vision/MedSAM3/sam3/model/sam3_video_predictor.py +521 -0
- 之前的代码版本/这一版注意力有问题/HuatuoGPT-Vision/MedSAM3/sam3/model/tokenizer_ve.py +253 -0
benchmarks/VGMED/image_folder/SAMed2D_v1/pet/masks/pet_00--autoPET--PETCT_04a4e1c874_11-18-2001-NA-PET-CT_Ganzkoerper__primaer_mit_KM-96019--x_0187--0000_000.png
ADDED
|
Git LFS Details
|
benchmarks/VGMED/image_folder/SAMed2D_v1/pet/masks/pet_00--autoPET--PETCT_2b60c8135a_12-09-2005-NA-PET-CT_Ganzkoerper__primaer_mit_KM-49696--x_0211--0000_001.png
ADDED
|
Git LFS Details
|
benchmarks/VGMED/image_folder/SAMed2D_v1/pet/masks/pet_00--autoPET--PETCT_2b60c8135a_12-09-2005-NA-PET-CT_Ganzkoerper__primaer_mit_KM-49696--y_0164--0000_018.png
ADDED
|
Git LFS Details
|
benchmarks/VGMED/image_folder/SAMed2D_v1/pet/masks/pet_00--autoPET--PETCT_4c75fa4a5d_04-19-2001-NA-PET-CT_Ganzkoerper__primaer_mit_KM-33664--y_0208--0000_000.png
ADDED
|
Git LFS Details
|
benchmarks/VGMED/image_folder/SAMed2D_v1/pet/masks/pet_00--autoPET--PETCT_53a0610615_07-14-2001-NA-PET-CT_Ganzkoerper__primaer_mit_KM-95772--z_0180--0000_000.png
ADDED
|
Git LFS Details
|
benchmarks/VGMED/image_folder/SAMed2D_v1/pet/masks/pet_00--autoPET--PETCT_5ac322455f_05-26-2003-NA-PET-CT_Ganzkoerper__primaer_mit_KM-53199--x_0127--0000_000.png
ADDED
|
Git LFS Details
|
benchmarks/VGMED/image_folder/SAMed2D_v1/pet/masks/pet_00--autoPET--PETCT_685d7c09b5_12-23-2000-NA-PET-CT_Ganzkoerper__primaer_mit_KM-22883--x_0224--0000_000.png
ADDED
|
Git LFS Details
|
benchmarks/VGMED/image_folder/SAMed2D_v1/pet/masks/pet_00--autoPET--PETCT_9afd440677_03-17-2003-NA-PET-CT_Ganzkoerper__primaer_mit_KM-70730--x_0195--0000_000.png
ADDED
|
Git LFS Details
|
benchmarks/VGMED/image_folder/SAMed2D_v1/pet/masks/pet_00--autoPET--PETCT_aa27cb9156_12-14-2003-NA-PET-CT_Ganzkoerper__primaer_mit_KM-81079--y_0209--0000_004.png
ADDED
|
Git LFS Details
|
之前的代码版本/这一版注意力有问题/HuatuoGPT-Vision/MedSAM3/sam3/model/box_ops.py
ADDED
|
@@ -0,0 +1,217 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
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|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
# Copyright (c) Meta Platforms, Inc. and affiliates. All Rights Reserved
|
| 2 |
+
"""
|
| 3 |
+
Utilities for bounding box manipulation and GIoU.
|
| 4 |
+
"""
|
| 5 |
+
|
| 6 |
+
from typing import Tuple
|
| 7 |
+
|
| 8 |
+
import torch
|
| 9 |
+
|
| 10 |
+
|
| 11 |
+
def box_cxcywh_to_xyxy(x):
|
| 12 |
+
x_c, y_c, w, h = x.unbind(-1)
|
| 13 |
+
b = [(x_c - 0.5 * w), (y_c - 0.5 * h), (x_c + 0.5 * w), (y_c + 0.5 * h)]
|
| 14 |
+
return torch.stack(b, dim=-1)
|
| 15 |
+
|
| 16 |
+
|
| 17 |
+
def box_cxcywh_to_xywh(x):
|
| 18 |
+
x_c, y_c, w, h = x.unbind(-1)
|
| 19 |
+
b = [(x_c - 0.5 * w), (y_c - 0.5 * h), (w), (h)]
|
| 20 |
+
return torch.stack(b, dim=-1)
|
| 21 |
+
|
| 22 |
+
|
| 23 |
+
def box_xywh_to_xyxy(x):
|
| 24 |
+
x, y, w, h = x.unbind(-1)
|
| 25 |
+
b = [(x), (y), (x + w), (y + h)]
|
| 26 |
+
return torch.stack(b, dim=-1)
|
| 27 |
+
|
| 28 |
+
|
| 29 |
+
def box_xywh_to_cxcywh(x):
|
| 30 |
+
x, y, w, h = x.unbind(-1)
|
| 31 |
+
b = [(x + 0.5 * w), (y + 0.5 * h), (w), (h)]
|
| 32 |
+
return torch.stack(b, dim=-1)
|
| 33 |
+
|
| 34 |
+
|
| 35 |
+
def box_xyxy_to_xywh(x):
|
| 36 |
+
x, y, X, Y = x.unbind(-1)
|
| 37 |
+
b = [(x), (y), (X - x), (Y - y)]
|
| 38 |
+
return torch.stack(b, dim=-1)
|
| 39 |
+
|
| 40 |
+
|
| 41 |
+
def box_xyxy_to_cxcywh(x):
|
| 42 |
+
x0, y0, x1, y1 = x.unbind(-1)
|
| 43 |
+
b = [(x0 + x1) / 2, (y0 + y1) / 2, (x1 - x0), (y1 - y0)]
|
| 44 |
+
return torch.stack(b, dim=-1)
|
| 45 |
+
|
| 46 |
+
|
| 47 |
+
def box_area(boxes):
|
| 48 |
+
"""
|
| 49 |
+
Batched version of box area. Boxes should be in [x0, y0, x1, y1] format.
|
| 50 |
+
|
| 51 |
+
Inputs:
|
| 52 |
+
- boxes: Tensor of shape (..., 4)
|
| 53 |
+
|
| 54 |
+
Returns:
|
| 55 |
+
- areas: Tensor of shape (...,)
|
| 56 |
+
"""
|
| 57 |
+
x0, y0, x1, y1 = boxes.unbind(-1)
|
| 58 |
+
return (x1 - x0) * (y1 - y0)
|
| 59 |
+
|
| 60 |
+
|
| 61 |
+
def masks_to_boxes(masks):
|
| 62 |
+
"""Compute the bounding boxes around the provided masks
|
| 63 |
+
|
| 64 |
+
The masks should be in format [N, H, W] where N is the number of masks, (H, W) are the spatial dimensions.
|
| 65 |
+
|
| 66 |
+
Returns a [N, 4] tensors, with the boxes in xyxy format
|
| 67 |
+
"""
|
| 68 |
+
if masks.numel() == 0:
|
| 69 |
+
return torch.zeros((0, 4), device=masks.device)
|
| 70 |
+
|
| 71 |
+
h, w = masks.shape[-2:]
|
| 72 |
+
|
| 73 |
+
y = torch.arange(0, h, dtype=torch.float, device=masks.device)
|
| 74 |
+
x = torch.arange(0, w, dtype=torch.float, device=masks.device)
|
| 75 |
+
y, x = torch.meshgrid(y, x)
|
| 76 |
+
|
| 77 |
+
x_mask = masks * x.unsqueeze(0)
|
| 78 |
+
x_max = x_mask.flatten(1).max(-1)[0] + 1
|
| 79 |
+
x_min = x_mask.masked_fill(~(masks.bool()), 1e8).flatten(1).min(-1)[0]
|
| 80 |
+
|
| 81 |
+
y_mask = masks * y.unsqueeze(0)
|
| 82 |
+
y_max = y_mask.flatten(1).max(-1)[0] + 1
|
| 83 |
+
y_min = y_mask.masked_fill(~(masks.bool()), 1e8).flatten(1).min(-1)[0]
|
| 84 |
+
|
| 85 |
+
boxes = torch.stack([x_min, y_min, x_max, y_max], 1)
|
| 86 |
+
# Invalidate boxes corresponding to empty masks.
|
| 87 |
+
boxes = boxes * masks.flatten(-2).any(-1)
|
| 88 |
+
return boxes
|
| 89 |
+
|
| 90 |
+
|
| 91 |
+
def box_iou(boxes1, boxes2):
|
| 92 |
+
"""
|
| 93 |
+
Batched version of box_iou. Boxes should be in [x0, y0, x1, y1] format.
|
| 94 |
+
|
| 95 |
+
Inputs:
|
| 96 |
+
- boxes1: Tensor of shape (..., N, 4)
|
| 97 |
+
- boxes2: Tensor of shape (..., M, 4)
|
| 98 |
+
|
| 99 |
+
Returns:
|
| 100 |
+
- iou, union: Tensors of shape (..., N, M)
|
| 101 |
+
"""
|
| 102 |
+
area1 = box_area(boxes1)
|
| 103 |
+
area2 = box_area(boxes2)
|
| 104 |
+
|
| 105 |
+
# boxes1: (..., N, 4) -> (..., N, 1, 2)
|
| 106 |
+
# boxes2: (..., M, 4) -> (..., 1, M, 2)
|
| 107 |
+
lt = torch.max(boxes1[..., :, None, :2], boxes2[..., None, :, :2])
|
| 108 |
+
rb = torch.min(boxes1[..., :, None, 2:], boxes2[..., None, :, 2:])
|
| 109 |
+
|
| 110 |
+
wh = (rb - lt).clamp(min=0) # (..., N, M, 2)
|
| 111 |
+
inter = wh[..., 0] * wh[..., 1] # (..., N, M)
|
| 112 |
+
|
| 113 |
+
union = area1[..., None] + area2[..., None, :] - inter
|
| 114 |
+
|
| 115 |
+
iou = inter / union
|
| 116 |
+
return iou, union
|
| 117 |
+
|
| 118 |
+
|
| 119 |
+
def generalized_box_iou(boxes1, boxes2):
|
| 120 |
+
"""
|
| 121 |
+
Batched version of Generalized IoU from https://giou.stanford.edu/
|
| 122 |
+
|
| 123 |
+
Boxes should be in [x0, y0, x1, y1] format
|
| 124 |
+
|
| 125 |
+
Inputs:
|
| 126 |
+
- boxes1: Tensor of shape (..., N, 4)
|
| 127 |
+
- boxes2: Tensor of shape (..., M, 4)
|
| 128 |
+
|
| 129 |
+
Returns:
|
| 130 |
+
- giou: Tensor of shape (..., N, M)
|
| 131 |
+
"""
|
| 132 |
+
iou, union = box_iou(boxes1, boxes2)
|
| 133 |
+
|
| 134 |
+
# boxes1: (..., N, 4) -> (..., N, 1, 2)
|
| 135 |
+
# boxes2: (..., M, 4) -> (..., 1, M, 2)
|
| 136 |
+
lt = torch.min(boxes1[..., :, None, :2], boxes2[..., None, :, :2])
|
| 137 |
+
rb = torch.max(boxes1[..., :, None, 2:], boxes2[..., None, :, 2:])
|
| 138 |
+
|
| 139 |
+
wh = (rb - lt).clamp(min=0) # (..., N, M, 2)
|
| 140 |
+
area = wh[..., 0] * wh[..., 1] # (..., N, M)
|
| 141 |
+
|
| 142 |
+
return iou - (area - union) / area
|
| 143 |
+
|
| 144 |
+
|
| 145 |
+
@torch.jit.script
|
| 146 |
+
def fast_diag_generalized_box_iou(boxes1, boxes2):
|
| 147 |
+
assert len(boxes1) == len(boxes2)
|
| 148 |
+
box1_xy = boxes1[:, 2:]
|
| 149 |
+
box1_XY = boxes1[:, :2]
|
| 150 |
+
box2_xy = boxes2[:, 2:]
|
| 151 |
+
box2_XY = boxes2[:, :2]
|
| 152 |
+
# assert (box1_xy >= box1_XY).all()
|
| 153 |
+
# assert (box2_xy >= box2_XY).all()
|
| 154 |
+
area1 = (box1_xy - box1_XY).prod(-1)
|
| 155 |
+
area2 = (box2_xy - box2_XY).prod(-1)
|
| 156 |
+
|
| 157 |
+
lt = torch.max(box1_XY, box2_XY) # [N,2]
|
| 158 |
+
lt2 = torch.min(box1_XY, box2_XY)
|
| 159 |
+
rb = torch.min(box1_xy, box2_xy) # [N,2]
|
| 160 |
+
rb2 = torch.max(box1_xy, box2_xy)
|
| 161 |
+
|
| 162 |
+
inter = (rb - lt).clamp(min=0).prod(-1)
|
| 163 |
+
tot_area = (rb2 - lt2).clamp(min=0).prod(-1)
|
| 164 |
+
|
| 165 |
+
union = area1 + area2 - inter
|
| 166 |
+
|
| 167 |
+
iou = inter / union
|
| 168 |
+
|
| 169 |
+
return iou - (tot_area - union) / tot_area
|
| 170 |
+
|
| 171 |
+
|
| 172 |
+
@torch.jit.script
|
| 173 |
+
def fast_diag_box_iou(boxes1, boxes2):
|
| 174 |
+
assert len(boxes1) == len(boxes2)
|
| 175 |
+
box1_xy = boxes1[:, 2:]
|
| 176 |
+
box1_XY = boxes1[:, :2]
|
| 177 |
+
box2_xy = boxes2[:, 2:]
|
| 178 |
+
box2_XY = boxes2[:, :2]
|
| 179 |
+
# assert (box1_xy >= box1_XY).all()
|
| 180 |
+
# assert (box2_xy >= box2_XY).all()
|
| 181 |
+
area1 = (box1_xy - box1_XY).prod(-1)
|
| 182 |
+
area2 = (box2_xy - box2_XY).prod(-1)
|
| 183 |
+
|
| 184 |
+
lt = torch.max(box1_XY, box2_XY) # [N,2]
|
| 185 |
+
rb = torch.min(box1_xy, box2_xy) # [N,2]
|
| 186 |
+
|
| 187 |
+
inter = (rb - lt).clamp(min=0).prod(-1)
|
| 188 |
+
|
| 189 |
+
union = area1 + area2 - inter
|
| 190 |
+
|
| 191 |
+
iou = inter / union
|
| 192 |
+
|
| 193 |
+
return iou
|
| 194 |
+
|
| 195 |
+
|
| 196 |
+
def box_xywh_inter_union(
|
| 197 |
+
boxes1: torch.Tensor, boxes2: torch.Tensor
|
| 198 |
+
) -> Tuple[torch.Tensor, torch.Tensor]:
|
| 199 |
+
# Asuumes boxes in xywh format
|
| 200 |
+
assert boxes1.size(-1) == 4 and boxes2.size(-1) == 4
|
| 201 |
+
boxes1 = box_xywh_to_xyxy(boxes1)
|
| 202 |
+
boxes2 = box_xywh_to_xyxy(boxes2)
|
| 203 |
+
box1_tl_xy = boxes1[..., :2]
|
| 204 |
+
box1_br_xy = boxes1[..., 2:]
|
| 205 |
+
box2_tl_xy = boxes2[..., :2]
|
| 206 |
+
box2_br_xy = boxes2[..., 2:]
|
| 207 |
+
area1 = (box1_br_xy - box1_tl_xy).prod(-1)
|
| 208 |
+
area2 = (box2_br_xy - box2_tl_xy).prod(-1)
|
| 209 |
+
|
| 210 |
+
assert (area1 >= 0).all() and (area2 >= 0).all()
|
| 211 |
+
tl = torch.max(box1_tl_xy, box2_tl_xy)
|
| 212 |
+
br = torch.min(box1_br_xy, box2_br_xy)
|
| 213 |
+
|
| 214 |
+
inter = (br - tl).clamp(min=0).prod(-1)
|
| 215 |
+
union = area1 + area2 - inter
|
| 216 |
+
|
| 217 |
+
return inter, union
|
之前的代码版本/这一版注意力有问题/HuatuoGPT-Vision/MedSAM3/sam3/model/io_utils.py
ADDED
|
@@ -0,0 +1,709 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|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
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
# Copyright (c) Meta Platforms, Inc. and affiliates. All Rights Reserved
|
| 2 |
+
|
| 3 |
+
import contextlib
|
| 4 |
+
import os
|
| 5 |
+
import queue
|
| 6 |
+
import re
|
| 7 |
+
import time
|
| 8 |
+
from threading import Condition, get_ident, Lock, Thread
|
| 9 |
+
|
| 10 |
+
import numpy as np
|
| 11 |
+
import torch
|
| 12 |
+
import torch.nn.functional as F
|
| 13 |
+
import torchvision.transforms.functional as TF
|
| 14 |
+
|
| 15 |
+
from PIL import Image
|
| 16 |
+
|
| 17 |
+
from sam3.logger import get_logger
|
| 18 |
+
from tqdm import tqdm
|
| 19 |
+
|
| 20 |
+
logger = get_logger(__name__)
|
| 21 |
+
|
| 22 |
+
IS_MAIN_PROCESS = os.getenv("IS_MAIN_PROCESS", "1") == "1"
|
| 23 |
+
RANK = int(os.getenv("RANK", "0"))
|
| 24 |
+
|
| 25 |
+
IMAGE_EXTS = [".jpg", ".jpeg", ".png", ".bmp", ".tiff", ".webp"]
|
| 26 |
+
VIDEO_EXTS = [".mp4", ".mov", ".avi", ".mkv", ".webm"]
|
| 27 |
+
|
| 28 |
+
|
| 29 |
+
def load_resource_as_video_frames(
|
| 30 |
+
resource_path,
|
| 31 |
+
image_size,
|
| 32 |
+
offload_video_to_cpu,
|
| 33 |
+
img_mean=(0.5, 0.5, 0.5),
|
| 34 |
+
img_std=(0.5, 0.5, 0.5),
|
| 35 |
+
async_loading_frames=False,
|
| 36 |
+
video_loader_type="cv2",
|
| 37 |
+
):
|
| 38 |
+
"""
|
| 39 |
+
Load video frames from either a video or an image (as a single-frame video).
|
| 40 |
+
Alternatively, if input is a list of PIL images, convert its format
|
| 41 |
+
"""
|
| 42 |
+
if isinstance(resource_path, list):
|
| 43 |
+
img_mean = torch.tensor(img_mean, dtype=torch.float16)[:, None, None]
|
| 44 |
+
img_std = torch.tensor(img_std, dtype=torch.float16)[:, None, None]
|
| 45 |
+
assert all(isinstance(img_pil, Image.Image) for img_pil in resource_path)
|
| 46 |
+
assert len(resource_path) is not None
|
| 47 |
+
orig_height, orig_width = resource_path[0].size
|
| 48 |
+
orig_height, orig_width = (
|
| 49 |
+
orig_width,
|
| 50 |
+
orig_height,
|
| 51 |
+
) # For some reason, this method returns these swapped
|
| 52 |
+
images = []
|
| 53 |
+
for img_pil in resource_path:
|
| 54 |
+
img_np = np.array(img_pil.convert("RGB").resize((image_size, image_size)))
|
| 55 |
+
assert img_np.dtype == np.uint8, "np.uint8 is expected for JPEG images"
|
| 56 |
+
img_np = img_np / 255.0
|
| 57 |
+
img = torch.from_numpy(img_np).permute(2, 0, 1)
|
| 58 |
+
# float16 precision should be sufficient for image tensor storage
|
| 59 |
+
img = img.to(dtype=torch.float16)
|
| 60 |
+
# normalize by mean and std
|
| 61 |
+
img -= img_mean
|
| 62 |
+
img /= img_std
|
| 63 |
+
images.append(img)
|
| 64 |
+
images = torch.stack(images)
|
| 65 |
+
if not offload_video_to_cpu:
|
| 66 |
+
images = images.cuda()
|
| 67 |
+
return images, orig_height, orig_width
|
| 68 |
+
|
| 69 |
+
is_image = (
|
| 70 |
+
isinstance(resource_path, str)
|
| 71 |
+
and os.path.splitext(resource_path)[-1].lower() in IMAGE_EXTS
|
| 72 |
+
)
|
| 73 |
+
if is_image:
|
| 74 |
+
return load_image_as_single_frame_video(
|
| 75 |
+
image_path=resource_path,
|
| 76 |
+
image_size=image_size,
|
| 77 |
+
offload_video_to_cpu=offload_video_to_cpu,
|
| 78 |
+
img_mean=img_mean,
|
| 79 |
+
img_std=img_std,
|
| 80 |
+
)
|
| 81 |
+
else:
|
| 82 |
+
return load_video_frames(
|
| 83 |
+
video_path=resource_path,
|
| 84 |
+
image_size=image_size,
|
| 85 |
+
offload_video_to_cpu=offload_video_to_cpu,
|
| 86 |
+
img_mean=img_mean,
|
| 87 |
+
img_std=img_std,
|
| 88 |
+
async_loading_frames=async_loading_frames,
|
| 89 |
+
video_loader_type=video_loader_type,
|
| 90 |
+
)
|
| 91 |
+
|
| 92 |
+
|
| 93 |
+
def load_image_as_single_frame_video(
|
| 94 |
+
image_path,
|
| 95 |
+
image_size,
|
| 96 |
+
offload_video_to_cpu,
|
| 97 |
+
img_mean=(0.5, 0.5, 0.5),
|
| 98 |
+
img_std=(0.5, 0.5, 0.5),
|
| 99 |
+
):
|
| 100 |
+
"""Load an image as a single-frame video."""
|
| 101 |
+
images, image_height, image_width = _load_img_as_tensor(image_path, image_size)
|
| 102 |
+
images = images.unsqueeze(0).half()
|
| 103 |
+
|
| 104 |
+
img_mean = torch.tensor(img_mean, dtype=torch.float16)[:, None, None]
|
| 105 |
+
img_std = torch.tensor(img_std, dtype=torch.float16)[:, None, None]
|
| 106 |
+
if not offload_video_to_cpu:
|
| 107 |
+
images = images.cuda()
|
| 108 |
+
img_mean = img_mean.cuda()
|
| 109 |
+
img_std = img_std.cuda()
|
| 110 |
+
# normalize by mean and std
|
| 111 |
+
images -= img_mean
|
| 112 |
+
images /= img_std
|
| 113 |
+
return images, image_height, image_width
|
| 114 |
+
|
| 115 |
+
|
| 116 |
+
def load_video_frames(
|
| 117 |
+
video_path,
|
| 118 |
+
image_size,
|
| 119 |
+
offload_video_to_cpu,
|
| 120 |
+
img_mean=(0.5, 0.5, 0.5),
|
| 121 |
+
img_std=(0.5, 0.5, 0.5),
|
| 122 |
+
async_loading_frames=False,
|
| 123 |
+
video_loader_type="cv2",
|
| 124 |
+
):
|
| 125 |
+
"""
|
| 126 |
+
Load the video frames from video_path. The frames are resized to image_size as in
|
| 127 |
+
the model and are loaded to GPU if offload_video_to_cpu=False. This is used by the demo.
|
| 128 |
+
"""
|
| 129 |
+
assert isinstance(video_path, str)
|
| 130 |
+
if video_path.startswith("<load-dummy-video"):
|
| 131 |
+
# Check for pattern <load-dummy-video-N> where N is an integer
|
| 132 |
+
match = re.match(r"<load-dummy-video-(\d+)>", video_path)
|
| 133 |
+
num_frames = int(match.group(1)) if match else 60
|
| 134 |
+
return load_dummy_video(image_size, offload_video_to_cpu, num_frames=num_frames)
|
| 135 |
+
elif os.path.isdir(video_path):
|
| 136 |
+
return load_video_frames_from_image_folder(
|
| 137 |
+
image_folder=video_path,
|
| 138 |
+
image_size=image_size,
|
| 139 |
+
offload_video_to_cpu=offload_video_to_cpu,
|
| 140 |
+
img_mean=img_mean,
|
| 141 |
+
img_std=img_std,
|
| 142 |
+
async_loading_frames=async_loading_frames,
|
| 143 |
+
)
|
| 144 |
+
elif os.path.splitext(video_path)[-1].lower() in VIDEO_EXTS:
|
| 145 |
+
return load_video_frames_from_video_file(
|
| 146 |
+
video_path=video_path,
|
| 147 |
+
image_size=image_size,
|
| 148 |
+
offload_video_to_cpu=offload_video_to_cpu,
|
| 149 |
+
img_mean=img_mean,
|
| 150 |
+
img_std=img_std,
|
| 151 |
+
async_loading_frames=async_loading_frames,
|
| 152 |
+
video_loader_type=video_loader_type,
|
| 153 |
+
)
|
| 154 |
+
else:
|
| 155 |
+
raise NotImplementedError("Only video files and image folders are supported")
|
| 156 |
+
|
| 157 |
+
|
| 158 |
+
def load_video_frames_from_image_folder(
|
| 159 |
+
image_folder,
|
| 160 |
+
image_size,
|
| 161 |
+
offload_video_to_cpu,
|
| 162 |
+
img_mean,
|
| 163 |
+
img_std,
|
| 164 |
+
async_loading_frames,
|
| 165 |
+
):
|
| 166 |
+
"""
|
| 167 |
+
Load the video frames from a directory of image files ("<frame_index>.<img_ext>" format)
|
| 168 |
+
"""
|
| 169 |
+
frame_names = [
|
| 170 |
+
p
|
| 171 |
+
for p in os.listdir(image_folder)
|
| 172 |
+
if os.path.splitext(p)[-1].lower() in IMAGE_EXTS
|
| 173 |
+
]
|
| 174 |
+
try:
|
| 175 |
+
frame_names.sort(key=lambda p: int(os.path.splitext(p)[0]))
|
| 176 |
+
except ValueError:
|
| 177 |
+
# fallback to lexicographic sort if the format is not "<frame_index>.<img_ext>"
|
| 178 |
+
logger.warning(
|
| 179 |
+
f'frame names are not in "<frame_index>.<img_ext>" format: {frame_names[:5]=}, '
|
| 180 |
+
f"falling back to lexicographic sort."
|
| 181 |
+
)
|
| 182 |
+
frame_names.sort()
|
| 183 |
+
num_frames = len(frame_names)
|
| 184 |
+
if num_frames == 0:
|
| 185 |
+
raise RuntimeError(f"no images found in {image_folder}")
|
| 186 |
+
img_paths = [os.path.join(image_folder, frame_name) for frame_name in frame_names]
|
| 187 |
+
img_mean = torch.tensor(img_mean, dtype=torch.float16)[:, None, None]
|
| 188 |
+
img_std = torch.tensor(img_std, dtype=torch.float16)[:, None, None]
|
| 189 |
+
|
| 190 |
+
if async_loading_frames:
|
| 191 |
+
lazy_images = AsyncImageFrameLoader(
|
| 192 |
+
img_paths, image_size, offload_video_to_cpu, img_mean, img_std
|
| 193 |
+
)
|
| 194 |
+
return lazy_images, lazy_images.video_height, lazy_images.video_width
|
| 195 |
+
|
| 196 |
+
# float16 precision should be sufficient for image tensor storage
|
| 197 |
+
images = torch.zeros(num_frames, 3, image_size, image_size, dtype=torch.float16)
|
| 198 |
+
video_height, video_width = None, None
|
| 199 |
+
for n, img_path in enumerate(
|
| 200 |
+
tqdm(img_paths, desc=f"frame loading (image folder) [rank={RANK}]")
|
| 201 |
+
):
|
| 202 |
+
images[n], video_height, video_width = _load_img_as_tensor(img_path, image_size)
|
| 203 |
+
if not offload_video_to_cpu:
|
| 204 |
+
images = images.cuda()
|
| 205 |
+
img_mean = img_mean.cuda()
|
| 206 |
+
img_std = img_std.cuda()
|
| 207 |
+
# normalize by mean and std
|
| 208 |
+
images -= img_mean
|
| 209 |
+
images /= img_std
|
| 210 |
+
return images, video_height, video_width
|
| 211 |
+
|
| 212 |
+
|
| 213 |
+
def load_video_frames_from_video_file(
|
| 214 |
+
video_path,
|
| 215 |
+
image_size,
|
| 216 |
+
offload_video_to_cpu,
|
| 217 |
+
img_mean,
|
| 218 |
+
img_std,
|
| 219 |
+
async_loading_frames,
|
| 220 |
+
gpu_acceleration=False,
|
| 221 |
+
gpu_device=None,
|
| 222 |
+
video_loader_type="cv2",
|
| 223 |
+
):
|
| 224 |
+
"""Load the video frames from a video file."""
|
| 225 |
+
if video_loader_type == "cv2":
|
| 226 |
+
return load_video_frames_from_video_file_using_cv2(
|
| 227 |
+
video_path=video_path,
|
| 228 |
+
image_size=image_size,
|
| 229 |
+
img_mean=img_mean,
|
| 230 |
+
img_std=img_std,
|
| 231 |
+
offload_video_to_cpu=offload_video_to_cpu,
|
| 232 |
+
)
|
| 233 |
+
elif video_loader_type == "torchcodec":
|
| 234 |
+
logger.info("Using torchcodec to load video file")
|
| 235 |
+
lazy_images = AsyncVideoFileLoaderWithTorchCodec(
|
| 236 |
+
video_path=video_path,
|
| 237 |
+
image_size=image_size,
|
| 238 |
+
offload_video_to_cpu=offload_video_to_cpu,
|
| 239 |
+
img_mean=img_mean,
|
| 240 |
+
img_std=img_std,
|
| 241 |
+
gpu_acceleration=gpu_acceleration,
|
| 242 |
+
gpu_device=gpu_device,
|
| 243 |
+
)
|
| 244 |
+
# The `AsyncVideoFileLoaderWithTorchCodec` class always loads the videos asynchronously,
|
| 245 |
+
# so we just wait for its loading thread to finish if async_loading_frames=False.
|
| 246 |
+
if not async_loading_frames:
|
| 247 |
+
async_thread = lazy_images.thread
|
| 248 |
+
if async_thread is not None:
|
| 249 |
+
async_thread.join()
|
| 250 |
+
return lazy_images, lazy_images.video_height, lazy_images.video_width
|
| 251 |
+
else:
|
| 252 |
+
raise RuntimeError("video_loader_type must be either 'cv2' or 'torchcodec'")
|
| 253 |
+
|
| 254 |
+
|
| 255 |
+
def load_video_frames_from_video_file_using_cv2(
|
| 256 |
+
video_path: str,
|
| 257 |
+
image_size: int,
|
| 258 |
+
img_mean: tuple = (0.5, 0.5, 0.5),
|
| 259 |
+
img_std: tuple = (0.5, 0.5, 0.5),
|
| 260 |
+
offload_video_to_cpu: bool = False,
|
| 261 |
+
) -> torch.Tensor:
|
| 262 |
+
"""
|
| 263 |
+
Load video from path, convert to normalized tensor with specified preprocessing
|
| 264 |
+
|
| 265 |
+
Args:
|
| 266 |
+
video_path: Path to video file
|
| 267 |
+
image_size: Target size for square frames (height and width)
|
| 268 |
+
img_mean: Normalization mean (RGB)
|
| 269 |
+
img_std: Normalization standard deviation (RGB)
|
| 270 |
+
|
| 271 |
+
Returns:
|
| 272 |
+
torch.Tensor: Preprocessed video tensor in shape (T, C, H, W) with float16 dtype
|
| 273 |
+
"""
|
| 274 |
+
import cv2 # delay OpenCV import to avoid unnecessary dependency
|
| 275 |
+
|
| 276 |
+
# Initialize video capture
|
| 277 |
+
cap = cv2.VideoCapture(video_path)
|
| 278 |
+
if not cap.isOpened():
|
| 279 |
+
raise ValueError(f"Could not open video: {video_path}")
|
| 280 |
+
|
| 281 |
+
original_height = int(cap.get(cv2.CAP_PROP_FRAME_HEIGHT))
|
| 282 |
+
original_width = int(cap.get(cv2.CAP_PROP_FRAME_WIDTH))
|
| 283 |
+
num_frames = int(cap.get(cv2.CAP_PROP_FRAME_COUNT))
|
| 284 |
+
num_frames = num_frames if num_frames > 0 else None
|
| 285 |
+
|
| 286 |
+
frames = []
|
| 287 |
+
pbar = tqdm(desc=f"frame loading (OpenCV) [rank={RANK}]", total=num_frames)
|
| 288 |
+
while True:
|
| 289 |
+
ret, frame = cap.read()
|
| 290 |
+
if not ret:
|
| 291 |
+
break
|
| 292 |
+
|
| 293 |
+
# Convert BGR to RGB and resize
|
| 294 |
+
frame_rgb = cv2.cvtColor(frame, cv2.COLOR_BGR2RGB)
|
| 295 |
+
frame_resized = cv2.resize(
|
| 296 |
+
frame_rgb, (image_size, image_size), interpolation=cv2.INTER_CUBIC
|
| 297 |
+
)
|
| 298 |
+
frames.append(frame_resized)
|
| 299 |
+
pbar.update(1)
|
| 300 |
+
cap.release()
|
| 301 |
+
pbar.close()
|
| 302 |
+
|
| 303 |
+
# Convert to tensor
|
| 304 |
+
frames_np = np.stack(frames, axis=0).astype(np.float32) # (T, H, W, C)
|
| 305 |
+
video_tensor = torch.from_numpy(frames_np).permute(0, 3, 1, 2) # (T, C, H, W)
|
| 306 |
+
|
| 307 |
+
img_mean = torch.tensor(img_mean, dtype=torch.float16).view(1, 3, 1, 1)
|
| 308 |
+
img_std = torch.tensor(img_std, dtype=torch.float16).view(1, 3, 1, 1)
|
| 309 |
+
if not offload_video_to_cpu:
|
| 310 |
+
video_tensor = video_tensor.cuda()
|
| 311 |
+
img_mean = img_mean.cuda()
|
| 312 |
+
img_std = img_std.cuda()
|
| 313 |
+
# normalize by mean and std
|
| 314 |
+
video_tensor -= img_mean
|
| 315 |
+
video_tensor /= img_std
|
| 316 |
+
return video_tensor, original_height, original_width
|
| 317 |
+
|
| 318 |
+
|
| 319 |
+
def load_dummy_video(image_size, offload_video_to_cpu, num_frames=60):
|
| 320 |
+
"""
|
| 321 |
+
Load a dummy video with random frames for testing and compilation warmup purposes.
|
| 322 |
+
"""
|
| 323 |
+
video_height, video_width = 480, 640 # dummy original video sizes
|
| 324 |
+
images = torch.randn(num_frames, 3, image_size, image_size, dtype=torch.float16)
|
| 325 |
+
if not offload_video_to_cpu:
|
| 326 |
+
images = images.cuda()
|
| 327 |
+
return images, video_height, video_width
|
| 328 |
+
|
| 329 |
+
|
| 330 |
+
def _load_img_as_tensor(img_path, image_size):
|
| 331 |
+
"""Load and resize an image and convert it into a PyTorch tensor."""
|
| 332 |
+
img = Image.open(img_path).convert("RGB")
|
| 333 |
+
orig_width, orig_height = img.width, img.height
|
| 334 |
+
img = TF.resize(img, size=(image_size, image_size))
|
| 335 |
+
img = TF.to_tensor(img)
|
| 336 |
+
return img, orig_height, orig_width
|
| 337 |
+
|
| 338 |
+
|
| 339 |
+
class AsyncImageFrameLoader:
|
| 340 |
+
"""
|
| 341 |
+
A list of video frames to be load asynchronously without blocking session start.
|
| 342 |
+
"""
|
| 343 |
+
|
| 344 |
+
def __init__(self, img_paths, image_size, offload_video_to_cpu, img_mean, img_std):
|
| 345 |
+
self.img_paths = img_paths
|
| 346 |
+
self.image_size = image_size
|
| 347 |
+
self.offload_video_to_cpu = offload_video_to_cpu
|
| 348 |
+
self.img_mean = img_mean
|
| 349 |
+
self.img_std = img_std
|
| 350 |
+
# items in `self._images` will be loaded asynchronously
|
| 351 |
+
self.images = [None] * len(img_paths)
|
| 352 |
+
# catch and raise any exceptions in the async loading thread
|
| 353 |
+
self.exception = None
|
| 354 |
+
# video_height and video_width be filled when loading the first image
|
| 355 |
+
self.video_height = None
|
| 356 |
+
self.video_width = None
|
| 357 |
+
|
| 358 |
+
# load the first frame to fill video_height and video_width and also
|
| 359 |
+
# to cache it (since it's most likely where the user will click)
|
| 360 |
+
self.__getitem__(0)
|
| 361 |
+
|
| 362 |
+
# load the rest of frames asynchronously without blocking the session start
|
| 363 |
+
def _load_frames():
|
| 364 |
+
try:
|
| 365 |
+
for n in tqdm(
|
| 366 |
+
range(len(self.images)),
|
| 367 |
+
desc=f"frame loading (image folder) [rank={RANK}]",
|
| 368 |
+
):
|
| 369 |
+
self.__getitem__(n)
|
| 370 |
+
except Exception as e:
|
| 371 |
+
self.exception = e
|
| 372 |
+
|
| 373 |
+
self.thread = Thread(target=_load_frames, daemon=True)
|
| 374 |
+
self.thread.start()
|
| 375 |
+
|
| 376 |
+
def __getitem__(self, index):
|
| 377 |
+
if self.exception is not None:
|
| 378 |
+
raise RuntimeError("Failure in frame loading thread") from self.exception
|
| 379 |
+
|
| 380 |
+
img = self.images[index]
|
| 381 |
+
if img is not None:
|
| 382 |
+
return img
|
| 383 |
+
|
| 384 |
+
img, video_height, video_width = _load_img_as_tensor(
|
| 385 |
+
self.img_paths[index], self.image_size
|
| 386 |
+
)
|
| 387 |
+
self.video_height = video_height
|
| 388 |
+
self.video_width = video_width
|
| 389 |
+
# float16 precision should be sufficient for image tensor storage
|
| 390 |
+
img = img.to(dtype=torch.float16)
|
| 391 |
+
# normalize by mean and std
|
| 392 |
+
img -= self.img_mean
|
| 393 |
+
img /= self.img_std
|
| 394 |
+
if not self.offload_video_to_cpu:
|
| 395 |
+
img = img.cuda()
|
| 396 |
+
self.images[index] = img
|
| 397 |
+
return img
|
| 398 |
+
|
| 399 |
+
def __len__(self):
|
| 400 |
+
return len(self.images)
|
| 401 |
+
|
| 402 |
+
|
| 403 |
+
class TorchCodecDecoder:
|
| 404 |
+
"""
|
| 405 |
+
A wrapper to support GPU device and num_threads in TorchCodec decoder,
|
| 406 |
+
which are not supported by `torchcodec.decoders.SimpleVideoDecoder` yet.
|
| 407 |
+
"""
|
| 408 |
+
|
| 409 |
+
def __init__(self, source, dimension_order="NCHW", device="cpu", num_threads=1):
|
| 410 |
+
from torchcodec import _core as core
|
| 411 |
+
|
| 412 |
+
self._source = source # hold a reference to the source to prevent it from GC
|
| 413 |
+
if isinstance(source, str):
|
| 414 |
+
self._decoder = core.create_from_file(source, "exact")
|
| 415 |
+
elif isinstance(source, bytes):
|
| 416 |
+
self._decoder = core.create_from_bytes(source, "exact")
|
| 417 |
+
else:
|
| 418 |
+
raise TypeError(f"Unknown source type: {type(source)}.")
|
| 419 |
+
assert dimension_order in ("NCHW", "NHWC")
|
| 420 |
+
|
| 421 |
+
device_string = str(device)
|
| 422 |
+
core.scan_all_streams_to_update_metadata(self._decoder)
|
| 423 |
+
core.add_video_stream(
|
| 424 |
+
self._decoder,
|
| 425 |
+
dimension_order=dimension_order,
|
| 426 |
+
device=device_string,
|
| 427 |
+
num_threads=(1 if "cuda" in device_string else num_threads),
|
| 428 |
+
)
|
| 429 |
+
video_metadata = core.get_container_metadata(self._decoder)
|
| 430 |
+
best_stream_index = video_metadata.best_video_stream_index
|
| 431 |
+
assert best_stream_index is not None
|
| 432 |
+
self.metadata = video_metadata.streams[best_stream_index]
|
| 433 |
+
assert self.metadata.num_frames_from_content is not None
|
| 434 |
+
self._num_frames = self.metadata.num_frames_from_content
|
| 435 |
+
|
| 436 |
+
def __len__(self) -> int:
|
| 437 |
+
return self._num_frames
|
| 438 |
+
|
| 439 |
+
def __getitem__(self, key: int):
|
| 440 |
+
from torchcodec import _core as core
|
| 441 |
+
|
| 442 |
+
if key < 0:
|
| 443 |
+
key += self._num_frames
|
| 444 |
+
if key >= self._num_frames or key < 0:
|
| 445 |
+
raise IndexError(
|
| 446 |
+
f"Index {key} is out of bounds; length is {self._num_frames}"
|
| 447 |
+
)
|
| 448 |
+
frame_data, *_ = core.get_frame_at_index(
|
| 449 |
+
self._decoder,
|
| 450 |
+
frame_index=key,
|
| 451 |
+
)
|
| 452 |
+
return frame_data
|
| 453 |
+
|
| 454 |
+
|
| 455 |
+
class FIFOLock:
|
| 456 |
+
"""A lock that ensures FIFO ordering of lock acquisitions."""
|
| 457 |
+
|
| 458 |
+
def __init__(self):
|
| 459 |
+
self._lock = Lock()
|
| 460 |
+
self._waiters = queue.Queue()
|
| 461 |
+
self._condition = Condition()
|
| 462 |
+
|
| 463 |
+
def acquire(self):
|
| 464 |
+
ident = get_ident()
|
| 465 |
+
with self._condition:
|
| 466 |
+
self._waiters.put(ident)
|
| 467 |
+
while self._waiters.queue[0] != ident or not self._lock.acquire(
|
| 468 |
+
blocking=False
|
| 469 |
+
):
|
| 470 |
+
self._condition.wait()
|
| 471 |
+
# got the lock and it's our turn
|
| 472 |
+
|
| 473 |
+
def release(self):
|
| 474 |
+
with self._condition:
|
| 475 |
+
self._lock.release()
|
| 476 |
+
self._waiters.get()
|
| 477 |
+
self._condition.notify_all()
|
| 478 |
+
|
| 479 |
+
def __enter__(self):
|
| 480 |
+
self.acquire()
|
| 481 |
+
|
| 482 |
+
def __exit__(self, t, v, tb):
|
| 483 |
+
self.release()
|
| 484 |
+
|
| 485 |
+
|
| 486 |
+
class AsyncVideoFileLoaderWithTorchCodec:
|
| 487 |
+
"""
|
| 488 |
+
Loading frames from video files asynchronously without blocking session start.
|
| 489 |
+
|
| 490 |
+
Unlike `AsyncVideoFileLoader`, this class uses PyTorch's offical TorchCodec library
|
| 491 |
+
for video decoding, which is more efficient and supports more video formats.
|
| 492 |
+
"""
|
| 493 |
+
|
| 494 |
+
def __init__(
|
| 495 |
+
self,
|
| 496 |
+
video_path,
|
| 497 |
+
image_size,
|
| 498 |
+
offload_video_to_cpu,
|
| 499 |
+
img_mean,
|
| 500 |
+
img_std,
|
| 501 |
+
gpu_acceleration=True,
|
| 502 |
+
gpu_device=None,
|
| 503 |
+
use_rand_seek_in_loading=False,
|
| 504 |
+
):
|
| 505 |
+
# Check and possibly infer the output device (and also get its GPU id when applicable)
|
| 506 |
+
assert gpu_device is None or gpu_device.type == "cuda"
|
| 507 |
+
gpu_id = (
|
| 508 |
+
gpu_device.index
|
| 509 |
+
if gpu_device is not None and gpu_device.index is not None
|
| 510 |
+
else torch.cuda.current_device()
|
| 511 |
+
)
|
| 512 |
+
if offload_video_to_cpu:
|
| 513 |
+
out_device = torch.device("cpu")
|
| 514 |
+
else:
|
| 515 |
+
out_device = torch.device("cuda") if gpu_device is None else gpu_device
|
| 516 |
+
self.out_device = out_device
|
| 517 |
+
self.gpu_acceleration = gpu_acceleration
|
| 518 |
+
self.gpu_id = gpu_id
|
| 519 |
+
self.image_size = image_size
|
| 520 |
+
self.offload_video_to_cpu = offload_video_to_cpu
|
| 521 |
+
if not isinstance(img_mean, torch.Tensor):
|
| 522 |
+
img_mean = torch.tensor(img_mean, dtype=torch.float16)[:, None, None]
|
| 523 |
+
self.img_mean = img_mean
|
| 524 |
+
if not isinstance(img_std, torch.Tensor):
|
| 525 |
+
img_std = torch.tensor(img_std, dtype=torch.float16)[:, None, None]
|
| 526 |
+
self.img_std = img_std
|
| 527 |
+
|
| 528 |
+
if gpu_acceleration:
|
| 529 |
+
self.img_mean = self.img_mean.to(f"cuda:{self.gpu_id}")
|
| 530 |
+
self.img_std = self.img_std.to(f"cuda:{self.gpu_id}")
|
| 531 |
+
decoder_option = {"device": f"cuda:{self.gpu_id}"}
|
| 532 |
+
else:
|
| 533 |
+
self.img_mean = self.img_mean.cpu()
|
| 534 |
+
self.img_std = self.img_std.cpu()
|
| 535 |
+
decoder_option = {"num_threads": 1} # use a single thread to save memory
|
| 536 |
+
|
| 537 |
+
self.rank = int(os.environ.get("RANK", "0"))
|
| 538 |
+
self.world_size = int(os.environ.get("WORLD_SIZE", "1"))
|
| 539 |
+
self.async_reader = TorchCodecDecoder(video_path, **decoder_option)
|
| 540 |
+
|
| 541 |
+
# `num_frames_from_content` is the true number of frames in the video content
|
| 542 |
+
# from the scan operation (rather than from the metadata, which could be wrong)
|
| 543 |
+
self.num_frames = self.async_reader.metadata.num_frames_from_content
|
| 544 |
+
self.video_height = self.async_reader.metadata.height
|
| 545 |
+
self.video_width = self.async_reader.metadata.width
|
| 546 |
+
|
| 547 |
+
# items in `self._images` will be loaded asynchronously
|
| 548 |
+
self.images_loaded = [False] * self.num_frames
|
| 549 |
+
self.images = torch.zeros(
|
| 550 |
+
self.num_frames,
|
| 551 |
+
3,
|
| 552 |
+
self.image_size,
|
| 553 |
+
self.image_size,
|
| 554 |
+
dtype=torch.float16,
|
| 555 |
+
device=self.out_device,
|
| 556 |
+
)
|
| 557 |
+
# catch and raise any exceptions in the async loading thread
|
| 558 |
+
self.exception = None
|
| 559 |
+
self.use_rand_seek_in_loading = use_rand_seek_in_loading
|
| 560 |
+
self.rand_seek_idx_queue = queue.Queue()
|
| 561 |
+
# use a lock to avoid race condition between concurrent access to torchcodec
|
| 562 |
+
# libs (which are not thread-safe); the lock is replaced with a nullcontext
|
| 563 |
+
# when the video is fully loaded
|
| 564 |
+
self.torchcodec_access_lock = FIFOLock()
|
| 565 |
+
self._start_video_loading()
|
| 566 |
+
|
| 567 |
+
def _load_one_frame(self, idx):
|
| 568 |
+
frame_resized = self._transform_frame(self.async_reader[idx])
|
| 569 |
+
return frame_resized
|
| 570 |
+
|
| 571 |
+
@torch.inference_mode()
|
| 572 |
+
def _start_video_loading(self):
|
| 573 |
+
desc = f"frame loading (TorchCodec w/ {'GPU' if self.gpu_acceleration else 'CPU'}) [rank={RANK}]"
|
| 574 |
+
pbar = tqdm(desc=desc, total=self.num_frames)
|
| 575 |
+
self.num_loaded_frames = 0
|
| 576 |
+
# load the first frame synchronously to cache it before the session is opened
|
| 577 |
+
idx = self.num_loaded_frames
|
| 578 |
+
self.images[idx] = self._load_one_frame(idx)
|
| 579 |
+
self.images_loaded[idx] = True
|
| 580 |
+
self.num_loaded_frames += 1
|
| 581 |
+
pbar.update(n=1)
|
| 582 |
+
self.all_frames_loaded = self.num_loaded_frames == self.num_frames
|
| 583 |
+
|
| 584 |
+
# load the frames asynchronously without blocking the session start
|
| 585 |
+
def _load_frames():
|
| 586 |
+
finished = self.all_frames_loaded
|
| 587 |
+
chunk_size = 16
|
| 588 |
+
while not finished:
|
| 589 |
+
# asynchronously load `chunk_size` frames each time we acquire the lock
|
| 590 |
+
with self.torchcodec_access_lock, torch.inference_mode():
|
| 591 |
+
for _ in range(chunk_size):
|
| 592 |
+
try:
|
| 593 |
+
idx = self.num_loaded_frames
|
| 594 |
+
self.images[idx] = self._load_one_frame(idx)
|
| 595 |
+
self.images_loaded[idx] = True
|
| 596 |
+
self.num_loaded_frames += 1
|
| 597 |
+
pbar.update(n=1)
|
| 598 |
+
if self.num_loaded_frames >= self.num_frames:
|
| 599 |
+
finished = True
|
| 600 |
+
break
|
| 601 |
+
except Exception as e:
|
| 602 |
+
self.exception = e
|
| 603 |
+
raise
|
| 604 |
+
|
| 605 |
+
# also read the frame that is being randomly seeked to
|
| 606 |
+
while True:
|
| 607 |
+
try:
|
| 608 |
+
idx = self.rand_seek_idx_queue.get_nowait()
|
| 609 |
+
if not self.images_loaded[idx]:
|
| 610 |
+
self.images[idx] = self._load_one_frame(idx)
|
| 611 |
+
self.images_loaded[idx] = True
|
| 612 |
+
except queue.Empty:
|
| 613 |
+
break
|
| 614 |
+
except Exception as e:
|
| 615 |
+
self.exception = e
|
| 616 |
+
raise
|
| 617 |
+
|
| 618 |
+
# finished -- check whether we have loaded the total number of frames
|
| 619 |
+
if self.num_loaded_frames != self.num_frames:
|
| 620 |
+
raise RuntimeError(
|
| 621 |
+
f"There are {self.num_frames} frames in the video, but only "
|
| 622 |
+
f"{self.num_loaded_frames} frames can be loaded successfully."
|
| 623 |
+
)
|
| 624 |
+
else:
|
| 625 |
+
self.all_frames_loaded = True
|
| 626 |
+
pbar.close()
|
| 627 |
+
with self.torchcodec_access_lock:
|
| 628 |
+
import gc
|
| 629 |
+
|
| 630 |
+
# all frames have been loaded, so we can release the readers and free their memory
|
| 631 |
+
# also remove pbar and thread (which shouldn't be a part of session saving)
|
| 632 |
+
reader = self.async_reader
|
| 633 |
+
if reader is not None:
|
| 634 |
+
reader._source = None
|
| 635 |
+
self.async_reader = None
|
| 636 |
+
self.pbar = None
|
| 637 |
+
self.thread = None
|
| 638 |
+
self.rand_seek_idx_queue = None
|
| 639 |
+
gc.collect()
|
| 640 |
+
# remove the lock (replace it with nullcontext) when the video is fully loaded
|
| 641 |
+
self.torchcodec_access_lock = contextlib.nullcontext()
|
| 642 |
+
|
| 643 |
+
self.thread = Thread(target=_load_frames, daemon=True)
|
| 644 |
+
self.thread.start()
|
| 645 |
+
|
| 646 |
+
def _transform_frame(self, frame):
|
| 647 |
+
frame = frame.clone() # make a copy to avoid modifying the original frame bytes
|
| 648 |
+
frame = frame.float() # convert to float32 before interpolation
|
| 649 |
+
frame_resized = F.interpolate(
|
| 650 |
+
frame[None, :],
|
| 651 |
+
size=(self.image_size, self.image_size),
|
| 652 |
+
mode="bicubic",
|
| 653 |
+
align_corners=False,
|
| 654 |
+
)[0]
|
| 655 |
+
# float16 precision should be sufficient for image tensor storage
|
| 656 |
+
frame_resized = frame_resized.half() # uint8 -> float16
|
| 657 |
+
frame_resized /= 255
|
| 658 |
+
frame_resized -= self.img_mean
|
| 659 |
+
frame_resized /= self.img_std
|
| 660 |
+
if self.offload_video_to_cpu:
|
| 661 |
+
frame_resized = frame_resized.cpu()
|
| 662 |
+
elif frame_resized.device != self.out_device:
|
| 663 |
+
frame_resized = frame_resized.to(device=self.out_device, non_blocking=True)
|
| 664 |
+
return frame_resized
|
| 665 |
+
|
| 666 |
+
def __getitem__(self, index):
|
| 667 |
+
if self.exception is not None:
|
| 668 |
+
raise RuntimeError("Failure in frame loading thread") from self.exception
|
| 669 |
+
|
| 670 |
+
max_tries = 1200
|
| 671 |
+
for _ in range(max_tries):
|
| 672 |
+
# use a lock to avoid race condition between concurrent access to torchcodec
|
| 673 |
+
# libs (which are not thread-safe); the lock is replaced with a nullcontext
|
| 674 |
+
# when the video is fully loaded
|
| 675 |
+
with self.torchcodec_access_lock:
|
| 676 |
+
if self.images_loaded[index]:
|
| 677 |
+
return self.images[index]
|
| 678 |
+
|
| 679 |
+
if self.use_rand_seek_in_loading:
|
| 680 |
+
# async loading hasn't reached this frame yet, so we load this frame individually
|
| 681 |
+
# (it will be loaded by in _load_frames thread and added to self.images[index])
|
| 682 |
+
self.rand_seek_idx_queue.put(index)
|
| 683 |
+
|
| 684 |
+
time.sleep(0.1)
|
| 685 |
+
|
| 686 |
+
raise RuntimeError(f"Failed to load frame {index} after {max_tries} tries")
|
| 687 |
+
|
| 688 |
+
def __len__(self):
|
| 689 |
+
return len(self.images)
|
| 690 |
+
|
| 691 |
+
def __getstate__(self):
|
| 692 |
+
"""
|
| 693 |
+
Remove a few attributes during pickling, so that this async video loader can be
|
| 694 |
+
saved and loaded as a part of the model session.
|
| 695 |
+
"""
|
| 696 |
+
# wait for async video loading to finish before pickling
|
| 697 |
+
async_thread = self.thread
|
| 698 |
+
if async_thread is not None:
|
| 699 |
+
async_thread.join()
|
| 700 |
+
# release a few objects that cannot be pickled
|
| 701 |
+
reader = self.async_reader
|
| 702 |
+
if reader is not None:
|
| 703 |
+
reader._source = None
|
| 704 |
+
self.async_reader = None
|
| 705 |
+
self.pbar = None
|
| 706 |
+
self.thread = None
|
| 707 |
+
self.rand_seek_idx_queue = None
|
| 708 |
+
self.torchcodec_access_lock = contextlib.nullcontext()
|
| 709 |
+
return self.__dict__.copy()
|
之前的代码版本/这一版注意力有问题/HuatuoGPT-Vision/MedSAM3/sam3/model/maskformer_segmentation.py
ADDED
|
@@ -0,0 +1,323 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
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|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
# Copyright (c) Meta Platforms, Inc. and affiliates. All Rights Reserved
|
| 2 |
+
|
| 3 |
+
import math
|
| 4 |
+
from typing import Dict, List, Optional
|
| 5 |
+
|
| 6 |
+
import torch
|
| 7 |
+
import torch.nn as nn
|
| 8 |
+
import torch.nn.functional as F
|
| 9 |
+
import torch.utils.checkpoint as checkpoint
|
| 10 |
+
|
| 11 |
+
from .model_misc import MLP
|
| 12 |
+
|
| 13 |
+
|
| 14 |
+
class LinearPresenceHead(nn.Sequential):
|
| 15 |
+
def __init__(self, d_model):
|
| 16 |
+
# a hack to make `LinearPresenceHead` compatible with old checkpoints
|
| 17 |
+
super().__init__(nn.Identity(), nn.Identity(), nn.Linear(d_model, 1))
|
| 18 |
+
|
| 19 |
+
def forward(self, hs, prompt, prompt_mask):
|
| 20 |
+
return super().forward(hs)
|
| 21 |
+
|
| 22 |
+
|
| 23 |
+
class MaskPredictor(nn.Module):
|
| 24 |
+
def __init__(self, hidden_dim, mask_dim):
|
| 25 |
+
super().__init__()
|
| 26 |
+
self.mask_embed = MLP(hidden_dim, hidden_dim, mask_dim, 3)
|
| 27 |
+
|
| 28 |
+
def forward(self, obj_queries, pixel_embed):
|
| 29 |
+
if len(obj_queries.shape) == 3:
|
| 30 |
+
if pixel_embed.ndim == 3:
|
| 31 |
+
# batch size was omitted
|
| 32 |
+
mask_preds = torch.einsum(
|
| 33 |
+
"bqc,chw->bqhw", self.mask_embed(obj_queries), pixel_embed
|
| 34 |
+
)
|
| 35 |
+
else:
|
| 36 |
+
mask_preds = torch.einsum(
|
| 37 |
+
"bqc,bchw->bqhw", self.mask_embed(obj_queries), pixel_embed
|
| 38 |
+
)
|
| 39 |
+
else:
|
| 40 |
+
# Assumed to have aux masks
|
| 41 |
+
if pixel_embed.ndim == 3:
|
| 42 |
+
# batch size was omitted
|
| 43 |
+
mask_preds = torch.einsum(
|
| 44 |
+
"lbqc,chw->lbqhw", self.mask_embed(obj_queries), pixel_embed
|
| 45 |
+
)
|
| 46 |
+
else:
|
| 47 |
+
mask_preds = torch.einsum(
|
| 48 |
+
"lbqc,bchw->lbqhw", self.mask_embed(obj_queries), pixel_embed
|
| 49 |
+
)
|
| 50 |
+
|
| 51 |
+
return mask_preds
|
| 52 |
+
|
| 53 |
+
|
| 54 |
+
class SegmentationHead(nn.Module):
|
| 55 |
+
def __init__(
|
| 56 |
+
self,
|
| 57 |
+
hidden_dim,
|
| 58 |
+
upsampling_stages,
|
| 59 |
+
use_encoder_inputs=False,
|
| 60 |
+
aux_masks=False,
|
| 61 |
+
no_dec=False,
|
| 62 |
+
pixel_decoder=None,
|
| 63 |
+
act_ckpt=False,
|
| 64 |
+
shared_conv=False,
|
| 65 |
+
compile_mode_pixel_decoder=None,
|
| 66 |
+
):
|
| 67 |
+
super().__init__()
|
| 68 |
+
self.use_encoder_inputs = use_encoder_inputs
|
| 69 |
+
self.aux_masks = aux_masks
|
| 70 |
+
if pixel_decoder is not None:
|
| 71 |
+
self.pixel_decoder = pixel_decoder
|
| 72 |
+
else:
|
| 73 |
+
self.pixel_decoder = PixelDecoder(
|
| 74 |
+
hidden_dim,
|
| 75 |
+
upsampling_stages,
|
| 76 |
+
shared_conv=shared_conv,
|
| 77 |
+
compile_mode=compile_mode_pixel_decoder,
|
| 78 |
+
)
|
| 79 |
+
self.no_dec = no_dec
|
| 80 |
+
if no_dec:
|
| 81 |
+
self.mask_predictor = nn.Conv2d(
|
| 82 |
+
hidden_dim, 1, kernel_size=3, stride=1, padding=1
|
| 83 |
+
)
|
| 84 |
+
else:
|
| 85 |
+
self.mask_predictor = MaskPredictor(hidden_dim, mask_dim=hidden_dim)
|
| 86 |
+
|
| 87 |
+
self.act_ckpt = act_ckpt
|
| 88 |
+
|
| 89 |
+
# used to update the output dictionary
|
| 90 |
+
self.instance_keys = ["pred_masks"]
|
| 91 |
+
|
| 92 |
+
@property
|
| 93 |
+
def device(self):
|
| 94 |
+
self._device = getattr(self, "_device", None) or next(self.parameters()).device
|
| 95 |
+
return self._device
|
| 96 |
+
|
| 97 |
+
def to(self, *args, **kwargs):
|
| 98 |
+
# clear cached _device in case the model is moved to a different device
|
| 99 |
+
self._device = None
|
| 100 |
+
return super().to(*args, **kwargs)
|
| 101 |
+
|
| 102 |
+
def _embed_pixels(
|
| 103 |
+
self,
|
| 104 |
+
backbone_feats: List[torch.Tensor],
|
| 105 |
+
image_ids,
|
| 106 |
+
encoder_hidden_states,
|
| 107 |
+
) -> torch.Tensor:
|
| 108 |
+
feature_device = backbone_feats[0].device # features could be on CPU
|
| 109 |
+
model_device = self.device
|
| 110 |
+
image_ids_ = image_ids.to(feature_device)
|
| 111 |
+
if self.use_encoder_inputs:
|
| 112 |
+
if backbone_feats[0].shape[0] > 1:
|
| 113 |
+
# For bs > 1, we construct the per query backbone features
|
| 114 |
+
backbone_visual_feats = []
|
| 115 |
+
for feat in backbone_feats:
|
| 116 |
+
# Copy the img features per query (pixel decoder won't share img feats)
|
| 117 |
+
backbone_visual_feats.append(feat[image_ids_, ...].to(model_device))
|
| 118 |
+
else:
|
| 119 |
+
# Bs=1, we rely on broadcasting for query-based processing
|
| 120 |
+
backbone_visual_feats = [bb_feat.clone() for bb_feat in backbone_feats]
|
| 121 |
+
# Extract visual embeddings
|
| 122 |
+
encoder_hidden_states = encoder_hidden_states.permute(1, 2, 0)
|
| 123 |
+
spatial_dim = math.prod(backbone_feats[-1].shape[-2:])
|
| 124 |
+
encoder_visual_embed = encoder_hidden_states[..., :spatial_dim].reshape(
|
| 125 |
+
-1, *backbone_feats[-1].shape[1:]
|
| 126 |
+
)
|
| 127 |
+
|
| 128 |
+
backbone_visual_feats[-1] = encoder_visual_embed
|
| 129 |
+
if self.act_ckpt:
|
| 130 |
+
pixel_embed = checkpoint.checkpoint(
|
| 131 |
+
self.pixel_decoder, backbone_visual_feats, use_reentrant=False
|
| 132 |
+
)
|
| 133 |
+
else:
|
| 134 |
+
pixel_embed = self.pixel_decoder(backbone_visual_feats)
|
| 135 |
+
else:
|
| 136 |
+
backbone_feats = [x.to(model_device) for x in backbone_feats]
|
| 137 |
+
pixel_embed = self.pixel_decoder(backbone_feats)
|
| 138 |
+
if pixel_embed.shape[0] == 1:
|
| 139 |
+
# For batch_size=1 training, we can avoid the indexing to save memory
|
| 140 |
+
pixel_embed = pixel_embed.squeeze(0)
|
| 141 |
+
else:
|
| 142 |
+
pixel_embed = pixel_embed[image_ids, ...]
|
| 143 |
+
return pixel_embed
|
| 144 |
+
|
| 145 |
+
def forward(
|
| 146 |
+
self,
|
| 147 |
+
backbone_feats: List[torch.Tensor],
|
| 148 |
+
obj_queries: torch.Tensor,
|
| 149 |
+
image_ids,
|
| 150 |
+
encoder_hidden_states: Optional[torch.Tensor] = None,
|
| 151 |
+
**kwargs,
|
| 152 |
+
) -> Dict[str, torch.Tensor]:
|
| 153 |
+
if self.use_encoder_inputs:
|
| 154 |
+
assert encoder_hidden_states is not None
|
| 155 |
+
|
| 156 |
+
pixel_embed = self._embed_pixels(
|
| 157 |
+
backbone_feats=backbone_feats,
|
| 158 |
+
image_ids=image_ids,
|
| 159 |
+
encoder_hidden_states=encoder_hidden_states,
|
| 160 |
+
)
|
| 161 |
+
|
| 162 |
+
if self.no_dec:
|
| 163 |
+
mask_pred = self.mask_predictor(pixel_embed)
|
| 164 |
+
elif self.aux_masks:
|
| 165 |
+
mask_pred = self.mask_predictor(obj_queries, pixel_embed)
|
| 166 |
+
else:
|
| 167 |
+
mask_pred = self.mask_predictor(obj_queries[-1], pixel_embed)
|
| 168 |
+
|
| 169 |
+
return {"pred_masks": mask_pred}
|
| 170 |
+
|
| 171 |
+
|
| 172 |
+
class PixelDecoder(nn.Module):
|
| 173 |
+
def __init__(
|
| 174 |
+
self,
|
| 175 |
+
hidden_dim,
|
| 176 |
+
num_upsampling_stages,
|
| 177 |
+
interpolation_mode="nearest",
|
| 178 |
+
shared_conv=False,
|
| 179 |
+
compile_mode=None,
|
| 180 |
+
):
|
| 181 |
+
super().__init__()
|
| 182 |
+
self.hidden_dim = hidden_dim
|
| 183 |
+
self.num_upsampling_stages = num_upsampling_stages
|
| 184 |
+
self.interpolation_mode = interpolation_mode
|
| 185 |
+
conv_layers = []
|
| 186 |
+
norms = []
|
| 187 |
+
num_convs = 1 if shared_conv else num_upsampling_stages
|
| 188 |
+
for _ in range(num_convs):
|
| 189 |
+
conv_layers.append(nn.Conv2d(self.hidden_dim, self.hidden_dim, 3, 1, 1))
|
| 190 |
+
norms.append(nn.GroupNorm(8, self.hidden_dim))
|
| 191 |
+
|
| 192 |
+
self.conv_layers = nn.ModuleList(conv_layers)
|
| 193 |
+
self.norms = nn.ModuleList(norms)
|
| 194 |
+
self.shared_conv = shared_conv
|
| 195 |
+
self.out_dim = self.conv_layers[-1].out_channels
|
| 196 |
+
if compile_mode is not None:
|
| 197 |
+
self.forward = torch.compile(
|
| 198 |
+
self.forward, mode=compile_mode, dynamic=True, fullgraph=True
|
| 199 |
+
)
|
| 200 |
+
# Needed to make checkpointing happy. But we don't know if the module is checkpointed, so we disable it by default.
|
| 201 |
+
torch._dynamo.config.optimize_ddp = False
|
| 202 |
+
|
| 203 |
+
def forward(self, backbone_feats: List[torch.Tensor]):
|
| 204 |
+
# Assumes backbone features are already projected (C == hidden dim)
|
| 205 |
+
|
| 206 |
+
prev_fpn = backbone_feats[-1]
|
| 207 |
+
fpn_feats = backbone_feats[:-1]
|
| 208 |
+
for layer_idx, bb_feat in enumerate(fpn_feats[::-1]):
|
| 209 |
+
curr_fpn = bb_feat
|
| 210 |
+
prev_fpn = curr_fpn + F.interpolate(
|
| 211 |
+
prev_fpn, size=curr_fpn.shape[-2:], mode=self.interpolation_mode
|
| 212 |
+
)
|
| 213 |
+
if self.shared_conv:
|
| 214 |
+
# only one conv layer
|
| 215 |
+
layer_idx = 0
|
| 216 |
+
prev_fpn = self.conv_layers[layer_idx](prev_fpn)
|
| 217 |
+
prev_fpn = F.relu(self.norms[layer_idx](prev_fpn))
|
| 218 |
+
|
| 219 |
+
return prev_fpn
|
| 220 |
+
|
| 221 |
+
|
| 222 |
+
class UniversalSegmentationHead(SegmentationHead):
|
| 223 |
+
"""This module handles semantic+instance segmentation"""
|
| 224 |
+
|
| 225 |
+
def __init__(
|
| 226 |
+
self,
|
| 227 |
+
hidden_dim,
|
| 228 |
+
upsampling_stages,
|
| 229 |
+
pixel_decoder,
|
| 230 |
+
aux_masks=False,
|
| 231 |
+
no_dec=False,
|
| 232 |
+
act_ckpt=False,
|
| 233 |
+
presence_head: bool = False,
|
| 234 |
+
dot_product_scorer=None,
|
| 235 |
+
cross_attend_prompt=None,
|
| 236 |
+
):
|
| 237 |
+
super().__init__(
|
| 238 |
+
hidden_dim=hidden_dim,
|
| 239 |
+
upsampling_stages=upsampling_stages,
|
| 240 |
+
use_encoder_inputs=True,
|
| 241 |
+
aux_masks=aux_masks,
|
| 242 |
+
no_dec=no_dec,
|
| 243 |
+
pixel_decoder=pixel_decoder,
|
| 244 |
+
act_ckpt=act_ckpt,
|
| 245 |
+
)
|
| 246 |
+
self.d_model = hidden_dim
|
| 247 |
+
|
| 248 |
+
if dot_product_scorer is not None:
|
| 249 |
+
assert presence_head, "Specifying a dot product scorer without a presence head is likely a mistake"
|
| 250 |
+
|
| 251 |
+
self.presence_head = None
|
| 252 |
+
if presence_head:
|
| 253 |
+
self.presence_head = (
|
| 254 |
+
dot_product_scorer
|
| 255 |
+
if dot_product_scorer is not None
|
| 256 |
+
else LinearPresenceHead(self.d_model)
|
| 257 |
+
)
|
| 258 |
+
|
| 259 |
+
self.cross_attend_prompt = cross_attend_prompt
|
| 260 |
+
if self.cross_attend_prompt is not None:
|
| 261 |
+
self.cross_attn_norm = nn.LayerNorm(self.d_model)
|
| 262 |
+
|
| 263 |
+
self.semantic_seg_head = nn.Conv2d(self.pixel_decoder.out_dim, 1, kernel_size=1)
|
| 264 |
+
self.instance_seg_head = nn.Conv2d(
|
| 265 |
+
self.pixel_decoder.out_dim, self.d_model, kernel_size=1
|
| 266 |
+
)
|
| 267 |
+
|
| 268 |
+
def forward(
|
| 269 |
+
self,
|
| 270 |
+
backbone_feats: List[torch.Tensor],
|
| 271 |
+
obj_queries: torch.Tensor,
|
| 272 |
+
image_ids,
|
| 273 |
+
encoder_hidden_states: Optional[torch.Tensor] = None,
|
| 274 |
+
prompt: Optional[torch.Tensor] = None,
|
| 275 |
+
prompt_mask: Optional[torch.Tensor] = None,
|
| 276 |
+
**kwargs,
|
| 277 |
+
) -> Dict[str, Optional[torch.Tensor]]:
|
| 278 |
+
assert encoder_hidden_states is not None
|
| 279 |
+
bs = encoder_hidden_states.shape[1]
|
| 280 |
+
|
| 281 |
+
if self.cross_attend_prompt is not None:
|
| 282 |
+
tgt2 = self.cross_attn_norm(encoder_hidden_states)
|
| 283 |
+
tgt2 = self.cross_attend_prompt(
|
| 284 |
+
query=tgt2,
|
| 285 |
+
key=prompt,
|
| 286 |
+
value=prompt,
|
| 287 |
+
key_padding_mask=prompt_mask,
|
| 288 |
+
)[0]
|
| 289 |
+
encoder_hidden_states = tgt2 + encoder_hidden_states
|
| 290 |
+
|
| 291 |
+
presence_logit = None
|
| 292 |
+
if self.presence_head is not None:
|
| 293 |
+
pooled_enc = encoder_hidden_states.mean(0)
|
| 294 |
+
presence_logit = (
|
| 295 |
+
self.presence_head(
|
| 296 |
+
pooled_enc.view(1, bs, 1, self.d_model),
|
| 297 |
+
prompt=prompt,
|
| 298 |
+
prompt_mask=prompt_mask,
|
| 299 |
+
)
|
| 300 |
+
.squeeze(0)
|
| 301 |
+
.squeeze(1)
|
| 302 |
+
)
|
| 303 |
+
|
| 304 |
+
pixel_embed = self._embed_pixels(
|
| 305 |
+
backbone_feats=backbone_feats,
|
| 306 |
+
image_ids=image_ids,
|
| 307 |
+
encoder_hidden_states=encoder_hidden_states,
|
| 308 |
+
)
|
| 309 |
+
|
| 310 |
+
instance_embeds = self.instance_seg_head(pixel_embed)
|
| 311 |
+
|
| 312 |
+
if self.no_dec:
|
| 313 |
+
mask_pred = self.mask_predictor(instance_embeds)
|
| 314 |
+
elif self.aux_masks:
|
| 315 |
+
mask_pred = self.mask_predictor(obj_queries, instance_embeds)
|
| 316 |
+
else:
|
| 317 |
+
mask_pred = self.mask_predictor(obj_queries[-1], instance_embeds)
|
| 318 |
+
|
| 319 |
+
return {
|
| 320 |
+
"pred_masks": mask_pred,
|
| 321 |
+
"semantic_seg": self.semantic_seg_head(pixel_embed),
|
| 322 |
+
"presence_logit": presence_logit,
|
| 323 |
+
}
|
之前的代码版本/这一版注意力有问题/HuatuoGPT-Vision/MedSAM3/sam3/model/memory.py
ADDED
|
@@ -0,0 +1,201 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
# Copyright (c) Meta Platforms, Inc. and affiliates. All Rights Reserved
|
| 2 |
+
|
| 3 |
+
import math
|
| 4 |
+
from typing import Tuple
|
| 5 |
+
|
| 6 |
+
import torch
|
| 7 |
+
import torch.nn as nn
|
| 8 |
+
import torch.nn.functional as F
|
| 9 |
+
|
| 10 |
+
try:
|
| 11 |
+
from timm.layers import DropPath
|
| 12 |
+
except ModuleNotFoundError:
|
| 13 |
+
# compatibility for older timm versions
|
| 14 |
+
from timm.models.layers import DropPath
|
| 15 |
+
|
| 16 |
+
from .model_misc import get_clones, LayerNorm2d
|
| 17 |
+
|
| 18 |
+
|
| 19 |
+
class SimpleMaskDownSampler(nn.Module):
|
| 20 |
+
"""
|
| 21 |
+
Progressively downsample a mask by total_stride, each time by stride.
|
| 22 |
+
Note that LayerNorm is applied per *token*, like in ViT.
|
| 23 |
+
|
| 24 |
+
With each downsample (by a factor stride**2), channel capacity increases by the same factor.
|
| 25 |
+
In the end, we linearly project to embed_dim channels.
|
| 26 |
+
"""
|
| 27 |
+
|
| 28 |
+
def __init__(
|
| 29 |
+
self,
|
| 30 |
+
embed_dim=256,
|
| 31 |
+
kernel_size=4,
|
| 32 |
+
stride=4,
|
| 33 |
+
padding=0,
|
| 34 |
+
total_stride=16,
|
| 35 |
+
activation=nn.GELU,
|
| 36 |
+
# Option to interpolate the input mask first before downsampling using convs. In that case, the total_stride is assumed to be after interpolation.
|
| 37 |
+
# If set to input resolution or None, we don't interpolate. We default to None to be safe (for older configs or if not explicitly set)
|
| 38 |
+
interpol_size=None,
|
| 39 |
+
):
|
| 40 |
+
super().__init__()
|
| 41 |
+
num_layers = int(math.log2(total_stride) // math.log2(stride))
|
| 42 |
+
assert stride**num_layers == total_stride
|
| 43 |
+
self.encoder = nn.Sequential()
|
| 44 |
+
mask_in_chans, mask_out_chans = 1, 1
|
| 45 |
+
for _ in range(num_layers):
|
| 46 |
+
mask_out_chans = mask_in_chans * (stride**2)
|
| 47 |
+
self.encoder.append(
|
| 48 |
+
nn.Conv2d(
|
| 49 |
+
mask_in_chans,
|
| 50 |
+
mask_out_chans,
|
| 51 |
+
kernel_size=kernel_size,
|
| 52 |
+
stride=stride,
|
| 53 |
+
padding=padding,
|
| 54 |
+
)
|
| 55 |
+
)
|
| 56 |
+
self.encoder.append(LayerNorm2d(mask_out_chans))
|
| 57 |
+
self.encoder.append(activation())
|
| 58 |
+
mask_in_chans = mask_out_chans
|
| 59 |
+
|
| 60 |
+
self.encoder.append(nn.Conv2d(mask_out_chans, embed_dim, kernel_size=1))
|
| 61 |
+
self.interpol_size = interpol_size
|
| 62 |
+
if self.interpol_size is not None:
|
| 63 |
+
assert isinstance(
|
| 64 |
+
self.interpol_size, (list, tuple)
|
| 65 |
+
), f"Unsupported type {type(self.interpol_size)}. Should be a list or tuple."
|
| 66 |
+
self.interpol_size = list(interpol_size)
|
| 67 |
+
assert len(self.interpol_size) == 2
|
| 68 |
+
|
| 69 |
+
def forward(self, x: torch.Tensor):
|
| 70 |
+
if self.interpol_size is not None and self.interpol_size != list(x.shape[-2:]):
|
| 71 |
+
x = F.interpolate(
|
| 72 |
+
x.float(),
|
| 73 |
+
size=self.interpol_size,
|
| 74 |
+
align_corners=False,
|
| 75 |
+
mode="bilinear",
|
| 76 |
+
antialias=True,
|
| 77 |
+
)
|
| 78 |
+
return self.encoder(x)
|
| 79 |
+
|
| 80 |
+
|
| 81 |
+
# Lightly adapted from ConvNext (https://github.com/facebookresearch/ConvNeXt)
|
| 82 |
+
class CXBlock(nn.Module):
|
| 83 |
+
r"""ConvNeXt Block. There are two equivalent implementations:
|
| 84 |
+
(1) DwConv -> LayerNorm (channels_first) -> 1x1 Conv -> GELU -> 1x1 Conv; all in (N, C, H, W)
|
| 85 |
+
(2) DwConv -> Permute to (N, H, W, C); LayerNorm (channels_last) -> Linear -> GELU -> Linear; Permute back
|
| 86 |
+
We use (2) as we find it slightly faster in PyTorch
|
| 87 |
+
|
| 88 |
+
Args:
|
| 89 |
+
dim (int): Number of input channels.
|
| 90 |
+
drop_path (float): Stochastic depth rate. Default: 0.0
|
| 91 |
+
layer_scale_init_value (float): Init value for Layer Scale. Default: 1e-6.
|
| 92 |
+
"""
|
| 93 |
+
|
| 94 |
+
def __init__(
|
| 95 |
+
self,
|
| 96 |
+
dim,
|
| 97 |
+
kernel_size=7,
|
| 98 |
+
padding=3,
|
| 99 |
+
drop_path=0.0,
|
| 100 |
+
layer_scale_init_value=1e-6,
|
| 101 |
+
use_dwconv=True,
|
| 102 |
+
):
|
| 103 |
+
super().__init__()
|
| 104 |
+
self.dwconv = nn.Conv2d(
|
| 105 |
+
dim,
|
| 106 |
+
dim,
|
| 107 |
+
kernel_size=kernel_size,
|
| 108 |
+
padding=padding,
|
| 109 |
+
groups=dim if use_dwconv else 1,
|
| 110 |
+
) # depthwise conv
|
| 111 |
+
self.norm = LayerNorm2d(dim, eps=1e-6)
|
| 112 |
+
self.pwconv1 = nn.Linear(
|
| 113 |
+
dim, 4 * dim
|
| 114 |
+
) # pointwise/1x1 convs, implemented with linear layers
|
| 115 |
+
self.act = nn.GELU()
|
| 116 |
+
self.pwconv2 = nn.Linear(4 * dim, dim)
|
| 117 |
+
self.gamma = (
|
| 118 |
+
nn.Parameter(layer_scale_init_value * torch.ones((dim)), requires_grad=True)
|
| 119 |
+
if layer_scale_init_value > 0
|
| 120 |
+
else None
|
| 121 |
+
)
|
| 122 |
+
self.drop_path = DropPath(drop_path) if drop_path > 0.0 else nn.Identity()
|
| 123 |
+
|
| 124 |
+
def forward(self, x):
|
| 125 |
+
input = x
|
| 126 |
+
x = self.dwconv(x)
|
| 127 |
+
x = self.norm(x)
|
| 128 |
+
x = x.permute(0, 2, 3, 1) # (N, C, H, W) -> (N, H, W, C)
|
| 129 |
+
x = self.pwconv1(x)
|
| 130 |
+
x = self.act(x)
|
| 131 |
+
x = self.pwconv2(x)
|
| 132 |
+
if self.gamma is not None:
|
| 133 |
+
x = self.gamma * x
|
| 134 |
+
x = x.permute(0, 3, 1, 2) # (N, H, W, C) -> (N, C, H, W)
|
| 135 |
+
|
| 136 |
+
x = input + self.drop_path(x)
|
| 137 |
+
return x
|
| 138 |
+
|
| 139 |
+
|
| 140 |
+
class SimpleFuser(nn.Module):
|
| 141 |
+
def __init__(self, layer, num_layers, dim=None, input_projection=False):
|
| 142 |
+
super().__init__()
|
| 143 |
+
self.proj = nn.Identity()
|
| 144 |
+
self.layers = get_clones(layer, num_layers)
|
| 145 |
+
|
| 146 |
+
if input_projection:
|
| 147 |
+
assert dim is not None
|
| 148 |
+
self.proj = nn.Conv2d(dim, dim, kernel_size=1)
|
| 149 |
+
|
| 150 |
+
def forward(self, x):
|
| 151 |
+
# normally x: (N, C, H, W)
|
| 152 |
+
x = self.proj(x)
|
| 153 |
+
for layer in self.layers:
|
| 154 |
+
x = layer(x)
|
| 155 |
+
return x
|
| 156 |
+
|
| 157 |
+
|
| 158 |
+
class SimpleMaskEncoder(nn.Module):
|
| 159 |
+
def __init__(
|
| 160 |
+
self,
|
| 161 |
+
out_dim,
|
| 162 |
+
mask_downsampler,
|
| 163 |
+
fuser,
|
| 164 |
+
position_encoding,
|
| 165 |
+
in_dim=256, # in_dim of pix_feats
|
| 166 |
+
):
|
| 167 |
+
super().__init__()
|
| 168 |
+
|
| 169 |
+
self.mask_downsampler = mask_downsampler
|
| 170 |
+
|
| 171 |
+
self.pix_feat_proj = nn.Conv2d(in_dim, in_dim, kernel_size=1)
|
| 172 |
+
self.fuser = fuser
|
| 173 |
+
self.position_encoding = position_encoding
|
| 174 |
+
self.out_proj = nn.Identity()
|
| 175 |
+
if out_dim != in_dim:
|
| 176 |
+
self.out_proj = nn.Conv2d(in_dim, out_dim, kernel_size=1)
|
| 177 |
+
|
| 178 |
+
def forward(
|
| 179 |
+
self,
|
| 180 |
+
pix_feat: torch.Tensor,
|
| 181 |
+
masks: torch.Tensor,
|
| 182 |
+
skip_mask_sigmoid: bool = False,
|
| 183 |
+
) -> Tuple[torch.Tensor, torch.Tensor]:
|
| 184 |
+
## Process masks
|
| 185 |
+
# sigmoid, so that less domain shift from gt masks which are bool
|
| 186 |
+
if not skip_mask_sigmoid:
|
| 187 |
+
masks = F.sigmoid(masks)
|
| 188 |
+
masks = self.mask_downsampler(masks)
|
| 189 |
+
|
| 190 |
+
## Fuse pix_feats and downsampled masks
|
| 191 |
+
# in case the visual features are on CPU, cast them to CUDA
|
| 192 |
+
pix_feat = pix_feat.to(masks.device)
|
| 193 |
+
|
| 194 |
+
x = self.pix_feat_proj(pix_feat)
|
| 195 |
+
x = x + masks
|
| 196 |
+
x = self.fuser(x)
|
| 197 |
+
x = self.out_proj(x)
|
| 198 |
+
|
| 199 |
+
pos = self.position_encoding(x).to(x.dtype)
|
| 200 |
+
|
| 201 |
+
return {"vision_features": x, "vision_pos_enc": [pos]}
|
之前的代码版本/这一版注意力有问题/HuatuoGPT-Vision/MedSAM3/sam3/model/necks.py
ADDED
|
@@ -0,0 +1,125 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
# Copyright (c) Meta Platforms, Inc. and affiliates. All Rights Reserved
|
| 2 |
+
|
| 3 |
+
"""Necks are the interface between a vision backbone and the rest of the detection model"""
|
| 4 |
+
|
| 5 |
+
from copy import deepcopy
|
| 6 |
+
from typing import List, Optional, Tuple
|
| 7 |
+
|
| 8 |
+
import torch
|
| 9 |
+
|
| 10 |
+
import torch.nn as nn
|
| 11 |
+
|
| 12 |
+
|
| 13 |
+
class Sam3DualViTDetNeck(nn.Module):
|
| 14 |
+
def __init__(
|
| 15 |
+
self,
|
| 16 |
+
trunk: nn.Module,
|
| 17 |
+
position_encoding: nn.Module,
|
| 18 |
+
d_model: int,
|
| 19 |
+
scale_factors=(4.0, 2.0, 1.0, 0.5),
|
| 20 |
+
add_sam2_neck: bool = False,
|
| 21 |
+
):
|
| 22 |
+
"""
|
| 23 |
+
SimpleFPN neck a la ViTDet
|
| 24 |
+
(From detectron2, very lightly adapted)
|
| 25 |
+
It supports a "dual neck" setting, where we have two identical necks (for SAM3 and SAM2), with different weights
|
| 26 |
+
|
| 27 |
+
:param trunk: the backbone
|
| 28 |
+
:param position_encoding: the positional encoding to use
|
| 29 |
+
:param d_model: the dimension of the model
|
| 30 |
+
"""
|
| 31 |
+
super().__init__()
|
| 32 |
+
self.trunk = trunk
|
| 33 |
+
self.position_encoding = position_encoding
|
| 34 |
+
self.convs = nn.ModuleList()
|
| 35 |
+
|
| 36 |
+
self.scale_factors = scale_factors
|
| 37 |
+
use_bias = True
|
| 38 |
+
dim: int = self.trunk.channel_list[-1]
|
| 39 |
+
|
| 40 |
+
for _, scale in enumerate(scale_factors):
|
| 41 |
+
current = nn.Sequential()
|
| 42 |
+
|
| 43 |
+
if scale == 4.0:
|
| 44 |
+
current.add_module(
|
| 45 |
+
"dconv_2x2_0",
|
| 46 |
+
nn.ConvTranspose2d(dim, dim // 2, kernel_size=2, stride=2),
|
| 47 |
+
)
|
| 48 |
+
current.add_module(
|
| 49 |
+
"gelu",
|
| 50 |
+
nn.GELU(),
|
| 51 |
+
)
|
| 52 |
+
current.add_module(
|
| 53 |
+
"dconv_2x2_1",
|
| 54 |
+
nn.ConvTranspose2d(dim // 2, dim // 4, kernel_size=2, stride=2),
|
| 55 |
+
)
|
| 56 |
+
out_dim = dim // 4
|
| 57 |
+
elif scale == 2.0:
|
| 58 |
+
current.add_module(
|
| 59 |
+
"dconv_2x2",
|
| 60 |
+
nn.ConvTranspose2d(dim, dim // 2, kernel_size=2, stride=2),
|
| 61 |
+
)
|
| 62 |
+
out_dim = dim // 2
|
| 63 |
+
elif scale == 1.0:
|
| 64 |
+
out_dim = dim
|
| 65 |
+
elif scale == 0.5:
|
| 66 |
+
current.add_module(
|
| 67 |
+
"maxpool_2x2",
|
| 68 |
+
nn.MaxPool2d(kernel_size=2, stride=2),
|
| 69 |
+
)
|
| 70 |
+
out_dim = dim
|
| 71 |
+
else:
|
| 72 |
+
raise NotImplementedError(f"scale_factor={scale} is not supported yet.")
|
| 73 |
+
|
| 74 |
+
current.add_module(
|
| 75 |
+
"conv_1x1",
|
| 76 |
+
nn.Conv2d(
|
| 77 |
+
in_channels=out_dim,
|
| 78 |
+
out_channels=d_model,
|
| 79 |
+
kernel_size=1,
|
| 80 |
+
bias=use_bias,
|
| 81 |
+
),
|
| 82 |
+
)
|
| 83 |
+
current.add_module(
|
| 84 |
+
"conv_3x3",
|
| 85 |
+
nn.Conv2d(
|
| 86 |
+
in_channels=d_model,
|
| 87 |
+
out_channels=d_model,
|
| 88 |
+
kernel_size=3,
|
| 89 |
+
padding=1,
|
| 90 |
+
bias=use_bias,
|
| 91 |
+
),
|
| 92 |
+
)
|
| 93 |
+
self.convs.append(current)
|
| 94 |
+
|
| 95 |
+
self.sam2_convs = None
|
| 96 |
+
if add_sam2_neck:
|
| 97 |
+
# Assumes sam2 neck is just a clone of the original neck
|
| 98 |
+
self.sam2_convs = deepcopy(self.convs)
|
| 99 |
+
|
| 100 |
+
def forward(
|
| 101 |
+
self, tensor_list: List[torch.Tensor]
|
| 102 |
+
) -> Tuple[
|
| 103 |
+
List[torch.Tensor],
|
| 104 |
+
List[torch.Tensor],
|
| 105 |
+
Optional[List[torch.Tensor]],
|
| 106 |
+
Optional[List[torch.Tensor]],
|
| 107 |
+
]:
|
| 108 |
+
xs = self.trunk(tensor_list)
|
| 109 |
+
sam3_out, sam3_pos = [], []
|
| 110 |
+
sam2_out, sam2_pos = None, None
|
| 111 |
+
if self.sam2_convs is not None:
|
| 112 |
+
sam2_out, sam2_pos = [], []
|
| 113 |
+
x = xs[-1] # simpleFPN
|
| 114 |
+
for i in range(len(self.convs)):
|
| 115 |
+
sam3_x_out = self.convs[i](x)
|
| 116 |
+
sam3_pos_out = self.position_encoding(sam3_x_out).to(sam3_x_out.dtype)
|
| 117 |
+
sam3_out.append(sam3_x_out)
|
| 118 |
+
sam3_pos.append(sam3_pos_out)
|
| 119 |
+
|
| 120 |
+
if self.sam2_convs is not None:
|
| 121 |
+
sam2_x_out = self.sam2_convs[i](x)
|
| 122 |
+
sam2_pos_out = self.position_encoding(sam2_x_out).to(sam2_x_out.dtype)
|
| 123 |
+
sam2_out.append(sam2_x_out)
|
| 124 |
+
sam2_pos.append(sam2_pos_out)
|
| 125 |
+
return sam3_out, sam3_pos, sam2_out, sam2_pos
|
之前的代码版本/这一版注意力有问题/HuatuoGPT-Vision/MedSAM3/sam3/model/sam3_image.py
ADDED
|
@@ -0,0 +1,883 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
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|
+
from typing import Dict, List, Optional, Tuple
|
| 6 |
+
|
| 7 |
+
import numpy as np
|
| 8 |
+
import torch
|
| 9 |
+
|
| 10 |
+
from sam3.model.model_misc import SAM3Output
|
| 11 |
+
|
| 12 |
+
from sam3.model.sam1_task_predictor import SAM3InteractiveImagePredictor
|
| 13 |
+
from sam3.model.vl_combiner import SAM3VLBackbone
|
| 14 |
+
from sam3.perflib.nms import nms_masks
|
| 15 |
+
|
| 16 |
+
from sam3.train.data.collator import BatchedDatapoint
|
| 17 |
+
|
| 18 |
+
from .act_ckpt_utils import activation_ckpt_wrapper
|
| 19 |
+
|
| 20 |
+
from .box_ops import box_cxcywh_to_xyxy
|
| 21 |
+
|
| 22 |
+
from .geometry_encoders import Prompt
|
| 23 |
+
from .model_misc import inverse_sigmoid
|
| 24 |
+
|
| 25 |
+
|
| 26 |
+
def _update_out(out, out_name, out_value, auxiliary=True, update_aux=True):
|
| 27 |
+
out[out_name] = out_value[-1] if auxiliary else out_value
|
| 28 |
+
if auxiliary and update_aux:
|
| 29 |
+
if "aux_outputs" not in out:
|
| 30 |
+
out["aux_outputs"] = [{} for _ in range(len(out_value) - 1)]
|
| 31 |
+
assert len(out["aux_outputs"]) == len(out_value) - 1
|
| 32 |
+
for aux_output, aux_value in zip(out["aux_outputs"], out_value[:-1]):
|
| 33 |
+
aux_output[out_name] = aux_value
|
| 34 |
+
|
| 35 |
+
|
| 36 |
+
class Sam3Image(torch.nn.Module):
|
| 37 |
+
TEXT_ID_FOR_TEXT = 0
|
| 38 |
+
TEXT_ID_FOR_VISUAL = 1
|
| 39 |
+
TEXT_ID_FOR_GEOMETRIC = 2
|
| 40 |
+
|
| 41 |
+
def __init__(
|
| 42 |
+
self,
|
| 43 |
+
backbone: SAM3VLBackbone,
|
| 44 |
+
transformer,
|
| 45 |
+
input_geometry_encoder,
|
| 46 |
+
segmentation_head=None,
|
| 47 |
+
num_feature_levels=1,
|
| 48 |
+
o2m_mask_predict=True,
|
| 49 |
+
dot_prod_scoring=None,
|
| 50 |
+
use_instance_query: bool = True,
|
| 51 |
+
multimask_output: bool = True,
|
| 52 |
+
use_act_checkpoint_seg_head: bool = True,
|
| 53 |
+
interactivity_in_encoder: bool = True,
|
| 54 |
+
matcher=None,
|
| 55 |
+
use_dot_prod_scoring=True,
|
| 56 |
+
supervise_joint_box_scores: bool = False, # only relevant if using presence token/score
|
| 57 |
+
detach_presence_in_joint_score: bool = False, # only relevant if using presence token/score
|
| 58 |
+
separate_scorer_for_instance: bool = False,
|
| 59 |
+
num_interactive_steps_val: int = 0,
|
| 60 |
+
inst_interactive_predictor: SAM3InteractiveImagePredictor = None,
|
| 61 |
+
**kwargs,
|
| 62 |
+
):
|
| 63 |
+
super().__init__()
|
| 64 |
+
self.backbone = backbone
|
| 65 |
+
self.geometry_encoder = input_geometry_encoder
|
| 66 |
+
self.transformer = transformer
|
| 67 |
+
self.hidden_dim = transformer.d_model
|
| 68 |
+
self.num_feature_levels = num_feature_levels
|
| 69 |
+
self.segmentation_head = segmentation_head
|
| 70 |
+
|
| 71 |
+
self.o2m_mask_predict = o2m_mask_predict
|
| 72 |
+
|
| 73 |
+
self.dot_prod_scoring = dot_prod_scoring
|
| 74 |
+
self.use_act_checkpoint_seg_head = use_act_checkpoint_seg_head
|
| 75 |
+
self.interactivity_in_encoder = interactivity_in_encoder
|
| 76 |
+
self.matcher = matcher
|
| 77 |
+
|
| 78 |
+
self.num_interactive_steps_val = num_interactive_steps_val
|
| 79 |
+
self.use_dot_prod_scoring = use_dot_prod_scoring
|
| 80 |
+
|
| 81 |
+
if self.use_dot_prod_scoring:
|
| 82 |
+
assert dot_prod_scoring is not None
|
| 83 |
+
self.dot_prod_scoring = dot_prod_scoring
|
| 84 |
+
self.instance_dot_prod_scoring = None
|
| 85 |
+
if separate_scorer_for_instance:
|
| 86 |
+
self.instance_dot_prod_scoring = deepcopy(dot_prod_scoring)
|
| 87 |
+
else:
|
| 88 |
+
self.class_embed = torch.nn.Linear(self.hidden_dim, 1)
|
| 89 |
+
self.instance_class_embed = None
|
| 90 |
+
if separate_scorer_for_instance:
|
| 91 |
+
self.instance_class_embed = deepcopy(self.class_embed)
|
| 92 |
+
|
| 93 |
+
self.supervise_joint_box_scores = supervise_joint_box_scores
|
| 94 |
+
self.detach_presence_in_joint_score = detach_presence_in_joint_score
|
| 95 |
+
|
| 96 |
+
# verify the number of queries for O2O and O2M
|
| 97 |
+
num_o2o_static = self.transformer.decoder.num_queries
|
| 98 |
+
num_o2m_static = self.transformer.decoder.num_o2m_queries
|
| 99 |
+
assert num_o2m_static == (num_o2o_static if self.transformer.decoder.dac else 0)
|
| 100 |
+
self.dac = self.transformer.decoder.dac
|
| 101 |
+
|
| 102 |
+
self.use_instance_query = use_instance_query
|
| 103 |
+
self.multimask_output = multimask_output
|
| 104 |
+
|
| 105 |
+
self.inst_interactive_predictor = inst_interactive_predictor
|
| 106 |
+
|
| 107 |
+
@property
|
| 108 |
+
def device(self):
|
| 109 |
+
self._device = getattr(self, "_device", None) or next(self.parameters()).device
|
| 110 |
+
return self._device
|
| 111 |
+
|
| 112 |
+
def to(self, *args, **kwargs):
|
| 113 |
+
# clear cached _device in case the model is moved to a different device
|
| 114 |
+
self._device = None
|
| 115 |
+
return super().to(*args, **kwargs)
|
| 116 |
+
|
| 117 |
+
def _get_img_feats(self, backbone_out, img_ids):
|
| 118 |
+
"""Retrieve correct image features from backbone output."""
|
| 119 |
+
if "backbone_fpn" in backbone_out:
|
| 120 |
+
if "id_mapping" in backbone_out and backbone_out["id_mapping"] is not None:
|
| 121 |
+
img_ids = backbone_out["id_mapping"][img_ids]
|
| 122 |
+
# If this assert fails, it likely means we're requesting different img_ids (perhaps a different frame?)
|
| 123 |
+
# We currently don't expect this to happen. We could technically trigger a recompute here,
|
| 124 |
+
# but likely at the cost of a cpu<->gpu sync point, which would deteriorate perf
|
| 125 |
+
torch._assert_async((img_ids >= 0).all())
|
| 126 |
+
|
| 127 |
+
vis_feats = backbone_out["backbone_fpn"][-self.num_feature_levels :]
|
| 128 |
+
vis_pos_enc = backbone_out["vision_pos_enc"][-self.num_feature_levels :]
|
| 129 |
+
vis_feat_sizes = [x.shape[-2:] for x in vis_pos_enc] # (H, W) shapes
|
| 130 |
+
# index and flatten visual features NxCxHxW => HWxNxC (batch-first => seq-first)
|
| 131 |
+
img_feats = [x[img_ids].flatten(2).permute(2, 0, 1) for x in vis_feats]
|
| 132 |
+
img_pos_embeds = [
|
| 133 |
+
x[img_ids].flatten(2).permute(2, 0, 1) for x in vis_pos_enc
|
| 134 |
+
]
|
| 135 |
+
return backbone_out, img_feats, img_pos_embeds, vis_feat_sizes
|
| 136 |
+
|
| 137 |
+
# Image features not available in backbone output, so we compute them on the fly
|
| 138 |
+
# This case likely occurs for video. In that case, we want to forward only the current frame
|
| 139 |
+
img_batch = backbone_out["img_batch_all_stages"]
|
| 140 |
+
if img_ids.numel() > 1:
|
| 141 |
+
# Only forward backbone on unique image ids to avoid repetitive computation
|
| 142 |
+
unique_ids, _ = torch.unique(img_ids, return_inverse=True)
|
| 143 |
+
else:
|
| 144 |
+
unique_ids, _ = img_ids, slice(None)
|
| 145 |
+
# Compute the image features on those unique image ids
|
| 146 |
+
# note: we allow using a list (or other indexable types) of tensors as img_batch
|
| 147 |
+
# (e.g. for async frame loading in demo). In this case we index img_batch.tensors directly
|
| 148 |
+
if isinstance(img_batch, torch.Tensor):
|
| 149 |
+
image = img_batch[unique_ids]
|
| 150 |
+
elif unique_ids.numel() == 1:
|
| 151 |
+
image = img_batch[unique_ids.item()].unsqueeze(0)
|
| 152 |
+
else:
|
| 153 |
+
image = torch.stack([img_batch[i] for i in unique_ids.tolist()])
|
| 154 |
+
# `img_batch` might be fp16 and offloaded to CPU
|
| 155 |
+
image = image.to(dtype=torch.float32, device=self.device)
|
| 156 |
+
# Next time we call this function, we want to remember which indices we computed
|
| 157 |
+
id_mapping = torch.full(
|
| 158 |
+
(len(img_batch),), -1, dtype=torch.long, device=self.device
|
| 159 |
+
)
|
| 160 |
+
id_mapping[unique_ids] = torch.arange(len(unique_ids), device=self.device)
|
| 161 |
+
backbone_out = {
|
| 162 |
+
**backbone_out,
|
| 163 |
+
**self.backbone.forward_image(image),
|
| 164 |
+
"id_mapping": id_mapping,
|
| 165 |
+
}
|
| 166 |
+
assert "backbone_fpn" in backbone_out
|
| 167 |
+
return self._get_img_feats(backbone_out, img_ids=img_ids)
|
| 168 |
+
|
| 169 |
+
def _encode_prompt(
|
| 170 |
+
self,
|
| 171 |
+
backbone_out,
|
| 172 |
+
find_input,
|
| 173 |
+
geometric_prompt,
|
| 174 |
+
visual_prompt_embed=None,
|
| 175 |
+
visual_prompt_mask=None,
|
| 176 |
+
encode_text=True,
|
| 177 |
+
prev_mask_pred=None,
|
| 178 |
+
):
|
| 179 |
+
# index text features (note that regardless of early or late fusion, the batch size of
|
| 180 |
+
# `txt_feats` is always the number of *prompts* in the encoder)
|
| 181 |
+
txt_ids = find_input.text_ids
|
| 182 |
+
txt_feats = backbone_out["language_features"][:, txt_ids]
|
| 183 |
+
txt_masks = backbone_out["language_mask"][txt_ids]
|
| 184 |
+
|
| 185 |
+
feat_tuple = self._get_img_feats(backbone_out, find_input.img_ids)
|
| 186 |
+
backbone_out, img_feats, img_pos_embeds, vis_feat_sizes = feat_tuple
|
| 187 |
+
|
| 188 |
+
if prev_mask_pred is not None:
|
| 189 |
+
img_feats = [img_feats[-1] + prev_mask_pred]
|
| 190 |
+
# Encode geometry
|
| 191 |
+
geo_feats, geo_masks = self.geometry_encoder(
|
| 192 |
+
geo_prompt=geometric_prompt,
|
| 193 |
+
img_feats=img_feats,
|
| 194 |
+
img_sizes=vis_feat_sizes,
|
| 195 |
+
img_pos_embeds=img_pos_embeds,
|
| 196 |
+
)
|
| 197 |
+
if visual_prompt_embed is None:
|
| 198 |
+
visual_prompt_embed = torch.zeros(
|
| 199 |
+
(0, *geo_feats.shape[1:]), device=geo_feats.device
|
| 200 |
+
)
|
| 201 |
+
visual_prompt_mask = torch.zeros(
|
| 202 |
+
(*geo_masks.shape[:-1], 0),
|
| 203 |
+
device=geo_masks.device,
|
| 204 |
+
dtype=geo_masks.dtype,
|
| 205 |
+
)
|
| 206 |
+
if encode_text:
|
| 207 |
+
prompt = torch.cat([txt_feats, geo_feats, visual_prompt_embed], dim=0)
|
| 208 |
+
prompt_mask = torch.cat([txt_masks, geo_masks, visual_prompt_mask], dim=1)
|
| 209 |
+
else:
|
| 210 |
+
prompt = torch.cat([geo_feats, visual_prompt_embed], dim=0)
|
| 211 |
+
prompt_mask = torch.cat([geo_masks, visual_prompt_mask], dim=1)
|
| 212 |
+
return prompt, prompt_mask, backbone_out
|
| 213 |
+
|
| 214 |
+
def _run_encoder(
|
| 215 |
+
self,
|
| 216 |
+
backbone_out,
|
| 217 |
+
find_input,
|
| 218 |
+
prompt,
|
| 219 |
+
prompt_mask,
|
| 220 |
+
encoder_extra_kwargs: Optional[Dict] = None,
|
| 221 |
+
):
|
| 222 |
+
feat_tuple = self._get_img_feats(backbone_out, find_input.img_ids)
|
| 223 |
+
backbone_out, img_feats, img_pos_embeds, vis_feat_sizes = feat_tuple
|
| 224 |
+
|
| 225 |
+
# Run the encoder
|
| 226 |
+
prompt_pos_embed = torch.zeros_like(prompt)
|
| 227 |
+
# make a copy of the image feature lists since the encoder may modify these lists in-place
|
| 228 |
+
memory = self.transformer.encoder(
|
| 229 |
+
src=img_feats.copy(),
|
| 230 |
+
src_key_padding_mask=None,
|
| 231 |
+
src_pos=img_pos_embeds.copy(),
|
| 232 |
+
prompt=prompt,
|
| 233 |
+
prompt_pos=prompt_pos_embed,
|
| 234 |
+
prompt_key_padding_mask=prompt_mask,
|
| 235 |
+
feat_sizes=vis_feat_sizes,
|
| 236 |
+
encoder_extra_kwargs=encoder_extra_kwargs,
|
| 237 |
+
)
|
| 238 |
+
encoder_out = {
|
| 239 |
+
# encoded image features
|
| 240 |
+
"encoder_hidden_states": memory["memory"],
|
| 241 |
+
"pos_embed": memory["pos_embed"],
|
| 242 |
+
"padding_mask": memory["padding_mask"],
|
| 243 |
+
"level_start_index": memory["level_start_index"],
|
| 244 |
+
"spatial_shapes": memory["spatial_shapes"],
|
| 245 |
+
"valid_ratios": memory["valid_ratios"],
|
| 246 |
+
"vis_feat_sizes": vis_feat_sizes,
|
| 247 |
+
# encoded text features (or other prompts)
|
| 248 |
+
"prompt_before_enc": prompt,
|
| 249 |
+
"prompt_after_enc": memory.get("memory_text", prompt),
|
| 250 |
+
"prompt_mask": prompt_mask,
|
| 251 |
+
}
|
| 252 |
+
return backbone_out, encoder_out, feat_tuple
|
| 253 |
+
|
| 254 |
+
def _run_decoder(
|
| 255 |
+
self,
|
| 256 |
+
pos_embed,
|
| 257 |
+
memory,
|
| 258 |
+
src_mask,
|
| 259 |
+
out,
|
| 260 |
+
prompt,
|
| 261 |
+
prompt_mask,
|
| 262 |
+
encoder_out,
|
| 263 |
+
):
|
| 264 |
+
bs = memory.shape[1]
|
| 265 |
+
query_embed = self.transformer.decoder.query_embed.weight
|
| 266 |
+
tgt = query_embed.unsqueeze(1).repeat(1, bs, 1)
|
| 267 |
+
|
| 268 |
+
apply_dac = self.transformer.decoder.dac and self.training
|
| 269 |
+
hs, reference_boxes, dec_presence_out, dec_presence_feats = (
|
| 270 |
+
self.transformer.decoder(
|
| 271 |
+
tgt=tgt,
|
| 272 |
+
memory=memory,
|
| 273 |
+
memory_key_padding_mask=src_mask,
|
| 274 |
+
pos=pos_embed,
|
| 275 |
+
reference_boxes=None,
|
| 276 |
+
level_start_index=encoder_out["level_start_index"],
|
| 277 |
+
spatial_shapes=encoder_out["spatial_shapes"],
|
| 278 |
+
valid_ratios=encoder_out["valid_ratios"],
|
| 279 |
+
tgt_mask=None,
|
| 280 |
+
memory_text=prompt,
|
| 281 |
+
text_attention_mask=prompt_mask,
|
| 282 |
+
apply_dac=apply_dac,
|
| 283 |
+
)
|
| 284 |
+
)
|
| 285 |
+
hs = hs.transpose(1, 2) # seq-first to batch-first
|
| 286 |
+
reference_boxes = reference_boxes.transpose(1, 2) # seq-first to batch-first
|
| 287 |
+
if dec_presence_out is not None:
|
| 288 |
+
# seq-first to batch-first
|
| 289 |
+
dec_presence_out = dec_presence_out.transpose(1, 2)
|
| 290 |
+
|
| 291 |
+
out["presence_feats"] = dec_presence_feats
|
| 292 |
+
self._update_scores_and_boxes(
|
| 293 |
+
out,
|
| 294 |
+
hs,
|
| 295 |
+
reference_boxes,
|
| 296 |
+
prompt,
|
| 297 |
+
prompt_mask,
|
| 298 |
+
dec_presence_out=dec_presence_out,
|
| 299 |
+
)
|
| 300 |
+
return out, hs
|
| 301 |
+
|
| 302 |
+
def _update_scores_and_boxes(
|
| 303 |
+
self,
|
| 304 |
+
out,
|
| 305 |
+
hs,
|
| 306 |
+
reference_boxes,
|
| 307 |
+
prompt,
|
| 308 |
+
prompt_mask,
|
| 309 |
+
dec_presence_out=None,
|
| 310 |
+
is_instance_prompt=False,
|
| 311 |
+
):
|
| 312 |
+
apply_dac = self.transformer.decoder.dac and self.training
|
| 313 |
+
num_o2o = (hs.size(2) // 2) if apply_dac else hs.size(2)
|
| 314 |
+
num_o2m = hs.size(2) - num_o2o
|
| 315 |
+
assert num_o2m == (num_o2o if apply_dac else 0)
|
| 316 |
+
out["queries"] = hs[-1][:, :num_o2o] # remove o2m queries if there are any
|
| 317 |
+
# score prediction
|
| 318 |
+
if self.use_dot_prod_scoring:
|
| 319 |
+
dot_prod_scoring_head = self.dot_prod_scoring
|
| 320 |
+
if is_instance_prompt and self.instance_dot_prod_scoring is not None:
|
| 321 |
+
dot_prod_scoring_head = self.instance_dot_prod_scoring
|
| 322 |
+
outputs_class = dot_prod_scoring_head(hs, prompt, prompt_mask)
|
| 323 |
+
else:
|
| 324 |
+
class_embed_head = self.class_embed
|
| 325 |
+
if is_instance_prompt and self.instance_class_embed is not None:
|
| 326 |
+
class_embed_head = self.instance_class_embed
|
| 327 |
+
outputs_class = class_embed_head(hs)
|
| 328 |
+
|
| 329 |
+
# box prediction
|
| 330 |
+
box_head = self.transformer.decoder.bbox_embed
|
| 331 |
+
if (
|
| 332 |
+
is_instance_prompt
|
| 333 |
+
and self.transformer.decoder.instance_bbox_embed is not None
|
| 334 |
+
):
|
| 335 |
+
box_head = self.transformer.decoder.instance_bbox_embed
|
| 336 |
+
anchor_box_offsets = box_head(hs)
|
| 337 |
+
reference_boxes_inv_sig = inverse_sigmoid(reference_boxes)
|
| 338 |
+
outputs_coord = (reference_boxes_inv_sig + anchor_box_offsets).sigmoid()
|
| 339 |
+
outputs_boxes_xyxy = box_cxcywh_to_xyxy(outputs_coord)
|
| 340 |
+
|
| 341 |
+
if dec_presence_out is not None:
|
| 342 |
+
_update_out(
|
| 343 |
+
out, "presence_logit_dec", dec_presence_out, update_aux=self.training
|
| 344 |
+
)
|
| 345 |
+
|
| 346 |
+
if self.supervise_joint_box_scores:
|
| 347 |
+
assert dec_presence_out is not None
|
| 348 |
+
prob_dec_presence_out = dec_presence_out.clone().sigmoid()
|
| 349 |
+
if self.detach_presence_in_joint_score:
|
| 350 |
+
prob_dec_presence_out = prob_dec_presence_out.detach()
|
| 351 |
+
|
| 352 |
+
outputs_class = inverse_sigmoid(
|
| 353 |
+
outputs_class.sigmoid() * prob_dec_presence_out.unsqueeze(2)
|
| 354 |
+
).clamp(min=-10.0, max=10.0)
|
| 355 |
+
|
| 356 |
+
_update_out(
|
| 357 |
+
out, "pred_logits", outputs_class[:, :, :num_o2o], update_aux=self.training
|
| 358 |
+
)
|
| 359 |
+
_update_out(
|
| 360 |
+
out, "pred_boxes", outputs_coord[:, :, :num_o2o], update_aux=self.training
|
| 361 |
+
)
|
| 362 |
+
_update_out(
|
| 363 |
+
out,
|
| 364 |
+
"pred_boxes_xyxy",
|
| 365 |
+
outputs_boxes_xyxy[:, :, :num_o2o],
|
| 366 |
+
update_aux=self.training,
|
| 367 |
+
)
|
| 368 |
+
if num_o2m > 0 and self.training:
|
| 369 |
+
_update_out(
|
| 370 |
+
out,
|
| 371 |
+
"pred_logits_o2m",
|
| 372 |
+
outputs_class[:, :, num_o2o:],
|
| 373 |
+
update_aux=self.training,
|
| 374 |
+
)
|
| 375 |
+
_update_out(
|
| 376 |
+
out,
|
| 377 |
+
"pred_boxes_o2m",
|
| 378 |
+
outputs_coord[:, :, num_o2o:],
|
| 379 |
+
update_aux=self.training,
|
| 380 |
+
)
|
| 381 |
+
_update_out(
|
| 382 |
+
out,
|
| 383 |
+
"pred_boxes_xyxy_o2m",
|
| 384 |
+
outputs_boxes_xyxy[:, :, num_o2o:],
|
| 385 |
+
update_aux=self.training,
|
| 386 |
+
)
|
| 387 |
+
|
| 388 |
+
def _run_segmentation_heads(
|
| 389 |
+
self,
|
| 390 |
+
out,
|
| 391 |
+
backbone_out,
|
| 392 |
+
img_ids,
|
| 393 |
+
vis_feat_sizes,
|
| 394 |
+
encoder_hidden_states,
|
| 395 |
+
prompt,
|
| 396 |
+
prompt_mask,
|
| 397 |
+
hs,
|
| 398 |
+
):
|
| 399 |
+
apply_dac = self.transformer.decoder.dac and self.training
|
| 400 |
+
if self.segmentation_head is not None:
|
| 401 |
+
num_o2o = (hs.size(2) // 2) if apply_dac else hs.size(2)
|
| 402 |
+
num_o2m = hs.size(2) - num_o2o
|
| 403 |
+
obj_queries = hs if self.o2m_mask_predict else hs[:, :, :num_o2o]
|
| 404 |
+
seg_head_outputs = activation_ckpt_wrapper(self.segmentation_head)(
|
| 405 |
+
backbone_feats=backbone_out["backbone_fpn"],
|
| 406 |
+
obj_queries=obj_queries,
|
| 407 |
+
image_ids=img_ids,
|
| 408 |
+
encoder_hidden_states=encoder_hidden_states,
|
| 409 |
+
act_ckpt_enable=self.training and self.use_act_checkpoint_seg_head,
|
| 410 |
+
prompt=prompt,
|
| 411 |
+
prompt_mask=prompt_mask,
|
| 412 |
+
)
|
| 413 |
+
aux_masks = False # self.aux_loss and self.segmentation_head.aux_masks
|
| 414 |
+
for k, v in seg_head_outputs.items():
|
| 415 |
+
if k in self.segmentation_head.instance_keys:
|
| 416 |
+
_update_out(out, k, v[:, :num_o2o], auxiliary=aux_masks)
|
| 417 |
+
if (
|
| 418 |
+
self.o2m_mask_predict and num_o2m > 0
|
| 419 |
+
): # handle o2m mask prediction
|
| 420 |
+
_update_out(
|
| 421 |
+
out, f"{k}_o2m", v[:, num_o2o:], auxiliary=aux_masks
|
| 422 |
+
)
|
| 423 |
+
else:
|
| 424 |
+
out[k] = v
|
| 425 |
+
else:
|
| 426 |
+
backbone_out.pop("backbone_fpn", None)
|
| 427 |
+
|
| 428 |
+
def _get_best_mask(self, out):
|
| 429 |
+
prev_mask_idx = out["pred_logits"].argmax(dim=1).squeeze(1)
|
| 430 |
+
batch_idx = torch.arange(
|
| 431 |
+
out["pred_logits"].shape[0], device=prev_mask_idx.device
|
| 432 |
+
)
|
| 433 |
+
prev_mask_pred = out["pred_masks"][batch_idx, prev_mask_idx][:, None]
|
| 434 |
+
# Downsample mask to match image resolution.
|
| 435 |
+
prev_mask_pred = self.geometry_encoder.mask_encoder.mask_downsampler(
|
| 436 |
+
prev_mask_pred
|
| 437 |
+
)
|
| 438 |
+
prev_mask_pred = prev_mask_pred.flatten(-2).permute(2, 0, 1)
|
| 439 |
+
|
| 440 |
+
return prev_mask_pred
|
| 441 |
+
|
| 442 |
+
def forward_grounding(
|
| 443 |
+
self,
|
| 444 |
+
backbone_out,
|
| 445 |
+
find_input,
|
| 446 |
+
find_target,
|
| 447 |
+
geometric_prompt: Prompt,
|
| 448 |
+
):
|
| 449 |
+
with torch.profiler.record_function("SAM3Image._encode_prompt"):
|
| 450 |
+
prompt, prompt_mask, backbone_out = self._encode_prompt(
|
| 451 |
+
backbone_out, find_input, geometric_prompt
|
| 452 |
+
)
|
| 453 |
+
# Run the encoder
|
| 454 |
+
with torch.profiler.record_function("SAM3Image._run_encoder"):
|
| 455 |
+
backbone_out, encoder_out, _ = self._run_encoder(
|
| 456 |
+
backbone_out, find_input, prompt, prompt_mask
|
| 457 |
+
)
|
| 458 |
+
out = {
|
| 459 |
+
"encoder_hidden_states": encoder_out["encoder_hidden_states"],
|
| 460 |
+
"prev_encoder_out": {
|
| 461 |
+
"encoder_out": encoder_out,
|
| 462 |
+
"backbone_out": backbone_out,
|
| 463 |
+
},
|
| 464 |
+
}
|
| 465 |
+
|
| 466 |
+
# Run the decoder
|
| 467 |
+
with torch.profiler.record_function("SAM3Image._run_decoder"):
|
| 468 |
+
out, hs = self._run_decoder(
|
| 469 |
+
memory=out["encoder_hidden_states"],
|
| 470 |
+
pos_embed=encoder_out["pos_embed"],
|
| 471 |
+
src_mask=encoder_out["padding_mask"],
|
| 472 |
+
out=out,
|
| 473 |
+
prompt=prompt,
|
| 474 |
+
prompt_mask=prompt_mask,
|
| 475 |
+
encoder_out=encoder_out,
|
| 476 |
+
)
|
| 477 |
+
|
| 478 |
+
# Run segmentation heads
|
| 479 |
+
with torch.profiler.record_function("SAM3Image._run_segmentation_heads"):
|
| 480 |
+
self._run_segmentation_heads(
|
| 481 |
+
out=out,
|
| 482 |
+
backbone_out=backbone_out,
|
| 483 |
+
img_ids=find_input.img_ids,
|
| 484 |
+
vis_feat_sizes=encoder_out["vis_feat_sizes"],
|
| 485 |
+
encoder_hidden_states=out["encoder_hidden_states"],
|
| 486 |
+
prompt=prompt,
|
| 487 |
+
prompt_mask=prompt_mask,
|
| 488 |
+
hs=hs,
|
| 489 |
+
)
|
| 490 |
+
|
| 491 |
+
if self.training or self.num_interactive_steps_val > 0:
|
| 492 |
+
self._compute_matching(out, self.back_convert(find_target))
|
| 493 |
+
return out
|
| 494 |
+
|
| 495 |
+
def _postprocess_out(self, out: Dict, multimask_output: bool = False):
|
| 496 |
+
# For multimask output, during eval we return the single best mask with the dict keys expected by the evaluators, but also return the multimasks output with new keys.
|
| 497 |
+
num_mask_boxes = out["pred_boxes"].size(1)
|
| 498 |
+
if not self.training and multimask_output and num_mask_boxes > 1:
|
| 499 |
+
out["multi_pred_logits"] = out["pred_logits"]
|
| 500 |
+
if "pred_masks" in out:
|
| 501 |
+
out["multi_pred_masks"] = out["pred_masks"]
|
| 502 |
+
out["multi_pred_boxes"] = out["pred_boxes"]
|
| 503 |
+
out["multi_pred_boxes_xyxy"] = out["pred_boxes_xyxy"]
|
| 504 |
+
|
| 505 |
+
best_mask_idx = out["pred_logits"].argmax(1).squeeze(1)
|
| 506 |
+
batch_idx = torch.arange(len(best_mask_idx), device=best_mask_idx.device)
|
| 507 |
+
|
| 508 |
+
out["pred_logits"] = out["pred_logits"][batch_idx, best_mask_idx].unsqueeze(
|
| 509 |
+
1
|
| 510 |
+
)
|
| 511 |
+
if "pred_masks" in out:
|
| 512 |
+
out["pred_masks"] = out["pred_masks"][
|
| 513 |
+
batch_idx, best_mask_idx
|
| 514 |
+
].unsqueeze(1)
|
| 515 |
+
out["pred_boxes"] = out["pred_boxes"][batch_idx, best_mask_idx].unsqueeze(1)
|
| 516 |
+
out["pred_boxes_xyxy"] = out["pred_boxes_xyxy"][
|
| 517 |
+
batch_idx, best_mask_idx
|
| 518 |
+
].unsqueeze(1)
|
| 519 |
+
|
| 520 |
+
return out
|
| 521 |
+
|
| 522 |
+
def _get_dummy_prompt(self, num_prompts=1):
|
| 523 |
+
device = self.device
|
| 524 |
+
geometric_prompt = Prompt(
|
| 525 |
+
box_embeddings=torch.zeros(0, num_prompts, 4, device=device),
|
| 526 |
+
box_mask=torch.zeros(num_prompts, 0, device=device, dtype=torch.bool),
|
| 527 |
+
)
|
| 528 |
+
return geometric_prompt
|
| 529 |
+
|
| 530 |
+
def forward(self, input: BatchedDatapoint):
|
| 531 |
+
device = self.device
|
| 532 |
+
backbone_out = {"img_batch_all_stages": input.img_batch}
|
| 533 |
+
backbone_out.update(self.backbone.forward_image(input.img_batch))
|
| 534 |
+
num_frames = len(input.find_inputs)
|
| 535 |
+
assert num_frames == 1
|
| 536 |
+
|
| 537 |
+
text_outputs = self.backbone.forward_text(input.find_text_batch, device=device)
|
| 538 |
+
backbone_out.update(text_outputs)
|
| 539 |
+
|
| 540 |
+
previous_stages_out = SAM3Output(
|
| 541 |
+
iter_mode=SAM3Output.IterMode.LAST_STEP_PER_STAGE
|
| 542 |
+
)
|
| 543 |
+
|
| 544 |
+
find_input = input.find_inputs[0]
|
| 545 |
+
find_target = input.find_targets[0]
|
| 546 |
+
|
| 547 |
+
if find_input.input_points is not None and find_input.input_points.numel() > 0:
|
| 548 |
+
print("Warning: Point prompts are ignored in PCS.")
|
| 549 |
+
|
| 550 |
+
num_interactive_steps = 0 if self.training else self.num_interactive_steps_val
|
| 551 |
+
geometric_prompt = Prompt(
|
| 552 |
+
box_embeddings=find_input.input_boxes,
|
| 553 |
+
box_mask=find_input.input_boxes_mask,
|
| 554 |
+
box_labels=find_input.input_boxes_label,
|
| 555 |
+
)
|
| 556 |
+
|
| 557 |
+
# Init vars that are shared across the loop.
|
| 558 |
+
stage_outs = []
|
| 559 |
+
for cur_step in range(num_interactive_steps + 1):
|
| 560 |
+
if cur_step > 0:
|
| 561 |
+
# We sample interactive geometric prompts (boxes, points)
|
| 562 |
+
geometric_prompt, _ = self.interactive_prompt_sampler.sample(
|
| 563 |
+
geo_prompt=geometric_prompt,
|
| 564 |
+
find_target=find_target,
|
| 565 |
+
previous_out=stage_outs[-1],
|
| 566 |
+
)
|
| 567 |
+
out = self.forward_grounding(
|
| 568 |
+
backbone_out=backbone_out,
|
| 569 |
+
find_input=find_input,
|
| 570 |
+
find_target=find_target,
|
| 571 |
+
geometric_prompt=geometric_prompt.clone(),
|
| 572 |
+
)
|
| 573 |
+
stage_outs.append(out)
|
| 574 |
+
|
| 575 |
+
previous_stages_out.append(stage_outs)
|
| 576 |
+
return previous_stages_out
|
| 577 |
+
|
| 578 |
+
def _compute_matching(self, out, targets):
|
| 579 |
+
out["indices"] = self.matcher(out, targets)
|
| 580 |
+
for aux_out in out.get("aux_outputs", []):
|
| 581 |
+
aux_out["indices"] = self.matcher(aux_out, targets)
|
| 582 |
+
|
| 583 |
+
def back_convert(self, targets):
|
| 584 |
+
batched_targets = {
|
| 585 |
+
"boxes": targets.boxes.view(-1, 4),
|
| 586 |
+
"boxes_xyxy": box_cxcywh_to_xyxy(targets.boxes.view(-1, 4)),
|
| 587 |
+
"boxes_padded": targets.boxes_padded,
|
| 588 |
+
"positive_map": targets.boxes.new_ones(len(targets.boxes), 1),
|
| 589 |
+
"num_boxes": targets.num_boxes,
|
| 590 |
+
"masks": targets.segments,
|
| 591 |
+
"semantic_masks": targets.semantic_segments,
|
| 592 |
+
"is_valid_mask": targets.is_valid_segment,
|
| 593 |
+
"is_exhaustive": targets.is_exhaustive,
|
| 594 |
+
"object_ids_packed": targets.object_ids,
|
| 595 |
+
"object_ids_padded": targets.object_ids_padded,
|
| 596 |
+
}
|
| 597 |
+
return batched_targets
|
| 598 |
+
|
| 599 |
+
def predict_inst(
|
| 600 |
+
self,
|
| 601 |
+
inference_state,
|
| 602 |
+
**kwargs,
|
| 603 |
+
) -> Tuple[np.ndarray, np.ndarray, np.ndarray]:
|
| 604 |
+
orig_h, orig_w = (
|
| 605 |
+
inference_state["original_height"],
|
| 606 |
+
inference_state["original_width"],
|
| 607 |
+
)
|
| 608 |
+
backbone_out = inference_state["backbone_out"]["sam2_backbone_out"]
|
| 609 |
+
(
|
| 610 |
+
_,
|
| 611 |
+
vision_feats,
|
| 612 |
+
_,
|
| 613 |
+
_,
|
| 614 |
+
) = self.inst_interactive_predictor.model._prepare_backbone_features(
|
| 615 |
+
backbone_out
|
| 616 |
+
)
|
| 617 |
+
# Add no_mem_embed, which is added to the lowest rest feat. map during training on videos
|
| 618 |
+
vision_feats[-1] = (
|
| 619 |
+
vision_feats[-1] + self.inst_interactive_predictor.model.no_mem_embed
|
| 620 |
+
)
|
| 621 |
+
feats = [
|
| 622 |
+
feat.permute(1, 2, 0).view(1, -1, *feat_size)
|
| 623 |
+
for feat, feat_size in zip(
|
| 624 |
+
vision_feats[::-1], self.inst_interactive_predictor._bb_feat_sizes[::-1]
|
| 625 |
+
)
|
| 626 |
+
][::-1]
|
| 627 |
+
self.inst_interactive_predictor._features = {
|
| 628 |
+
"image_embed": feats[-1],
|
| 629 |
+
"high_res_feats": feats[:-1],
|
| 630 |
+
}
|
| 631 |
+
self.inst_interactive_predictor._is_image_set = True
|
| 632 |
+
self.inst_interactive_predictor._orig_hw = [(orig_h, orig_w)]
|
| 633 |
+
res = self.inst_interactive_predictor.predict(**kwargs)
|
| 634 |
+
self.inst_interactive_predictor._features = None
|
| 635 |
+
self.inst_interactive_predictor._is_image_set = False
|
| 636 |
+
return res
|
| 637 |
+
|
| 638 |
+
def predict_inst_batch(
|
| 639 |
+
self,
|
| 640 |
+
inference_state,
|
| 641 |
+
*args,
|
| 642 |
+
**kwargs,
|
| 643 |
+
) -> Tuple[List[np.ndarray], List[np.ndarray], List[np.ndarray]]:
|
| 644 |
+
backbone_out = inference_state["backbone_out"]["sam2_backbone_out"]
|
| 645 |
+
(
|
| 646 |
+
_,
|
| 647 |
+
vision_feats,
|
| 648 |
+
_,
|
| 649 |
+
_,
|
| 650 |
+
) = self.inst_interactive_predictor.model._prepare_backbone_features(
|
| 651 |
+
backbone_out
|
| 652 |
+
)
|
| 653 |
+
# Add no_mem_embed, which is added to the lowest res feat. map during training on videos
|
| 654 |
+
vision_feats[-1] = (
|
| 655 |
+
vision_feats[-1] + self.inst_interactive_predictor.model.no_mem_embed
|
| 656 |
+
)
|
| 657 |
+
batch_size = vision_feats[-1].shape[1]
|
| 658 |
+
orig_heights, orig_widths = (
|
| 659 |
+
inference_state["original_heights"],
|
| 660 |
+
inference_state["original_widths"],
|
| 661 |
+
)
|
| 662 |
+
assert (
|
| 663 |
+
batch_size == len(orig_heights) == len(orig_widths)
|
| 664 |
+
), f"Batch size mismatch in predict_inst_batch. Got {batch_size}, {len(orig_heights)}, {len(orig_widths)}"
|
| 665 |
+
feats = [
|
| 666 |
+
feat.permute(1, 2, 0).view(batch_size, -1, *feat_size)
|
| 667 |
+
for feat, feat_size in zip(
|
| 668 |
+
vision_feats[::-1], self.inst_interactive_predictor._bb_feat_sizes[::-1]
|
| 669 |
+
)
|
| 670 |
+
][::-1]
|
| 671 |
+
self.inst_interactive_predictor._features = {
|
| 672 |
+
"image_embed": feats[-1],
|
| 673 |
+
"high_res_feats": feats[:-1],
|
| 674 |
+
}
|
| 675 |
+
self.inst_interactive_predictor._is_image_set = True
|
| 676 |
+
self.inst_interactive_predictor._is_batch = True
|
| 677 |
+
self.inst_interactive_predictor._orig_hw = [
|
| 678 |
+
(orig_h, orig_w) for orig_h, orig_w in zip(orig_heights, orig_widths)
|
| 679 |
+
]
|
| 680 |
+
res = self.inst_interactive_predictor.predict_batch(*args, **kwargs)
|
| 681 |
+
self.inst_interactive_predictor._features = None
|
| 682 |
+
self.inst_interactive_predictor._is_image_set = False
|
| 683 |
+
self.inst_interactive_predictor._is_batch = False
|
| 684 |
+
return res
|
| 685 |
+
|
| 686 |
+
|
| 687 |
+
class Sam3ImageOnVideoMultiGPU(Sam3Image):
|
| 688 |
+
def __init__(
|
| 689 |
+
self, *args, async_all_gather=True, gather_backbone_out=None, **kwargs
|
| 690 |
+
):
|
| 691 |
+
super().__init__(*args, **kwargs)
|
| 692 |
+
self.rank = int(os.getenv("RANK", "0"))
|
| 693 |
+
self.world_size = int(os.getenv("WORLD_SIZE", "1"))
|
| 694 |
+
self.async_all_gather = async_all_gather
|
| 695 |
+
|
| 696 |
+
# if gather_backbone is not set, default to gathering only for `SAM3VLBackbone`
|
| 697 |
+
if gather_backbone_out is None:
|
| 698 |
+
gather_backbone_out = isinstance(self.backbone, SAM3VLBackbone)
|
| 699 |
+
self.gather_backbone_out = gather_backbone_out
|
| 700 |
+
|
| 701 |
+
def forward_video_grounding_multigpu(
|
| 702 |
+
self,
|
| 703 |
+
backbone_out,
|
| 704 |
+
find_inputs,
|
| 705 |
+
geometric_prompt: Prompt,
|
| 706 |
+
frame_idx,
|
| 707 |
+
num_frames,
|
| 708 |
+
# `multigpu_buffer` is a dict to cache detector's outputs in a chunk between different calls
|
| 709 |
+
multigpu_buffer,
|
| 710 |
+
track_in_reverse=False,
|
| 711 |
+
# whether to also return the SAM2 backbone features
|
| 712 |
+
return_sam2_backbone_feats=False,
|
| 713 |
+
# whether to perform NMS and suppress the scores of those detections removed by NMS
|
| 714 |
+
run_nms=False,
|
| 715 |
+
nms_prob_thresh=None,
|
| 716 |
+
nms_iou_thresh=None,
|
| 717 |
+
**kwargs,
|
| 718 |
+
):
|
| 719 |
+
"""
|
| 720 |
+
Compute the detector's detection outputs in a distributed manner, where all GPUs process
|
| 721 |
+
a chunk of frames (equal to the number of GPUs) at once and store them in cache.
|
| 722 |
+
"""
|
| 723 |
+
# Step 1: fetch the detector outputs in the current chunk from buffer
|
| 724 |
+
frame_idx_curr_b = frame_idx - frame_idx % self.world_size
|
| 725 |
+
frame_idx_curr_e = min(frame_idx_curr_b + self.world_size, num_frames)
|
| 726 |
+
# in case the current frame's detection results are not in the buffer yet, build the current chunk
|
| 727 |
+
# (this should only happen on the first chunk, since we are also building the next chunk below)
|
| 728 |
+
if frame_idx not in multigpu_buffer:
|
| 729 |
+
with torch.profiler.record_function("build_multigpu_buffer_next_chunk1"):
|
| 730 |
+
self._build_multigpu_buffer_next_chunk(
|
| 731 |
+
backbone_out=backbone_out,
|
| 732 |
+
find_inputs=find_inputs,
|
| 733 |
+
geometric_prompt=geometric_prompt,
|
| 734 |
+
frame_idx_begin=frame_idx_curr_b,
|
| 735 |
+
frame_idx_end=frame_idx_curr_e,
|
| 736 |
+
num_frames=num_frames,
|
| 737 |
+
multigpu_buffer=multigpu_buffer,
|
| 738 |
+
run_nms=run_nms,
|
| 739 |
+
nms_prob_thresh=nms_prob_thresh,
|
| 740 |
+
nms_iou_thresh=nms_iou_thresh,
|
| 741 |
+
)
|
| 742 |
+
|
| 743 |
+
# read out the current frame's results from `multigpu_buffer`
|
| 744 |
+
out = {}
|
| 745 |
+
for k, (v, handle) in multigpu_buffer[frame_idx].items():
|
| 746 |
+
if k.startswith("sam2_backbone_") and not return_sam2_backbone_feats:
|
| 747 |
+
continue
|
| 748 |
+
if handle is not None:
|
| 749 |
+
handle.wait() # wait for async all-gather to finish
|
| 750 |
+
out[k] = v
|
| 751 |
+
|
| 752 |
+
# Step 2: remove detection outputs of the previous chunk from cache to save GPU memory
|
| 753 |
+
if not track_in_reverse and frame_idx_curr_b - self.world_size >= 0:
|
| 754 |
+
frame_idx_prev_e = frame_idx_curr_b
|
| 755 |
+
frame_idx_prev_b = frame_idx_curr_b - self.world_size
|
| 756 |
+
elif track_in_reverse and frame_idx_curr_e < num_frames:
|
| 757 |
+
frame_idx_prev_b = frame_idx_curr_e
|
| 758 |
+
frame_idx_prev_e = min(frame_idx_prev_b + self.world_size, num_frames)
|
| 759 |
+
else:
|
| 760 |
+
frame_idx_prev_b = frame_idx_prev_e = None
|
| 761 |
+
if frame_idx_prev_b is not None:
|
| 762 |
+
for frame_idx_rm in range(frame_idx_prev_b, frame_idx_prev_e):
|
| 763 |
+
multigpu_buffer.pop(frame_idx_rm, None)
|
| 764 |
+
|
| 765 |
+
# Step 3: compute and cache detection outputs of the next chunk ahead of time
|
| 766 |
+
# (so that we can overlap computation with all-gather transfer)
|
| 767 |
+
if not track_in_reverse and frame_idx_curr_e < num_frames:
|
| 768 |
+
frame_idx_next_b = frame_idx_curr_e
|
| 769 |
+
frame_idx_next_e = min(frame_idx_next_b + self.world_size, num_frames)
|
| 770 |
+
elif track_in_reverse and frame_idx_curr_b - self.world_size >= 0:
|
| 771 |
+
frame_idx_next_e = frame_idx_curr_b
|
| 772 |
+
frame_idx_next_b = frame_idx_curr_b - self.world_size
|
| 773 |
+
else:
|
| 774 |
+
frame_idx_next_b = frame_idx_next_e = None
|
| 775 |
+
if frame_idx_next_b is not None and frame_idx_next_b not in multigpu_buffer:
|
| 776 |
+
with torch.profiler.record_function("build_multigpu_buffer_next_chunk2"):
|
| 777 |
+
self._build_multigpu_buffer_next_chunk(
|
| 778 |
+
backbone_out=backbone_out,
|
| 779 |
+
find_inputs=find_inputs,
|
| 780 |
+
geometric_prompt=geometric_prompt,
|
| 781 |
+
frame_idx_begin=frame_idx_next_b,
|
| 782 |
+
frame_idx_end=frame_idx_next_e,
|
| 783 |
+
num_frames=num_frames,
|
| 784 |
+
multigpu_buffer=multigpu_buffer,
|
| 785 |
+
run_nms=run_nms,
|
| 786 |
+
nms_prob_thresh=nms_prob_thresh,
|
| 787 |
+
nms_iou_thresh=nms_iou_thresh,
|
| 788 |
+
)
|
| 789 |
+
|
| 790 |
+
return out, backbone_out
|
| 791 |
+
|
| 792 |
+
def _build_multigpu_buffer_next_chunk(
|
| 793 |
+
self,
|
| 794 |
+
backbone_out,
|
| 795 |
+
find_inputs,
|
| 796 |
+
geometric_prompt: Prompt,
|
| 797 |
+
frame_idx_begin,
|
| 798 |
+
frame_idx_end,
|
| 799 |
+
num_frames,
|
| 800 |
+
multigpu_buffer,
|
| 801 |
+
run_nms=False,
|
| 802 |
+
nms_prob_thresh=None,
|
| 803 |
+
nms_iou_thresh=None,
|
| 804 |
+
):
|
| 805 |
+
"""Compute detection outputs on a chunk of frames and store their results in multigpu_buffer."""
|
| 806 |
+
# each GPU computes detections on one frame in the chunk (in a round-robin manner)
|
| 807 |
+
frame_idx_local_gpu = min(frame_idx_begin + self.rank, frame_idx_end - 1)
|
| 808 |
+
# `forward_grounding` (from base class `Sam3ImageOnVideo`) runs the detector on a single frame
|
| 809 |
+
with torch.profiler.record_function("forward_grounding"):
|
| 810 |
+
out_local = self.forward_grounding(
|
| 811 |
+
backbone_out=backbone_out,
|
| 812 |
+
find_input=find_inputs[frame_idx_local_gpu],
|
| 813 |
+
find_target=None,
|
| 814 |
+
geometric_prompt=geometric_prompt,
|
| 815 |
+
)
|
| 816 |
+
if run_nms:
|
| 817 |
+
with torch.profiler.record_function("nms_masks"):
|
| 818 |
+
# run NMS as a post-processing step on top of the detection outputs
|
| 819 |
+
assert nms_prob_thresh is not None and nms_iou_thresh is not None
|
| 820 |
+
pred_probs = out_local["pred_logits"].squeeze(-1).sigmoid()
|
| 821 |
+
pred_masks = out_local["pred_masks"]
|
| 822 |
+
# loop over text prompts (not an overhead for demo where there's only 1 prompt)
|
| 823 |
+
for prompt_idx in range(pred_probs.size(0)):
|
| 824 |
+
keep = nms_masks(
|
| 825 |
+
pred_probs=pred_probs[prompt_idx],
|
| 826 |
+
pred_masks=pred_masks[prompt_idx],
|
| 827 |
+
prob_threshold=nms_prob_thresh,
|
| 828 |
+
iou_threshold=nms_iou_thresh,
|
| 829 |
+
)
|
| 830 |
+
# set a very low threshold for those detections removed by NMS
|
| 831 |
+
out_local["pred_logits"][prompt_idx, :, 0] -= 1e4 * (~keep).float()
|
| 832 |
+
|
| 833 |
+
if self.gather_backbone_out:
|
| 834 |
+
# gather the SAM 2 backbone features across GPUs
|
| 835 |
+
feats = out_local["prev_encoder_out"]["backbone_out"]["sam2_backbone_out"]
|
| 836 |
+
assert len(feats["backbone_fpn"]) == 3 # SAM2 backbone always have 3 levels
|
| 837 |
+
# cast the SAM2 backbone features to bfloat16 for all-gather (this is usually
|
| 838 |
+
# a no-op, SAM2 backbone features are likely already in bfloat16 due to AMP)
|
| 839 |
+
backbone_fpn_bf16 = [x.to(torch.bfloat16) for x in feats["backbone_fpn"]]
|
| 840 |
+
fpn0, fpn_handle0 = self._gather_tensor(backbone_fpn_bf16[0])
|
| 841 |
+
fpn1, fpn_handle1 = self._gather_tensor(backbone_fpn_bf16[1])
|
| 842 |
+
fpn2, fpn_handle2 = self._gather_tensor(backbone_fpn_bf16[2])
|
| 843 |
+
# vision_pos_enc is the same on all frames, so no need to all-gather them
|
| 844 |
+
vision_pos_enc = feats["vision_pos_enc"]
|
| 845 |
+
|
| 846 |
+
# trim the detector output to only include the necessary keys
|
| 847 |
+
out_local = {
|
| 848 |
+
"pred_logits": out_local["pred_logits"],
|
| 849 |
+
"pred_boxes": out_local["pred_boxes"],
|
| 850 |
+
"pred_boxes_xyxy": out_local["pred_boxes_xyxy"],
|
| 851 |
+
"pred_masks": out_local["pred_masks"],
|
| 852 |
+
}
|
| 853 |
+
|
| 854 |
+
# gather the results: after this step, each GPU will receive detector outputs on
|
| 855 |
+
# all frames in the chunk and store them in `multigpu_buffer`
|
| 856 |
+
out_gathered = {k: self._gather_tensor(v) for k, v in out_local.items()}
|
| 857 |
+
for rank in range(self.world_size):
|
| 858 |
+
frame_idx_to_save = frame_idx_begin + rank
|
| 859 |
+
if frame_idx_to_save >= num_frames:
|
| 860 |
+
continue
|
| 861 |
+
frame_buffer = {
|
| 862 |
+
k: (v[rank], handle) for k, (v, handle) in out_gathered.items()
|
| 863 |
+
}
|
| 864 |
+
if self.gather_backbone_out:
|
| 865 |
+
# also add gathered SAM 2 backbone features to frame_buffer
|
| 866 |
+
frame_buffer["tracker_backbone_fpn_0"] = (fpn0[rank], fpn_handle0)
|
| 867 |
+
frame_buffer["tracker_backbone_fpn_1"] = (fpn1[rank], fpn_handle1)
|
| 868 |
+
frame_buffer["tracker_backbone_fpn_2"] = (fpn2[rank], fpn_handle2)
|
| 869 |
+
frame_buffer["tracker_backbone_pos_enc"] = (vision_pos_enc, None)
|
| 870 |
+
|
| 871 |
+
multigpu_buffer[frame_idx_to_save] = frame_buffer
|
| 872 |
+
|
| 873 |
+
def _gather_tensor(self, x):
|
| 874 |
+
if self.world_size == 1:
|
| 875 |
+
return [x], None
|
| 876 |
+
|
| 877 |
+
async_op = self.async_all_gather
|
| 878 |
+
# here `.contiguous()` is required -- otherwise NCCL all_gather
|
| 879 |
+
# sometimes gives wrong results
|
| 880 |
+
x = x.contiguous() # ensure contiguous memory for NCCL
|
| 881 |
+
output_list = [torch.empty_like(x) for _ in range(self.world_size)]
|
| 882 |
+
handle = torch.distributed.all_gather(output_list, x, async_op=async_op)
|
| 883 |
+
return output_list, handle
|
之前的代码版本/这一版注意力有问题/HuatuoGPT-Vision/MedSAM3/sam3/model/sam3_tracker_utils.py
ADDED
|
@@ -0,0 +1,427 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|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
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
# Copyright (c) Meta Platforms, Inc. and affiliates. All Rights Reserved
|
| 2 |
+
|
| 3 |
+
import numpy as np
|
| 4 |
+
import torch
|
| 5 |
+
import torch.nn.functional as F
|
| 6 |
+
from numpy.typing import NDArray
|
| 7 |
+
|
| 8 |
+
from sam3.model.edt import edt_triton
|
| 9 |
+
|
| 10 |
+
|
| 11 |
+
def sample_box_points(
|
| 12 |
+
masks: torch.Tensor,
|
| 13 |
+
noise: float = 0.1, # SAM default
|
| 14 |
+
noise_bound: int = 20, # SAM default
|
| 15 |
+
top_left_label: int = 2,
|
| 16 |
+
bottom_right_label: int = 3,
|
| 17 |
+
) -> tuple[NDArray, NDArray]:
|
| 18 |
+
"""
|
| 19 |
+
Sample a noised version of the top left and bottom right corners of a given `bbox`
|
| 20 |
+
|
| 21 |
+
Inputs:
|
| 22 |
+
- masks: [B, 1, H, W] tensor
|
| 23 |
+
- noise: noise as a fraction of box width and height, dtype=float
|
| 24 |
+
- noise_bound: maximum amount of noise (in pure pixels), dtype=int
|
| 25 |
+
|
| 26 |
+
Returns:
|
| 27 |
+
- box_coords: [B, num_pt, 2], contains (x, y) coordinates of top left and bottom right box corners, dtype=torch.float
|
| 28 |
+
- box_labels: [B, num_pt], label 2 is reserverd for top left and 3 for bottom right corners, dtype=torch.int32
|
| 29 |
+
"""
|
| 30 |
+
device = masks.device
|
| 31 |
+
box_coords = mask_to_box(masks)
|
| 32 |
+
B, _, H, W = masks.shape
|
| 33 |
+
box_labels = torch.tensor(
|
| 34 |
+
[top_left_label, bottom_right_label], dtype=torch.int, device=device
|
| 35 |
+
).repeat(B)
|
| 36 |
+
if noise > 0.0:
|
| 37 |
+
if not isinstance(noise_bound, torch.Tensor):
|
| 38 |
+
noise_bound = torch.tensor(noise_bound, device=device)
|
| 39 |
+
bbox_w = box_coords[..., 2] - box_coords[..., 0]
|
| 40 |
+
bbox_h = box_coords[..., 3] - box_coords[..., 1]
|
| 41 |
+
max_dx = torch.min(bbox_w * noise, noise_bound)
|
| 42 |
+
max_dy = torch.min(bbox_h * noise, noise_bound)
|
| 43 |
+
box_noise = 2 * torch.rand(B, 1, 4, device=device) - 1
|
| 44 |
+
box_noise = box_noise * torch.stack((max_dx, max_dy, max_dx, max_dy), dim=-1)
|
| 45 |
+
|
| 46 |
+
box_coords = box_coords + box_noise
|
| 47 |
+
img_bounds = (
|
| 48 |
+
torch.tensor([W, H, W, H], device=device) - 1
|
| 49 |
+
) # uncentered pixel coords
|
| 50 |
+
box_coords.clamp_(torch.zeros_like(img_bounds), img_bounds) # In place clamping
|
| 51 |
+
|
| 52 |
+
box_coords = box_coords.reshape(-1, 2, 2) # always 2 points
|
| 53 |
+
box_labels = box_labels.reshape(-1, 2)
|
| 54 |
+
return box_coords, box_labels
|
| 55 |
+
|
| 56 |
+
|
| 57 |
+
def mask_to_box(masks: torch.Tensor):
|
| 58 |
+
"""
|
| 59 |
+
compute bounding box given an input mask
|
| 60 |
+
|
| 61 |
+
Inputs:
|
| 62 |
+
- masks: [B, 1, H, W] tensor
|
| 63 |
+
|
| 64 |
+
Returns:
|
| 65 |
+
- box_coords: [B, 1, 4], contains (x, y) coordinates of top left and bottom right box corners, dtype=torch.Tensor
|
| 66 |
+
"""
|
| 67 |
+
B, _, h, w = masks.shape
|
| 68 |
+
device = masks.device
|
| 69 |
+
mask_area = masks.sum(dim=(-1, -2))
|
| 70 |
+
xs = torch.arange(w, device=device, dtype=torch.int32)
|
| 71 |
+
ys = torch.arange(h, device=device, dtype=torch.int32)
|
| 72 |
+
grid_xs, grid_ys = torch.meshgrid(xs, ys, indexing="xy")
|
| 73 |
+
grid_xs = grid_xs[None, None, ...].expand(B, 1, h, w)
|
| 74 |
+
grid_ys = grid_ys[None, None, ...].expand(B, 1, h, w)
|
| 75 |
+
min_xs, _ = torch.min(torch.where(masks, grid_xs, w).flatten(-2), dim=-1)
|
| 76 |
+
max_xs, _ = torch.max(torch.where(masks, grid_xs, -1).flatten(-2), dim=-1)
|
| 77 |
+
min_ys, _ = torch.min(torch.where(masks, grid_ys, h).flatten(-2), dim=-1)
|
| 78 |
+
max_ys, _ = torch.max(torch.where(masks, grid_ys, -1).flatten(-2), dim=-1)
|
| 79 |
+
bbox_coords = torch.stack((min_xs, min_ys, max_xs, max_ys), dim=-1)
|
| 80 |
+
bbox_coords = torch.where(
|
| 81 |
+
mask_area[..., None] > 0, bbox_coords, torch.zeros_like(bbox_coords)
|
| 82 |
+
)
|
| 83 |
+
return bbox_coords
|
| 84 |
+
|
| 85 |
+
|
| 86 |
+
def sample_random_points_from_errors(gt_masks, pred_masks, num_pt=1):
|
| 87 |
+
"""
|
| 88 |
+
Sample `num_pt` random points (along with their labels) independently from the error regions.
|
| 89 |
+
|
| 90 |
+
Inputs:
|
| 91 |
+
- gt_masks: [B, 1, H_im, W_im] masks, dtype=torch.bool
|
| 92 |
+
- pred_masks: [B, 1, H_im, W_im] masks, dtype=torch.bool or None
|
| 93 |
+
- num_pt: int, number of points to sample independently for each of the B error maps
|
| 94 |
+
|
| 95 |
+
Outputs:
|
| 96 |
+
- points: [B, num_pt, 2], dtype=torch.float, contains (x, y) coordinates of each sampled point
|
| 97 |
+
- labels: [B, num_pt], dtype=torch.int32, where 1 means positive clicks and 0 means
|
| 98 |
+
negative clicks
|
| 99 |
+
"""
|
| 100 |
+
if pred_masks is None: # if pred_masks is not provided, treat it as empty
|
| 101 |
+
pred_masks = torch.zeros_like(gt_masks)
|
| 102 |
+
assert gt_masks.dtype == torch.bool and gt_masks.size(1) == 1
|
| 103 |
+
assert pred_masks.dtype == torch.bool and pred_masks.shape == gt_masks.shape
|
| 104 |
+
assert num_pt >= 0
|
| 105 |
+
|
| 106 |
+
B, _, H_im, W_im = gt_masks.shape
|
| 107 |
+
device = gt_masks.device
|
| 108 |
+
|
| 109 |
+
# false positive region, a new point sampled in this region should have
|
| 110 |
+
# negative label to correct the FP error
|
| 111 |
+
fp_masks = ~gt_masks & pred_masks
|
| 112 |
+
# false negative region, a new point sampled in this region should have
|
| 113 |
+
# positive label to correct the FN error
|
| 114 |
+
fn_masks = gt_masks & ~pred_masks
|
| 115 |
+
# whether the prediction completely match the ground-truth on each mask
|
| 116 |
+
all_correct = torch.all((gt_masks == pred_masks).flatten(2), dim=2)
|
| 117 |
+
all_correct = all_correct[..., None, None]
|
| 118 |
+
|
| 119 |
+
# channel 0 is FP map, while channel 1 is FN map
|
| 120 |
+
pts_noise = torch.rand(B, num_pt, H_im, W_im, 2, device=device)
|
| 121 |
+
# sample a negative new click from FP region or a positive new click
|
| 122 |
+
# from FN region, depend on where the maximum falls,
|
| 123 |
+
# and in case the predictions are all correct (no FP or FN), we just
|
| 124 |
+
# sample a negative click from the background region
|
| 125 |
+
pts_noise[..., 0] *= fp_masks | (all_correct & ~gt_masks)
|
| 126 |
+
pts_noise[..., 1] *= fn_masks
|
| 127 |
+
pts_idx = pts_noise.flatten(2).argmax(dim=2)
|
| 128 |
+
labels = (pts_idx % 2).to(torch.int32)
|
| 129 |
+
pts_idx = pts_idx // 2
|
| 130 |
+
pts_x = pts_idx % W_im
|
| 131 |
+
pts_y = pts_idx // W_im
|
| 132 |
+
points = torch.stack([pts_x, pts_y], dim=2).to(torch.float)
|
| 133 |
+
return points, labels
|
| 134 |
+
|
| 135 |
+
|
| 136 |
+
def sample_one_point_from_error_center(gt_masks, pred_masks, padding=True):
|
| 137 |
+
"""
|
| 138 |
+
Sample 1 random point (along with its label) from the center of each error region,
|
| 139 |
+
that is, the point with the largest distance to the boundary of each error region.
|
| 140 |
+
This is the RITM sampling method from https://github.com/saic-vul/ritm_interactive_segmentation/blob/master/isegm/inference/clicker.py
|
| 141 |
+
|
| 142 |
+
Inputs:
|
| 143 |
+
- gt_masks: [B, 1, H_im, W_im] masks, dtype=torch.bool
|
| 144 |
+
- pred_masks: [B, 1, H_im, W_im] masks, dtype=torch.bool or None
|
| 145 |
+
- padding: if True, pad with boundary of 1 px for distance transform
|
| 146 |
+
|
| 147 |
+
Outputs:
|
| 148 |
+
- points: [B, 1, 2], dtype=torch.float, contains (x, y) coordinates of each sampled point
|
| 149 |
+
- labels: [B, 1], dtype=torch.int32, where 1 means positive clicks and 0 means negative clicks
|
| 150 |
+
"""
|
| 151 |
+
if pred_masks is None:
|
| 152 |
+
pred_masks = torch.zeros_like(gt_masks)
|
| 153 |
+
assert gt_masks.dtype == torch.bool and gt_masks.size(1) == 1
|
| 154 |
+
assert pred_masks.dtype == torch.bool and pred_masks.shape == gt_masks.shape
|
| 155 |
+
|
| 156 |
+
B, _, H, W = gt_masks.shape
|
| 157 |
+
|
| 158 |
+
# false positive region, a new point sampled in this region should have
|
| 159 |
+
# negative label to correct the FP error
|
| 160 |
+
fp_masks = (~gt_masks & pred_masks).squeeze(1)
|
| 161 |
+
# false negative region, a new point sampled in this region should have
|
| 162 |
+
# positive label to correct the FN error
|
| 163 |
+
fn_masks = (gt_masks & ~pred_masks).squeeze(1)
|
| 164 |
+
|
| 165 |
+
if padding:
|
| 166 |
+
padded_fp_masks = torch.zeros(
|
| 167 |
+
B, H + 2, W + 2, dtype=fp_masks.dtype, device=fp_masks.device
|
| 168 |
+
)
|
| 169 |
+
padded_fp_masks[:, 1 : H + 1, 1 : W + 1] = fp_masks
|
| 170 |
+
padded_fn_masks = torch.zeros(
|
| 171 |
+
B, H + 2, W + 2, dtype=fp_masks.dtype, device=fp_masks.device
|
| 172 |
+
)
|
| 173 |
+
padded_fn_masks[:, 1 : H + 1, 1 : W + 1] = fn_masks
|
| 174 |
+
else:
|
| 175 |
+
padded_fp_masks = fp_masks
|
| 176 |
+
padded_fn_masks = fn_masks
|
| 177 |
+
|
| 178 |
+
fn_mask_dt = edt_triton(padded_fn_masks)
|
| 179 |
+
fp_mask_dt = edt_triton(padded_fp_masks)
|
| 180 |
+
if padding:
|
| 181 |
+
fn_mask_dt = fn_mask_dt[:, 1:-1, 1:-1]
|
| 182 |
+
fp_mask_dt = fp_mask_dt[:, 1:-1, 1:-1]
|
| 183 |
+
|
| 184 |
+
fn_max, fn_argmax = fn_mask_dt.reshape(B, -1).max(dim=-1)
|
| 185 |
+
fp_max, fp_argmax = fp_mask_dt.reshape(B, -1).max(dim=-1)
|
| 186 |
+
is_positive = fn_max > fp_max
|
| 187 |
+
chosen = torch.where(is_positive, fn_argmax, fp_argmax)
|
| 188 |
+
points_x = chosen % W
|
| 189 |
+
points_y = chosen // W
|
| 190 |
+
|
| 191 |
+
labels = is_positive.long()
|
| 192 |
+
points = torch.stack([points_x, points_y], -1)
|
| 193 |
+
return points.unsqueeze(1), labels.unsqueeze(1)
|
| 194 |
+
|
| 195 |
+
|
| 196 |
+
def sample_one_point_from_error_center_slow(gt_masks, pred_masks, padding=True):
|
| 197 |
+
"""
|
| 198 |
+
Sample 1 random point (along with its label) from the center of each error region,
|
| 199 |
+
that is, the point with the largest distance to the boundary of each error region.
|
| 200 |
+
This is the RITM sampling method from https://github.com/saic-vul/ritm_interactive_segmentation/blob/master/isegm/inference/clicker.py
|
| 201 |
+
|
| 202 |
+
Inputs:
|
| 203 |
+
- gt_masks: [B, 1, H_im, W_im] masks, dtype=torch.bool
|
| 204 |
+
- pred_masks: [B, 1, H_im, W_im] masks, dtype=torch.bool or None
|
| 205 |
+
- padding: if True, pad with boundary of 1 px for distance transform
|
| 206 |
+
|
| 207 |
+
Outputs:
|
| 208 |
+
- points: [B, 1, 2], dtype=torch.float, contains (x, y) coordinates of each sampled point
|
| 209 |
+
- labels: [B, 1], dtype=torch.int32, where 1 means positive clicks and 0 means negative clicks
|
| 210 |
+
"""
|
| 211 |
+
import cv2 # delay OpenCV import to avoid unnecessary dependency
|
| 212 |
+
|
| 213 |
+
if pred_masks is None:
|
| 214 |
+
pred_masks = torch.zeros_like(gt_masks)
|
| 215 |
+
assert gt_masks.dtype == torch.bool and gt_masks.size(1) == 1
|
| 216 |
+
assert pred_masks.dtype == torch.bool and pred_masks.shape == gt_masks.shape
|
| 217 |
+
|
| 218 |
+
B, _, _, W_im = gt_masks.shape
|
| 219 |
+
device = gt_masks.device
|
| 220 |
+
|
| 221 |
+
# false positive region, a new point sampled in this region should have
|
| 222 |
+
# negative label to correct the FP error
|
| 223 |
+
fp_masks = ~gt_masks & pred_masks
|
| 224 |
+
# false negative region, a new point sampled in this region should have
|
| 225 |
+
# positive label to correct the FN error
|
| 226 |
+
fn_masks = gt_masks & ~pred_masks
|
| 227 |
+
|
| 228 |
+
fp_masks = fp_masks.cpu().numpy()
|
| 229 |
+
fn_masks = fn_masks.cpu().numpy()
|
| 230 |
+
points = torch.zeros(B, 1, 2, dtype=torch.float)
|
| 231 |
+
labels = torch.ones(B, 1, dtype=torch.int32)
|
| 232 |
+
for b in range(B):
|
| 233 |
+
fn_mask = fn_masks[b, 0]
|
| 234 |
+
fp_mask = fp_masks[b, 0]
|
| 235 |
+
if padding:
|
| 236 |
+
fn_mask = np.pad(fn_mask, ((1, 1), (1, 1)), "constant")
|
| 237 |
+
fp_mask = np.pad(fp_mask, ((1, 1), (1, 1)), "constant")
|
| 238 |
+
# compute the distance of each point in FN/FP region to its boundary
|
| 239 |
+
fn_mask_dt = cv2.distanceTransform(fn_mask.astype(np.uint8), cv2.DIST_L2, 0)
|
| 240 |
+
fp_mask_dt = cv2.distanceTransform(fp_mask.astype(np.uint8), cv2.DIST_L2, 0)
|
| 241 |
+
if padding:
|
| 242 |
+
fn_mask_dt = fn_mask_dt[1:-1, 1:-1]
|
| 243 |
+
fp_mask_dt = fp_mask_dt[1:-1, 1:-1]
|
| 244 |
+
|
| 245 |
+
# take the point in FN/FP region with the largest distance to its boundary
|
| 246 |
+
fn_mask_dt_flat = fn_mask_dt.reshape(-1)
|
| 247 |
+
fp_mask_dt_flat = fp_mask_dt.reshape(-1)
|
| 248 |
+
fn_argmax = np.argmax(fn_mask_dt_flat)
|
| 249 |
+
fp_argmax = np.argmax(fp_mask_dt_flat)
|
| 250 |
+
is_positive = fn_mask_dt_flat[fn_argmax] > fp_mask_dt_flat[fp_argmax]
|
| 251 |
+
pt_idx = fn_argmax if is_positive else fp_argmax
|
| 252 |
+
points[b, 0, 0] = pt_idx % W_im # x
|
| 253 |
+
points[b, 0, 1] = pt_idx // W_im # y
|
| 254 |
+
labels[b, 0] = int(is_positive)
|
| 255 |
+
|
| 256 |
+
points = points.to(device)
|
| 257 |
+
labels = labels.to(device)
|
| 258 |
+
return points, labels
|
| 259 |
+
|
| 260 |
+
|
| 261 |
+
def get_next_point(gt_masks, pred_masks, method):
|
| 262 |
+
if method == "uniform":
|
| 263 |
+
return sample_random_points_from_errors(gt_masks, pred_masks)
|
| 264 |
+
elif method == "center":
|
| 265 |
+
return sample_one_point_from_error_center(gt_masks, pred_masks)
|
| 266 |
+
else:
|
| 267 |
+
raise ValueError(f"unknown sampling method {method}")
|
| 268 |
+
|
| 269 |
+
|
| 270 |
+
def select_closest_cond_frames(
|
| 271 |
+
frame_idx, cond_frame_outputs, max_cond_frame_num, keep_first_cond_frame=False
|
| 272 |
+
):
|
| 273 |
+
"""
|
| 274 |
+
Select up to `max_cond_frame_num` conditioning frames from `cond_frame_outputs`
|
| 275 |
+
that are temporally closest to the current frame at `frame_idx`. Here, we take
|
| 276 |
+
- a) the closest conditioning frame before `frame_idx` (if any);
|
| 277 |
+
- b) the closest conditioning frame after `frame_idx` (if any);
|
| 278 |
+
- c) any other temporally closest conditioning frames until reaching a total
|
| 279 |
+
of `max_cond_frame_num` conditioning frames.
|
| 280 |
+
|
| 281 |
+
Outputs:
|
| 282 |
+
- selected_outputs: selected items (keys & values) from `cond_frame_outputs`.
|
| 283 |
+
- unselected_outputs: items (keys & values) not selected in `cond_frame_outputs`.
|
| 284 |
+
"""
|
| 285 |
+
if max_cond_frame_num == -1 or len(cond_frame_outputs) <= max_cond_frame_num:
|
| 286 |
+
selected_outputs = cond_frame_outputs
|
| 287 |
+
unselected_outputs = {}
|
| 288 |
+
else:
|
| 289 |
+
assert max_cond_frame_num >= 2, "we should allow using 2+ conditioning frames"
|
| 290 |
+
selected_outputs = {}
|
| 291 |
+
if keep_first_cond_frame:
|
| 292 |
+
idx_first = min(
|
| 293 |
+
(t for t in cond_frame_outputs if t < frame_idx), default=None
|
| 294 |
+
)
|
| 295 |
+
if idx_first is None:
|
| 296 |
+
# Maybe we are tracking in reverse
|
| 297 |
+
idx_first = max(
|
| 298 |
+
(t for t in cond_frame_outputs if t > frame_idx), default=None
|
| 299 |
+
)
|
| 300 |
+
if idx_first is not None:
|
| 301 |
+
selected_outputs[idx_first] = cond_frame_outputs[idx_first]
|
| 302 |
+
# the closest conditioning frame before `frame_idx` (if any)
|
| 303 |
+
idx_before = max((t for t in cond_frame_outputs if t < frame_idx), default=None)
|
| 304 |
+
if idx_before is not None:
|
| 305 |
+
selected_outputs[idx_before] = cond_frame_outputs[idx_before]
|
| 306 |
+
|
| 307 |
+
# the closest conditioning frame after `frame_idx` (if any)
|
| 308 |
+
idx_after = min((t for t in cond_frame_outputs if t >= frame_idx), default=None)
|
| 309 |
+
if idx_after is not None:
|
| 310 |
+
selected_outputs[idx_after] = cond_frame_outputs[idx_after]
|
| 311 |
+
|
| 312 |
+
# add other temporally closest conditioning frames until reaching a total
|
| 313 |
+
# of `max_cond_frame_num` conditioning frames.
|
| 314 |
+
num_remain = max_cond_frame_num - len(selected_outputs)
|
| 315 |
+
inds_remain = sorted(
|
| 316 |
+
(t for t in cond_frame_outputs if t not in selected_outputs),
|
| 317 |
+
key=lambda x: abs(x - frame_idx),
|
| 318 |
+
)[:num_remain]
|
| 319 |
+
selected_outputs.update((t, cond_frame_outputs[t]) for t in inds_remain)
|
| 320 |
+
unselected_outputs = {
|
| 321 |
+
t: v for t, v in cond_frame_outputs.items() if t not in selected_outputs
|
| 322 |
+
}
|
| 323 |
+
|
| 324 |
+
return selected_outputs, unselected_outputs
|
| 325 |
+
|
| 326 |
+
|
| 327 |
+
def get_1d_sine_pe(pos_inds, dim, temperature=10000):
|
| 328 |
+
"""
|
| 329 |
+
Get 1D sine positional embedding as in the original Transformer paper.
|
| 330 |
+
"""
|
| 331 |
+
pe_dim = dim // 2
|
| 332 |
+
dim_t = torch.arange(pe_dim, dtype=torch.float32, device=pos_inds.device)
|
| 333 |
+
dim_t = temperature ** (2 * (dim_t // 2) / pe_dim)
|
| 334 |
+
|
| 335 |
+
pos_embed = pos_inds.unsqueeze(-1) / dim_t
|
| 336 |
+
pos_embed = torch.cat([pos_embed.sin(), pos_embed.cos()], dim=-1)
|
| 337 |
+
return pos_embed
|
| 338 |
+
|
| 339 |
+
|
| 340 |
+
def get_best_gt_match_from_multimasks(pred_multimasks, gt_masks, pred_scores=None):
|
| 341 |
+
"""
|
| 342 |
+
Get the mask with the best match to GT masks (based on IoU) from pred_multimasks.
|
| 343 |
+
Optionally, use `pred_scores` to break ties in case all IoUs are zeros.
|
| 344 |
+
"""
|
| 345 |
+
assert pred_multimasks.ndim == 4 and gt_masks.ndim == 4
|
| 346 |
+
if pred_multimasks.size(1) == 1:
|
| 347 |
+
return pred_multimasks # only a single mask channel, nothing to select
|
| 348 |
+
|
| 349 |
+
pred_multimasks_binary = pred_multimasks > 0
|
| 350 |
+
area_i = torch.sum(pred_multimasks_binary & gt_masks, dim=(2, 3)).float()
|
| 351 |
+
area_u = torch.sum(pred_multimasks_binary | gt_masks, dim=(2, 3)).float()
|
| 352 |
+
ious = area_i / torch.clamp(area_u, min=1.0)
|
| 353 |
+
|
| 354 |
+
# In case all IoUs are zeros (e.g. because the GT mask is empty), use pred_scores
|
| 355 |
+
# to break ties and select the best mask
|
| 356 |
+
if pred_scores is not None:
|
| 357 |
+
has_nonzero_ious = torch.any(ious > 0).expand_as(ious)
|
| 358 |
+
scores = torch.where(has_nonzero_ious, ious, pred_scores)
|
| 359 |
+
else:
|
| 360 |
+
scores = ious
|
| 361 |
+
|
| 362 |
+
# Finally, take the best mask prediction (with the highest score)
|
| 363 |
+
best_scores_inds = torch.argmax(scores, dim=-1)
|
| 364 |
+
batch_inds = torch.arange(scores.size(0), device=scores.device)
|
| 365 |
+
best_pred_mask = pred_multimasks[batch_inds, best_scores_inds].unsqueeze(1)
|
| 366 |
+
return best_pred_mask
|
| 367 |
+
|
| 368 |
+
|
| 369 |
+
def fill_holes_in_mask_scores(mask, max_area, fill_holes=True, remove_sprinkles=True):
|
| 370 |
+
"""
|
| 371 |
+
A post processor to fill small holes in mask scores with area under `max_area`.
|
| 372 |
+
Holes are those small connected components in either background or foreground.
|
| 373 |
+
|
| 374 |
+
Note that it relies on the "cc_torch" package to find connected components fast. You can
|
| 375 |
+
install it via the following command (`TORCH_CUDA_ARCH_LIST=8.0` is for A100 GPUs):
|
| 376 |
+
```
|
| 377 |
+
pip uninstall -y cc_torch; TORCH_CUDA_ARCH_LIST=8.0 9.0 pip install git+https://github.com/ronghanghu/cc_torch
|
| 378 |
+
```
|
| 379 |
+
Otherwise, it will fallback to a slightly slower triton implementation, or skimage if the tensor is on cpu
|
| 380 |
+
"""
|
| 381 |
+
|
| 382 |
+
if max_area <= 0:
|
| 383 |
+
return mask # nothing to fill in this case
|
| 384 |
+
|
| 385 |
+
if fill_holes:
|
| 386 |
+
# We remove small connected components in background by changing them to foreground
|
| 387 |
+
# with a small positive mask score (0.1).
|
| 388 |
+
mask_bg = mask <= 0
|
| 389 |
+
bg_area_thresh = max_area
|
| 390 |
+
_, areas_bg = _get_connected_components_with_padding(mask_bg)
|
| 391 |
+
small_components_bg = mask_bg & (areas_bg <= bg_area_thresh)
|
| 392 |
+
mask = torch.where(small_components_bg, 0.1, mask)
|
| 393 |
+
|
| 394 |
+
if remove_sprinkles:
|
| 395 |
+
# We remove small connected components in foreground by changing them to background
|
| 396 |
+
# with a small negative mask score (-0.1). Here we only remove connected components
|
| 397 |
+
# whose areas are under both `max_area` and half of the entire mask's area. This
|
| 398 |
+
# removes sprinkles while avoids filtering out tiny objects that we want to track.
|
| 399 |
+
mask_fg = mask > 0
|
| 400 |
+
fg_area_thresh = torch.sum(mask_fg, dim=(2, 3), keepdim=True, dtype=torch.int32)
|
| 401 |
+
fg_area_thresh.floor_divide_(2).clamp_(max=max_area)
|
| 402 |
+
_, areas_fg = _get_connected_components_with_padding(mask_fg)
|
| 403 |
+
small_components_fg = mask_fg & (areas_fg <= fg_area_thresh)
|
| 404 |
+
mask = torch.where(small_components_fg, -0.1, mask)
|
| 405 |
+
return mask
|
| 406 |
+
|
| 407 |
+
|
| 408 |
+
def _get_connected_components_with_padding(mask):
|
| 409 |
+
"""Get connected components from masks (possibly padding them to an even size)."""
|
| 410 |
+
from sam3.perflib.connected_components import connected_components
|
| 411 |
+
|
| 412 |
+
mask = mask.to(torch.uint8)
|
| 413 |
+
_, _, H, W = mask.shape
|
| 414 |
+
# make sure both height and width are even (to be compatible with cc_torch)
|
| 415 |
+
pad_h = H % 2
|
| 416 |
+
pad_w = W % 2
|
| 417 |
+
if pad_h == 0 and pad_w == 0:
|
| 418 |
+
labels, counts = connected_components(mask)
|
| 419 |
+
else:
|
| 420 |
+
# pad the mask to make its height and width even
|
| 421 |
+
# padding format is (padding_left,padding_right,padding_top,padding_bottom)
|
| 422 |
+
mask_pad = F.pad(mask, (0, pad_w, 0, pad_h), mode="constant", value=0)
|
| 423 |
+
labels, counts = connected_components(mask_pad)
|
| 424 |
+
labels = labels[:, :, :H, :W]
|
| 425 |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
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
# Copyright (c) Meta Platforms, Inc. and affiliates. All Rights Reserved
|
| 2 |
+
|
| 3 |
+
import logging
|
| 4 |
+
from collections import OrderedDict
|
| 5 |
+
|
| 6 |
+
import torch
|
| 7 |
+
|
| 8 |
+
from sam3.model.sam3_tracker_base import concat_points, NO_OBJ_SCORE, Sam3TrackerBase
|
| 9 |
+
from sam3.model.sam3_tracker_utils import fill_holes_in_mask_scores
|
| 10 |
+
from sam3.model.utils.sam2_utils import load_video_frames
|
| 11 |
+
from tqdm.auto import tqdm
|
| 12 |
+
|
| 13 |
+
|
| 14 |
+
class Sam3TrackerPredictor(Sam3TrackerBase):
|
| 15 |
+
"""
|
| 16 |
+
The demo class that extends the `Sam3TrackerBase` to handle user interactions
|
| 17 |
+
and manage inference states, with support for multi-object tracking.
|
| 18 |
+
"""
|
| 19 |
+
|
| 20 |
+
def __init__(
|
| 21 |
+
self,
|
| 22 |
+
# whether to clear non-conditioning memory of the surrounding frames (which may contain outdated information) after adding correction clicks;
|
| 23 |
+
# note that this would only apply to *single-object tracking* unless `clear_non_cond_mem_for_multi_obj` is also set to True)
|
| 24 |
+
clear_non_cond_mem_around_input=False,
|
| 25 |
+
# whether to also clear non-conditioning memory of the surrounding frames (only effective when `clear_non_cond_mem_around_input` is True).
|
| 26 |
+
clear_non_cond_mem_for_multi_obj=False,
|
| 27 |
+
# 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)
|
| 28 |
+
fill_hole_area=0,
|
| 29 |
+
# 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)
|
| 30 |
+
# and ignore the `start_frame_idx` passed to `propagate_in_video`
|
| 31 |
+
always_start_from_first_ann_frame=False,
|
| 32 |
+
# the maximum number of points to be used in the prompt encoder, which reduce the domain gap between training (that only has 8 points)
|
| 33 |
+
# - if it's set to a positive integer, we only take the `max_point_num_in_prompt_enc//2` points and
|
| 34 |
+
# the last `(max_point_num_in_prompt_enc - max_point_num_in_prompt_enc//2)` points in the prompt encoder
|
| 35 |
+
# - if it's set to 0 or negative, this option is turned off and we use all points in the prompt encoder
|
| 36 |
+
max_point_num_in_prompt_enc=16,
|
| 37 |
+
non_overlap_masks_for_output=True,
|
| 38 |
+
# checkpoint_file=None,
|
| 39 |
+
**kwargs,
|
| 40 |
+
):
|
| 41 |
+
super().__init__(**kwargs)
|
| 42 |
+
self.clear_non_cond_mem_around_input = clear_non_cond_mem_around_input
|
| 43 |
+
self.clear_non_cond_mem_for_multi_obj = clear_non_cond_mem_for_multi_obj
|
| 44 |
+
self.fill_hole_area = fill_hole_area
|
| 45 |
+
self.always_start_from_first_ann_frame = always_start_from_first_ann_frame
|
| 46 |
+
self.max_point_num_in_prompt_enc = max_point_num_in_prompt_enc
|
| 47 |
+
self.non_overlap_masks_for_output = non_overlap_masks_for_output
|
| 48 |
+
|
| 49 |
+
self.bf16_context = torch.autocast(device_type="cuda", dtype=torch.bfloat16)
|
| 50 |
+
self.bf16_context.__enter__() # keep using for the entire model process
|
| 51 |
+
|
| 52 |
+
self.iter_use_prev_mask_pred = True
|
| 53 |
+
self.add_all_frames_to_correct_as_cond = True
|
| 54 |
+
|
| 55 |
+
@torch.inference_mode()
|
| 56 |
+
def init_state(
|
| 57 |
+
self,
|
| 58 |
+
video_height=None,
|
| 59 |
+
video_width=None,
|
| 60 |
+
num_frames=None,
|
| 61 |
+
video_path=None,
|
| 62 |
+
cached_features=None,
|
| 63 |
+
offload_video_to_cpu=False,
|
| 64 |
+
offload_state_to_cpu=False,
|
| 65 |
+
async_loading_frames=False,
|
| 66 |
+
):
|
| 67 |
+
"""Initialize a inference state."""
|
| 68 |
+
inference_state = {}
|
| 69 |
+
# whether to offload the video frames to CPU memory
|
| 70 |
+
# turning on this option saves the GPU memory with only a very small overhead
|
| 71 |
+
inference_state["offload_video_to_cpu"] = offload_video_to_cpu
|
| 72 |
+
# whether to offload the inference state to CPU memory
|
| 73 |
+
# turning on this option saves the GPU memory at the cost of a lower tracking fps
|
| 74 |
+
# (e.g. in a test case of 768x768 model, fps dropped from 27 to 24 when tracking one object
|
| 75 |
+
# and from 24 to 21 when tracking two objects)
|
| 76 |
+
inference_state["offload_state_to_cpu"] = offload_state_to_cpu
|
| 77 |
+
inference_state["device"] = self.device
|
| 78 |
+
if offload_state_to_cpu:
|
| 79 |
+
inference_state["storage_device"] = torch.device("cpu")
|
| 80 |
+
else:
|
| 81 |
+
inference_state["storage_device"] = torch.device("cuda")
|
| 82 |
+
|
| 83 |
+
if video_path is not None:
|
| 84 |
+
images, video_height, video_width = load_video_frames(
|
| 85 |
+
video_path=video_path,
|
| 86 |
+
image_size=self.image_size,
|
| 87 |
+
offload_video_to_cpu=offload_video_to_cpu,
|
| 88 |
+
async_loading_frames=async_loading_frames,
|
| 89 |
+
compute_device=inference_state["storage_device"],
|
| 90 |
+
)
|
| 91 |
+
inference_state["images"] = images
|
| 92 |
+
inference_state["num_frames"] = len(images)
|
| 93 |
+
inference_state["video_height"] = video_height
|
| 94 |
+
inference_state["video_width"] = video_width
|
| 95 |
+
else:
|
| 96 |
+
# the original video height and width, used for resizing final output scores
|
| 97 |
+
inference_state["video_height"] = video_height
|
| 98 |
+
inference_state["video_width"] = video_width
|
| 99 |
+
inference_state["num_frames"] = num_frames
|
| 100 |
+
# inputs on each frame
|
| 101 |
+
inference_state["point_inputs_per_obj"] = {}
|
| 102 |
+
inference_state["mask_inputs_per_obj"] = {}
|
| 103 |
+
# visual features on a small number of recently visited frames for quick interactions
|
| 104 |
+
inference_state["cached_features"] = (
|
| 105 |
+
{} if cached_features is None else cached_features
|
| 106 |
+
)
|
| 107 |
+
# values that don't change across frames (so we only need to hold one copy of them)
|
| 108 |
+
inference_state["constants"] = {}
|
| 109 |
+
# mapping between client-side object id and model-side object index
|
| 110 |
+
inference_state["obj_id_to_idx"] = OrderedDict()
|
| 111 |
+
inference_state["obj_idx_to_id"] = OrderedDict()
|
| 112 |
+
inference_state["obj_ids"] = []
|
| 113 |
+
# A storage to hold the model's tracking results and states on each frame
|
| 114 |
+
inference_state["output_dict"] = {
|
| 115 |
+
"cond_frame_outputs": {}, # dict containing {frame_idx: <out>}
|
| 116 |
+
"non_cond_frame_outputs": {}, # dict containing {frame_idx: <out>}
|
| 117 |
+
}
|
| 118 |
+
# The index of the frame that received the first annotation
|
| 119 |
+
inference_state["first_ann_frame_idx"] = None
|
| 120 |
+
# Slice (view) of each object tracking results, sharing the same memory with "output_dict"
|
| 121 |
+
inference_state["output_dict_per_obj"] = {}
|
| 122 |
+
# A temporary storage to hold new outputs when user interact with a frame
|
| 123 |
+
# to add clicks or mask (it's merged into "output_dict" before propagation starts)
|
| 124 |
+
inference_state["temp_output_dict_per_obj"] = {}
|
| 125 |
+
# Frames that already holds consolidated outputs from click or mask inputs
|
| 126 |
+
# (we directly use their consolidated outputs during tracking)
|
| 127 |
+
inference_state["consolidated_frame_inds"] = {
|
| 128 |
+
"cond_frame_outputs": set(), # set containing frame indices
|
| 129 |
+
"non_cond_frame_outputs": set(), # set containing frame indices
|
| 130 |
+
}
|
| 131 |
+
# metadata for each tracking frame (e.g. which direction it's tracked)
|
| 132 |
+
inference_state["tracking_has_started"] = False
|
| 133 |
+
inference_state["frames_already_tracked"] = {}
|
| 134 |
+
self.clear_all_points_in_video(inference_state)
|
| 135 |
+
return inference_state
|
| 136 |
+
|
| 137 |
+
def _obj_id_to_idx(self, inference_state, obj_id):
|
| 138 |
+
"""Map client-side object id to model-side object index."""
|
| 139 |
+
obj_idx = inference_state["obj_id_to_idx"].get(obj_id, None)
|
| 140 |
+
if obj_idx is not None:
|
| 141 |
+
return obj_idx
|
| 142 |
+
|
| 143 |
+
# This is a new object id not sent to the server before. We only allow adding
|
| 144 |
+
# new objects *before* the tracking starts.
|
| 145 |
+
allow_new_object = not inference_state["tracking_has_started"]
|
| 146 |
+
if allow_new_object:
|
| 147 |
+
# get the next object slot
|
| 148 |
+
obj_idx = len(inference_state["obj_id_to_idx"])
|
| 149 |
+
inference_state["obj_id_to_idx"][obj_id] = obj_idx
|
| 150 |
+
inference_state["obj_idx_to_id"][obj_idx] = obj_id
|
| 151 |
+
inference_state["obj_ids"] = list(inference_state["obj_id_to_idx"])
|
| 152 |
+
# set up input and output structures for this object
|
| 153 |
+
inference_state["point_inputs_per_obj"][obj_idx] = {}
|
| 154 |
+
inference_state["mask_inputs_per_obj"][obj_idx] = {}
|
| 155 |
+
inference_state["output_dict_per_obj"][obj_idx] = {
|
| 156 |
+
"cond_frame_outputs": {}, # dict containing {frame_idx: <out>}
|
| 157 |
+
"non_cond_frame_outputs": {}, # dict containing {frame_idx: <out>}
|
| 158 |
+
}
|
| 159 |
+
inference_state["temp_output_dict_per_obj"][obj_idx] = {
|
| 160 |
+
"cond_frame_outputs": {}, # dict containing {frame_idx: <out>}
|
| 161 |
+
"non_cond_frame_outputs": {}, # dict containing {frame_idx: <out>}
|
| 162 |
+
}
|
| 163 |
+
return obj_idx
|
| 164 |
+
else:
|
| 165 |
+
raise RuntimeError(
|
| 166 |
+
f"Cannot add new object id {obj_id} after tracking starts. "
|
| 167 |
+
f"All existing object ids: {inference_state['obj_ids']}."
|
| 168 |
+
)
|
| 169 |
+
|
| 170 |
+
def _obj_idx_to_id(self, inference_state, obj_idx):
|
| 171 |
+
"""Map model-side object index to client-side object id."""
|
| 172 |
+
return inference_state["obj_idx_to_id"][obj_idx]
|
| 173 |
+
|
| 174 |
+
def _get_obj_num(self, inference_state):
|
| 175 |
+
"""Get the total number of unique object ids received so far in this session."""
|
| 176 |
+
return len(inference_state["obj_idx_to_id"])
|
| 177 |
+
|
| 178 |
+
@torch.inference_mode()
|
| 179 |
+
def add_new_points_or_box(
|
| 180 |
+
self,
|
| 181 |
+
inference_state,
|
| 182 |
+
frame_idx,
|
| 183 |
+
obj_id,
|
| 184 |
+
points=None,
|
| 185 |
+
labels=None,
|
| 186 |
+
clear_old_points=True,
|
| 187 |
+
rel_coordinates=True,
|
| 188 |
+
use_prev_mem_frame=False,
|
| 189 |
+
normalize_coords=True,
|
| 190 |
+
box=None,
|
| 191 |
+
):
|
| 192 |
+
"""Add new points to a frame."""
|
| 193 |
+
obj_idx = self._obj_id_to_idx(inference_state, obj_id)
|
| 194 |
+
point_inputs_per_frame = inference_state["point_inputs_per_obj"][obj_idx]
|
| 195 |
+
mask_inputs_per_frame = inference_state["mask_inputs_per_obj"][obj_idx]
|
| 196 |
+
|
| 197 |
+
if (points is not None) != (labels is not None):
|
| 198 |
+
raise ValueError("points and labels must be provided together")
|
| 199 |
+
if points is None and box is None:
|
| 200 |
+
raise ValueError("at least one of points or box must be provided as input")
|
| 201 |
+
|
| 202 |
+
if points is None:
|
| 203 |
+
points = torch.zeros(0, 2, dtype=torch.float32)
|
| 204 |
+
elif not isinstance(points, torch.Tensor):
|
| 205 |
+
points = torch.tensor(points, dtype=torch.float32)
|
| 206 |
+
if labels is None:
|
| 207 |
+
labels = torch.zeros(0, dtype=torch.int32)
|
| 208 |
+
elif not isinstance(labels, torch.Tensor):
|
| 209 |
+
labels = torch.tensor(labels, dtype=torch.int32)
|
| 210 |
+
if points.dim() == 2:
|
| 211 |
+
points = points.unsqueeze(0) # add batch dimension
|
| 212 |
+
if labels.dim() == 1:
|
| 213 |
+
labels = labels.unsqueeze(0) # add batch dimension
|
| 214 |
+
|
| 215 |
+
if rel_coordinates:
|
| 216 |
+
# convert the points from relative coordinates to absolute coordinates
|
| 217 |
+
if points is not None:
|
| 218 |
+
points = points * self.image_size
|
| 219 |
+
if box is not None:
|
| 220 |
+
box = box * self.image_size
|
| 221 |
+
|
| 222 |
+
# If `box` is provided, we add it as the first two points with labels 2 and 3
|
| 223 |
+
# along with the user-provided points (consistent with how SAM 2 is trained).
|
| 224 |
+
if box is not None:
|
| 225 |
+
if not clear_old_points:
|
| 226 |
+
raise ValueError(
|
| 227 |
+
"cannot add box without clearing old points, since "
|
| 228 |
+
"box prompt must be provided before any point prompt "
|
| 229 |
+
"(please use clear_old_points=True instead)"
|
| 230 |
+
)
|
| 231 |
+
if not isinstance(box, torch.Tensor):
|
| 232 |
+
box = torch.tensor(box, dtype=torch.float32, device=points.device)
|
| 233 |
+
box_coords = box.reshape(1, 2, 2)
|
| 234 |
+
box_labels = torch.tensor([2, 3], dtype=torch.int32, device=labels.device)
|
| 235 |
+
box_labels = box_labels.reshape(1, 2)
|
| 236 |
+
points = torch.cat([box_coords, points], dim=1)
|
| 237 |
+
labels = torch.cat([box_labels, labels], dim=1)
|
| 238 |
+
|
| 239 |
+
points = points.to(inference_state["device"])
|
| 240 |
+
labels = labels.to(inference_state["device"])
|
| 241 |
+
|
| 242 |
+
if not clear_old_points:
|
| 243 |
+
point_inputs = point_inputs_per_frame.get(frame_idx, None)
|
| 244 |
+
else:
|
| 245 |
+
point_inputs = None
|
| 246 |
+
point_inputs = concat_points(point_inputs, points, labels)
|
| 247 |
+
|
| 248 |
+
point_inputs_per_frame[frame_idx] = point_inputs
|
| 249 |
+
mask_inputs_per_frame.pop(frame_idx, None)
|
| 250 |
+
# If this frame hasn't been tracked before, we treat it as an initial conditioning
|
| 251 |
+
# frame, meaning that the inputs points are to generate segments on this frame without
|
| 252 |
+
# using any memory from other frames, like in SAM. Otherwise (if it has been tracked),
|
| 253 |
+
# the input points will be used to correct the already tracked masks.
|
| 254 |
+
is_init_cond_frame = frame_idx not in inference_state["frames_already_tracked"]
|
| 255 |
+
# whether to track in reverse time order
|
| 256 |
+
if is_init_cond_frame:
|
| 257 |
+
reverse = False
|
| 258 |
+
else:
|
| 259 |
+
reverse = inference_state["frames_already_tracked"][frame_idx]["reverse"]
|
| 260 |
+
obj_output_dict = inference_state["output_dict_per_obj"][obj_idx]
|
| 261 |
+
obj_temp_output_dict = inference_state["temp_output_dict_per_obj"][obj_idx]
|
| 262 |
+
# Add a frame to conditioning output if it's an initial conditioning frame or
|
| 263 |
+
# if the model sees all frames receiving clicks/mask as conditioning frames.
|
| 264 |
+
is_cond = is_init_cond_frame or self.add_all_frames_to_correct_as_cond
|
| 265 |
+
storage_key = "cond_frame_outputs" if is_cond else "non_cond_frame_outputs"
|
| 266 |
+
|
| 267 |
+
# Limit to a maximum number of input points to the prompt encoder (to reduce domain gap)
|
| 268 |
+
num_points = point_inputs["point_coords"].size(1)
|
| 269 |
+
if num_points > self.max_point_num_in_prompt_enc > 0:
|
| 270 |
+
num_first = self.max_point_num_in_prompt_enc // 2
|
| 271 |
+
num_last = self.max_point_num_in_prompt_enc - num_first
|
| 272 |
+
point_inputs["point_coords"] = torch.cat(
|
| 273 |
+
[
|
| 274 |
+
point_inputs["point_coords"][:, :num_first],
|
| 275 |
+
point_inputs["point_coords"][:, -num_last:],
|
| 276 |
+
],
|
| 277 |
+
dim=1,
|
| 278 |
+
)
|
| 279 |
+
point_inputs["point_labels"] = torch.cat(
|
| 280 |
+
[
|
| 281 |
+
point_inputs["point_labels"][:, :num_first],
|
| 282 |
+
point_inputs["point_labels"][:, -num_last:],
|
| 283 |
+
],
|
| 284 |
+
dim=1,
|
| 285 |
+
)
|
| 286 |
+
logging.warning(
|
| 287 |
+
f"Too many points ({num_points}) are provided on frame {frame_idx}. Only "
|
| 288 |
+
f"the first {num_first} points and the last {num_last} points will be used."
|
| 289 |
+
)
|
| 290 |
+
# Get any previously predicted mask logits on this object and feed it along with
|
| 291 |
+
# the new clicks into the SAM mask decoder when `self.iter_use_prev_mask_pred=True`.
|
| 292 |
+
prev_sam_mask_logits = None
|
| 293 |
+
if self.iter_use_prev_mask_pred:
|
| 294 |
+
# lookup temporary output dict first, which contains the most recent output
|
| 295 |
+
# (if not found, then lookup conditioning and non-conditioning frame output)
|
| 296 |
+
prev_out = obj_temp_output_dict[storage_key].get(frame_idx)
|
| 297 |
+
if prev_out is None:
|
| 298 |
+
prev_out = obj_output_dict["cond_frame_outputs"].get(frame_idx)
|
| 299 |
+
if prev_out is None:
|
| 300 |
+
prev_out = obj_output_dict["non_cond_frame_outputs"].get(frame_idx)
|
| 301 |
+
|
| 302 |
+
if prev_out is not None and prev_out["pred_masks"] is not None:
|
| 303 |
+
prev_sam_mask_logits = prev_out["pred_masks"].cuda(non_blocking=True)
|
| 304 |
+
# Clamp the scale of prev_sam_mask_logits to avoid rare numerical issues.
|
| 305 |
+
prev_sam_mask_logits = torch.clamp(prev_sam_mask_logits, -32.0, 32.0)
|
| 306 |
+
current_out, _ = self._run_single_frame_inference(
|
| 307 |
+
inference_state=inference_state,
|
| 308 |
+
output_dict=obj_output_dict, # run on the slice of a single object
|
| 309 |
+
frame_idx=frame_idx,
|
| 310 |
+
batch_size=1, # run on the slice of a single object
|
| 311 |
+
is_init_cond_frame=is_init_cond_frame,
|
| 312 |
+
point_inputs=point_inputs,
|
| 313 |
+
mask_inputs=None,
|
| 314 |
+
reverse=reverse,
|
| 315 |
+
# Skip the memory encoder when adding clicks or mask. We execute the memory encoder
|
| 316 |
+
# at the beginning of `propagate_in_video` (after user finalize their clicks). This
|
| 317 |
+
# allows us to enforce non-overlapping constraints on all objects before encoding
|
| 318 |
+
# them into memory.
|
| 319 |
+
run_mem_encoder=False,
|
| 320 |
+
prev_sam_mask_logits=prev_sam_mask_logits,
|
| 321 |
+
use_prev_mem_frame=use_prev_mem_frame,
|
| 322 |
+
)
|
| 323 |
+
# Add the output to the output dict (to be used as future memory)
|
| 324 |
+
obj_temp_output_dict[storage_key][frame_idx] = current_out
|
| 325 |
+
|
| 326 |
+
# Resize the output mask to the original video resolution
|
| 327 |
+
obj_ids = inference_state["obj_ids"]
|
| 328 |
+
consolidated_out = self._consolidate_temp_output_across_obj(
|
| 329 |
+
inference_state,
|
| 330 |
+
frame_idx,
|
| 331 |
+
is_cond=is_cond,
|
| 332 |
+
run_mem_encoder=False,
|
| 333 |
+
consolidate_at_video_res=True,
|
| 334 |
+
)
|
| 335 |
+
_, video_res_masks = self._get_orig_video_res_output(
|
| 336 |
+
inference_state, consolidated_out["pred_masks_video_res"]
|
| 337 |
+
)
|
| 338 |
+
low_res_masks = None # not needed by the demo
|
| 339 |
+
return frame_idx, obj_ids, low_res_masks, video_res_masks
|
| 340 |
+
|
| 341 |
+
@torch.inference_mode()
|
| 342 |
+
def add_new_mask(
|
| 343 |
+
self,
|
| 344 |
+
inference_state,
|
| 345 |
+
frame_idx,
|
| 346 |
+
obj_id,
|
| 347 |
+
mask,
|
| 348 |
+
add_mask_to_memory=False,
|
| 349 |
+
):
|
| 350 |
+
"""Add new mask to a frame."""
|
| 351 |
+
obj_idx = self._obj_id_to_idx(inference_state, obj_id)
|
| 352 |
+
point_inputs_per_frame = inference_state["point_inputs_per_obj"][obj_idx]
|
| 353 |
+
mask_inputs_per_frame = inference_state["mask_inputs_per_obj"][obj_idx]
|
| 354 |
+
|
| 355 |
+
assert mask.dim() == 2
|
| 356 |
+
mask_H, mask_W = mask.shape
|
| 357 |
+
mask_inputs_orig = mask[None, None] # add batch and channel dimension
|
| 358 |
+
mask_inputs_orig = mask_inputs_orig.float().to(inference_state["device"])
|
| 359 |
+
|
| 360 |
+
# resize the mask if it doesn't match the model's input mask size
|
| 361 |
+
if mask_H != self.input_mask_size or mask_W != self.input_mask_size:
|
| 362 |
+
mask_inputs = torch.nn.functional.interpolate(
|
| 363 |
+
mask_inputs_orig,
|
| 364 |
+
size=(self.input_mask_size, self.input_mask_size),
|
| 365 |
+
align_corners=False,
|
| 366 |
+
mode="bilinear",
|
| 367 |
+
antialias=True, # use antialias for downsampling
|
| 368 |
+
)
|
| 369 |
+
else:
|
| 370 |
+
mask_inputs = mask_inputs_orig
|
| 371 |
+
|
| 372 |
+
# also get the mask at the original video resolution (for outputting)
|
| 373 |
+
video_H = inference_state["video_height"]
|
| 374 |
+
video_W = inference_state["video_width"]
|
| 375 |
+
if mask_H != video_H or mask_W != video_W:
|
| 376 |
+
mask_inputs_video_res = torch.nn.functional.interpolate(
|
| 377 |
+
mask_inputs_orig,
|
| 378 |
+
size=(video_H, video_W),
|
| 379 |
+
align_corners=False,
|
| 380 |
+
mode="bilinear",
|
| 381 |
+
antialias=True, # use antialias for potential downsampling
|
| 382 |
+
)
|
| 383 |
+
else:
|
| 384 |
+
mask_inputs_video_res = mask_inputs_orig
|
| 385 |
+
# convert mask_inputs_video_res to binary (threshold at 0.5 as it is in range 0~1)
|
| 386 |
+
mask_inputs_video_res = mask_inputs_video_res > 0.5
|
| 387 |
+
|
| 388 |
+
mask_inputs_per_frame[frame_idx] = mask_inputs_video_res
|
| 389 |
+
point_inputs_per_frame.pop(frame_idx, None)
|
| 390 |
+
# If this frame hasn't been tracked before, we treat it as an initial conditioning
|
| 391 |
+
# frame, meaning that the inputs points are to generate segments on this frame without
|
| 392 |
+
# using any memory from other frames, like in SAM. Otherwise (if it has been tracked),
|
| 393 |
+
# the input points will be used to correct the already tracked masks.
|
| 394 |
+
is_init_cond_frame = frame_idx not in inference_state["frames_already_tracked"]
|
| 395 |
+
# whether to track in reverse time order
|
| 396 |
+
if is_init_cond_frame:
|
| 397 |
+
reverse = False
|
| 398 |
+
else:
|
| 399 |
+
reverse = inference_state["frames_already_tracked"][frame_idx]["reverse"]
|
| 400 |
+
obj_output_dict = inference_state["output_dict_per_obj"][obj_idx]
|
| 401 |
+
obj_temp_output_dict = inference_state["temp_output_dict_per_obj"][obj_idx]
|
| 402 |
+
# Add a frame to conditioning output if it's an initial conditioning frame or
|
| 403 |
+
# if the model sees all frames receiving clicks/mask as conditioning frames.
|
| 404 |
+
is_cond = is_init_cond_frame or self.add_all_frames_to_correct_as_cond
|
| 405 |
+
storage_key = "cond_frame_outputs" if is_cond else "non_cond_frame_outputs"
|
| 406 |
+
|
| 407 |
+
current_out, _ = self._run_single_frame_inference(
|
| 408 |
+
inference_state=inference_state,
|
| 409 |
+
output_dict=obj_output_dict, # run on the slice of a single object
|
| 410 |
+
frame_idx=frame_idx,
|
| 411 |
+
batch_size=1, # run on the slice of a single object
|
| 412 |
+
is_init_cond_frame=is_init_cond_frame,
|
| 413 |
+
point_inputs=None,
|
| 414 |
+
mask_inputs=mask_inputs,
|
| 415 |
+
reverse=reverse,
|
| 416 |
+
# Skip the memory encoder when adding clicks or mask. We execute the memory encoder
|
| 417 |
+
# at the beginning of `propagate_in_video` (after user finalize their clicks). This
|
| 418 |
+
# allows us to enforce non-overlapping constraints on all objects before encoding
|
| 419 |
+
# them into memory.
|
| 420 |
+
run_mem_encoder=False,
|
| 421 |
+
)
|
| 422 |
+
# We directly use the input mask at video resolution as the output mask for a better
|
| 423 |
+
# video editing experience (so that the masks don't change after each brushing).
|
| 424 |
+
# Here NO_OBJ_SCORE is a large negative value to represent the background and
|
| 425 |
+
# similarly -NO_OBJ_SCORE is a large positive value to represent the foreground.
|
| 426 |
+
current_out["pred_masks"] = None
|
| 427 |
+
current_out["pred_masks_video_res"] = torch.where(
|
| 428 |
+
mask_inputs_video_res, -NO_OBJ_SCORE, NO_OBJ_SCORE
|
| 429 |
+
)
|
| 430 |
+
# Add the output to the output dict (to be used as future memory)
|
| 431 |
+
obj_temp_output_dict[storage_key][frame_idx] = current_out
|
| 432 |
+
# Remove the overlapping proportion of other objects' input masks on this frame
|
| 433 |
+
temp_output_dict_per_obj = inference_state["temp_output_dict_per_obj"]
|
| 434 |
+
for obj_idx2, obj_temp_output_dict2 in temp_output_dict_per_obj.items():
|
| 435 |
+
if obj_idx2 == obj_idx:
|
| 436 |
+
continue
|
| 437 |
+
current_out2 = obj_temp_output_dict2[storage_key].get(frame_idx, None)
|
| 438 |
+
if current_out2 is not None and "pred_masks_video_res" in current_out2:
|
| 439 |
+
current_out2["pred_masks_video_res"] = torch.where(
|
| 440 |
+
mask_inputs_video_res,
|
| 441 |
+
NO_OBJ_SCORE,
|
| 442 |
+
current_out2["pred_masks_video_res"],
|
| 443 |
+
)
|
| 444 |
+
|
| 445 |
+
# Resize the output mask to the original video resolution
|
| 446 |
+
obj_ids = inference_state["obj_ids"]
|
| 447 |
+
consolidated_out = self._consolidate_temp_output_across_obj(
|
| 448 |
+
inference_state,
|
| 449 |
+
frame_idx,
|
| 450 |
+
is_cond=is_cond,
|
| 451 |
+
run_mem_encoder=False,
|
| 452 |
+
consolidate_at_video_res=True,
|
| 453 |
+
)
|
| 454 |
+
_, video_res_masks = self._get_orig_video_res_output(
|
| 455 |
+
inference_state, consolidated_out["pred_masks_video_res"]
|
| 456 |
+
)
|
| 457 |
+
low_res_masks = None # not needed by the demo
|
| 458 |
+
return frame_idx, obj_ids, low_res_masks, video_res_masks
|
| 459 |
+
|
| 460 |
+
def add_new_points(self, *args, **kwargs):
|
| 461 |
+
"""Deprecated method. Please use `add_new_points_or_box` instead."""
|
| 462 |
+
return self.add_new_points_or_box(*args, **kwargs)
|
| 463 |
+
|
| 464 |
+
def _get_orig_video_res_output(self, inference_state, any_res_masks):
|
| 465 |
+
"""
|
| 466 |
+
Resize the object scores to the original video resolution (video_res_masks)
|
| 467 |
+
and apply non-overlapping constraints for final output.
|
| 468 |
+
"""
|
| 469 |
+
device = inference_state["device"]
|
| 470 |
+
video_H = inference_state["video_height"]
|
| 471 |
+
video_W = inference_state["video_width"]
|
| 472 |
+
any_res_masks = any_res_masks.to(device, non_blocking=True)
|
| 473 |
+
if any_res_masks.shape[-2:] == (video_H, video_W):
|
| 474 |
+
video_res_masks = any_res_masks
|
| 475 |
+
else:
|
| 476 |
+
video_res_masks = torch.nn.functional.interpolate(
|
| 477 |
+
any_res_masks,
|
| 478 |
+
size=(video_H, video_W),
|
| 479 |
+
mode="bilinear",
|
| 480 |
+
align_corners=False,
|
| 481 |
+
)
|
| 482 |
+
if self.non_overlap_masks_for_output:
|
| 483 |
+
video_res_masks = self._apply_non_overlapping_constraints(video_res_masks)
|
| 484 |
+
# potentially fill holes in the predicted masks
|
| 485 |
+
if self.fill_hole_area > 0:
|
| 486 |
+
video_res_masks = fill_holes_in_mask_scores(
|
| 487 |
+
video_res_masks, self.fill_hole_area
|
| 488 |
+
)
|
| 489 |
+
return any_res_masks, video_res_masks
|
| 490 |
+
|
| 491 |
+
def _consolidate_temp_output_across_obj(
|
| 492 |
+
self,
|
| 493 |
+
inference_state,
|
| 494 |
+
frame_idx,
|
| 495 |
+
is_cond,
|
| 496 |
+
run_mem_encoder,
|
| 497 |
+
consolidate_at_video_res=False,
|
| 498 |
+
):
|
| 499 |
+
"""
|
| 500 |
+
Consolidate the per-object temporary outputs in `temp_output_dict_per_obj` on
|
| 501 |
+
a frame into a single output for all objects, including
|
| 502 |
+
1) fill any missing objects either from `output_dict_per_obj` (if they exist in
|
| 503 |
+
`output_dict_per_obj` for this frame) or leave them as placeholder values
|
| 504 |
+
(if they don't exist in `output_dict_per_obj` for this frame);
|
| 505 |
+
2) if specified, rerun memory encoder after apply non-overlapping constraints
|
| 506 |
+
on the object scores.
|
| 507 |
+
"""
|
| 508 |
+
batch_size = self._get_obj_num(inference_state)
|
| 509 |
+
storage_key = "cond_frame_outputs" if is_cond else "non_cond_frame_outputs"
|
| 510 |
+
# Optionally, we allow consolidating the temporary outputs at the original
|
| 511 |
+
# video resolution (to provide a better editing experience for mask prompts).
|
| 512 |
+
if consolidate_at_video_res:
|
| 513 |
+
assert not run_mem_encoder, "memory encoder cannot run at video resolution"
|
| 514 |
+
consolidated_H = inference_state["video_height"]
|
| 515 |
+
consolidated_W = inference_state["video_width"]
|
| 516 |
+
consolidated_mask_key = "pred_masks_video_res"
|
| 517 |
+
else:
|
| 518 |
+
consolidated_H = consolidated_W = self.low_res_mask_size
|
| 519 |
+
consolidated_mask_key = "pred_masks"
|
| 520 |
+
|
| 521 |
+
# Initialize `consolidated_out`. Its "maskmem_features" and "maskmem_pos_enc"
|
| 522 |
+
# will be added when rerunning the memory encoder after applying non-overlapping
|
| 523 |
+
# constraints to object scores. Its "pred_masks" are prefilled with a large
|
| 524 |
+
# negative value (NO_OBJ_SCORE) to represent missing objects.
|
| 525 |
+
consolidated_out = {
|
| 526 |
+
"maskmem_features": None,
|
| 527 |
+
"maskmem_pos_enc": None,
|
| 528 |
+
consolidated_mask_key: torch.full(
|
| 529 |
+
size=(batch_size, 1, consolidated_H, consolidated_W),
|
| 530 |
+
fill_value=NO_OBJ_SCORE,
|
| 531 |
+
dtype=torch.float32,
|
| 532 |
+
device=inference_state["storage_device"],
|
| 533 |
+
),
|
| 534 |
+
"obj_ptr": torch.full(
|
| 535 |
+
size=(batch_size, self.hidden_dim),
|
| 536 |
+
fill_value=NO_OBJ_SCORE,
|
| 537 |
+
dtype=torch.float32,
|
| 538 |
+
device=inference_state["device"],
|
| 539 |
+
),
|
| 540 |
+
"object_score_logits": torch.full(
|
| 541 |
+
size=(batch_size, 1),
|
| 542 |
+
# default to 10.0 for object_score_logits, i.e. assuming the object is
|
| 543 |
+
# present as sigmoid(10)=1, same as in `predict_masks` of `MaskDecoder`
|
| 544 |
+
fill_value=10.0,
|
| 545 |
+
dtype=torch.float32,
|
| 546 |
+
device=inference_state["device"],
|
| 547 |
+
),
|
| 548 |
+
}
|
| 549 |
+
if self.use_memory_selection:
|
| 550 |
+
consolidated_out["iou_score"] = torch.full(
|
| 551 |
+
size=(batch_size, 1),
|
| 552 |
+
fill_value=0.0,
|
| 553 |
+
dtype=torch.float32,
|
| 554 |
+
device=inference_state["device"],
|
| 555 |
+
)
|
| 556 |
+
empty_mask_ptr = None
|
| 557 |
+
for obj_idx in range(batch_size):
|
| 558 |
+
obj_temp_output_dict = inference_state["temp_output_dict_per_obj"][obj_idx]
|
| 559 |
+
obj_output_dict = inference_state["output_dict_per_obj"][obj_idx]
|
| 560 |
+
out = obj_temp_output_dict[storage_key].get(frame_idx, None)
|
| 561 |
+
# If the object doesn't appear in "temp_output_dict_per_obj" on this frame,
|
| 562 |
+
# we fall back and look up its previous output in "output_dict_per_obj".
|
| 563 |
+
# We look up both "cond_frame_outputs" and "non_cond_frame_outputs" in
|
| 564 |
+
# "output_dict_per_obj" to find a previous output for this object.
|
| 565 |
+
if out is None:
|
| 566 |
+
out = obj_output_dict["cond_frame_outputs"].get(frame_idx, None)
|
| 567 |
+
if out is None:
|
| 568 |
+
out = obj_output_dict["non_cond_frame_outputs"].get(frame_idx, None)
|
| 569 |
+
# If the object doesn't appear in "output_dict_per_obj" either, we skip it
|
| 570 |
+
# and leave its mask scores to the default scores (i.e. the NO_OBJ_SCORE
|
| 571 |
+
# placeholder above) and set its object pointer to be a dummy pointer.
|
| 572 |
+
if out is None:
|
| 573 |
+
# Fill in dummy object pointers for those objects without any inputs or
|
| 574 |
+
# tracking outcomes on this frame (only do it under `run_mem_encoder=True`,
|
| 575 |
+
# i.e. when we need to build the memory for tracking).
|
| 576 |
+
if run_mem_encoder:
|
| 577 |
+
if empty_mask_ptr is None:
|
| 578 |
+
empty_mask_ptr = self._get_empty_mask_ptr(
|
| 579 |
+
inference_state, frame_idx
|
| 580 |
+
)
|
| 581 |
+
# fill object pointer with a dummy pointer (based on an empty mask)
|
| 582 |
+
consolidated_out["obj_ptr"][obj_idx : obj_idx + 1] = empty_mask_ptr
|
| 583 |
+
continue
|
| 584 |
+
# Add the temporary object output mask to consolidated output mask
|
| 585 |
+
# (use "pred_masks_video_res" if it's available)
|
| 586 |
+
obj_mask = out.get("pred_masks_video_res", out["pred_masks"])
|
| 587 |
+
consolidated_pred_masks = consolidated_out[consolidated_mask_key]
|
| 588 |
+
if obj_mask.shape[-2:] == consolidated_pred_masks.shape[-2:]:
|
| 589 |
+
consolidated_pred_masks[obj_idx : obj_idx + 1] = obj_mask
|
| 590 |
+
else:
|
| 591 |
+
# Resize first if temporary object mask has a different resolution
|
| 592 |
+
is_downsampling = "pred_masks_video_res" in out
|
| 593 |
+
resized_obj_mask = torch.nn.functional.interpolate(
|
| 594 |
+
obj_mask,
|
| 595 |
+
size=consolidated_pred_masks.shape[-2:],
|
| 596 |
+
mode="bilinear",
|
| 597 |
+
align_corners=False,
|
| 598 |
+
antialias=is_downsampling, # use antialias for downsampling
|
| 599 |
+
)
|
| 600 |
+
consolidated_pred_masks[obj_idx : obj_idx + 1] = resized_obj_mask
|
| 601 |
+
consolidated_out["obj_ptr"][obj_idx : obj_idx + 1] = out["obj_ptr"]
|
| 602 |
+
consolidated_out["object_score_logits"][obj_idx : obj_idx + 1] = out[
|
| 603 |
+
"object_score_logits"
|
| 604 |
+
]
|
| 605 |
+
if self.use_memory_selection:
|
| 606 |
+
consolidated_out["iou_score"][obj_idx : obj_idx + 1] = out["iou_score"]
|
| 607 |
+
# Optionally, apply non-overlapping constraints on the consolidated scores
|
| 608 |
+
# and rerun the memory encoder
|
| 609 |
+
if run_mem_encoder:
|
| 610 |
+
device = inference_state["device"]
|
| 611 |
+
high_res_masks = torch.nn.functional.interpolate(
|
| 612 |
+
consolidated_out["pred_masks"].to(device, non_blocking=True),
|
| 613 |
+
size=(self.image_size, self.image_size),
|
| 614 |
+
mode="bilinear",
|
| 615 |
+
align_corners=False,
|
| 616 |
+
)
|
| 617 |
+
high_res_masks = self._apply_non_overlapping_constraints(high_res_masks)
|
| 618 |
+
maskmem_features, maskmem_pos_enc = self._run_memory_encoder(
|
| 619 |
+
inference_state=inference_state,
|
| 620 |
+
frame_idx=frame_idx,
|
| 621 |
+
batch_size=batch_size,
|
| 622 |
+
high_res_masks=high_res_masks,
|
| 623 |
+
object_score_logits=consolidated_out["object_score_logits"],
|
| 624 |
+
is_mask_from_pts=True, # these frames are what the user interacted with
|
| 625 |
+
)
|
| 626 |
+
consolidated_out["maskmem_features"] = maskmem_features
|
| 627 |
+
consolidated_out["maskmem_pos_enc"] = maskmem_pos_enc
|
| 628 |
+
|
| 629 |
+
return consolidated_out
|
| 630 |
+
|
| 631 |
+
def _get_empty_mask_ptr(self, inference_state, frame_idx):
|
| 632 |
+
"""Get a dummy object pointer based on an empty mask on the current frame."""
|
| 633 |
+
# A dummy (empty) mask with a single object
|
| 634 |
+
batch_size = 1
|
| 635 |
+
mask_inputs = torch.zeros(
|
| 636 |
+
(batch_size, 1, self.image_size, self.image_size),
|
| 637 |
+
dtype=torch.float32,
|
| 638 |
+
device=inference_state["device"],
|
| 639 |
+
)
|
| 640 |
+
|
| 641 |
+
# Retrieve correct image features
|
| 642 |
+
(
|
| 643 |
+
image,
|
| 644 |
+
_,
|
| 645 |
+
current_vision_feats,
|
| 646 |
+
current_vision_pos_embeds,
|
| 647 |
+
feat_sizes,
|
| 648 |
+
) = self._get_image_feature(inference_state, frame_idx, batch_size)
|
| 649 |
+
|
| 650 |
+
# Feed the empty mask and image feature above to get a dummy object pointer
|
| 651 |
+
current_out = self.track_step(
|
| 652 |
+
frame_idx=frame_idx,
|
| 653 |
+
is_init_cond_frame=True,
|
| 654 |
+
current_vision_feats=current_vision_feats,
|
| 655 |
+
current_vision_pos_embeds=current_vision_pos_embeds,
|
| 656 |
+
feat_sizes=feat_sizes,
|
| 657 |
+
image=image,
|
| 658 |
+
point_inputs=None,
|
| 659 |
+
mask_inputs=mask_inputs,
|
| 660 |
+
output_dict={
|
| 661 |
+
"cond_frame_outputs": {},
|
| 662 |
+
"non_cond_frame_outputs": {},
|
| 663 |
+
},
|
| 664 |
+
num_frames=inference_state["num_frames"],
|
| 665 |
+
track_in_reverse=False,
|
| 666 |
+
run_mem_encoder=False,
|
| 667 |
+
prev_sam_mask_logits=None,
|
| 668 |
+
)
|
| 669 |
+
return current_out["obj_ptr"]
|
| 670 |
+
|
| 671 |
+
@torch.inference_mode()
|
| 672 |
+
def propagate_in_video_preflight(self, inference_state, run_mem_encoder=True):
|
| 673 |
+
"""Prepare inference_state and consolidate temporary outputs before tracking."""
|
| 674 |
+
# Tracking has started and we don't allow adding new objects until session is reset.
|
| 675 |
+
inference_state["tracking_has_started"] = True
|
| 676 |
+
batch_size = self._get_obj_num(inference_state)
|
| 677 |
+
|
| 678 |
+
# Consolidate per-object temporary outputs in "temp_output_dict_per_obj" and
|
| 679 |
+
# add them into "output_dict".
|
| 680 |
+
temp_output_dict_per_obj = inference_state["temp_output_dict_per_obj"]
|
| 681 |
+
output_dict = inference_state["output_dict"]
|
| 682 |
+
# "consolidated_frame_inds" contains indices of those frames where consolidated
|
| 683 |
+
# temporary outputs have been added (either in this call or any previous calls
|
| 684 |
+
# to `propagate_in_video_preflight`).
|
| 685 |
+
consolidated_frame_inds = inference_state["consolidated_frame_inds"]
|
| 686 |
+
for is_cond in [False, True]:
|
| 687 |
+
# Separately consolidate conditioning and non-conditioning temp outptus
|
| 688 |
+
storage_key = "cond_frame_outputs" if is_cond else "non_cond_frame_outputs"
|
| 689 |
+
# Find all the frames that contain temporary outputs for any objects
|
| 690 |
+
# (these should be the frames that have just received clicks for mask inputs
|
| 691 |
+
# via `add_new_points` or `add_new_mask`)
|
| 692 |
+
temp_frame_inds = set()
|
| 693 |
+
for obj_temp_output_dict in temp_output_dict_per_obj.values():
|
| 694 |
+
temp_frame_inds.update(obj_temp_output_dict[storage_key].keys())
|
| 695 |
+
consolidated_frame_inds[storage_key].update(temp_frame_inds)
|
| 696 |
+
# consolidate the temprary output across all objects on this frame
|
| 697 |
+
for frame_idx in temp_frame_inds:
|
| 698 |
+
consolidated_out = self._consolidate_temp_output_across_obj(
|
| 699 |
+
inference_state,
|
| 700 |
+
frame_idx,
|
| 701 |
+
is_cond=is_cond,
|
| 702 |
+
run_mem_encoder=run_mem_encoder,
|
| 703 |
+
)
|
| 704 |
+
# merge them into "output_dict" and also create per-object slices
|
| 705 |
+
output_dict[storage_key][frame_idx] = consolidated_out
|
| 706 |
+
self._add_output_per_object(
|
| 707 |
+
inference_state, frame_idx, consolidated_out, storage_key
|
| 708 |
+
)
|
| 709 |
+
clear_non_cond_mem = self.clear_non_cond_mem_around_input and (
|
| 710 |
+
self.clear_non_cond_mem_for_multi_obj or batch_size <= 1
|
| 711 |
+
)
|
| 712 |
+
if clear_non_cond_mem:
|
| 713 |
+
# clear non-conditioning memory of the surrounding frames
|
| 714 |
+
self._clear_non_cond_mem_around_input(inference_state, frame_idx)
|
| 715 |
+
|
| 716 |
+
# clear temporary outputs in `temp_output_dict_per_obj`
|
| 717 |
+
for obj_temp_output_dict in temp_output_dict_per_obj.values():
|
| 718 |
+
obj_temp_output_dict[storage_key].clear()
|
| 719 |
+
|
| 720 |
+
# edge case: if an output is added to "cond_frame_outputs", we remove any prior
|
| 721 |
+
# output on the same frame in "non_cond_frame_outputs"
|
| 722 |
+
for frame_idx in output_dict["cond_frame_outputs"]:
|
| 723 |
+
output_dict["non_cond_frame_outputs"].pop(frame_idx, None)
|
| 724 |
+
for obj_output_dict in inference_state["output_dict_per_obj"].values():
|
| 725 |
+
for frame_idx in obj_output_dict["cond_frame_outputs"]:
|
| 726 |
+
obj_output_dict["non_cond_frame_outputs"].pop(frame_idx, None)
|
| 727 |
+
for frame_idx in consolidated_frame_inds["cond_frame_outputs"]:
|
| 728 |
+
assert frame_idx in output_dict["cond_frame_outputs"]
|
| 729 |
+
consolidated_frame_inds["non_cond_frame_outputs"].discard(frame_idx)
|
| 730 |
+
|
| 731 |
+
# Make sure that the frame indices in "consolidated_frame_inds" are exactly those frames
|
| 732 |
+
# with either points or mask inputs (which should be true under a correct demo workflow).
|
| 733 |
+
all_consolidated_frame_inds = (
|
| 734 |
+
consolidated_frame_inds["cond_frame_outputs"]
|
| 735 |
+
| consolidated_frame_inds["non_cond_frame_outputs"]
|
| 736 |
+
)
|
| 737 |
+
input_frames_inds = set()
|
| 738 |
+
for point_inputs_per_frame in inference_state["point_inputs_per_obj"].values():
|
| 739 |
+
input_frames_inds.update(point_inputs_per_frame.keys())
|
| 740 |
+
for mask_inputs_per_frame in inference_state["mask_inputs_per_obj"].values():
|
| 741 |
+
input_frames_inds.update(mask_inputs_per_frame.keys())
|
| 742 |
+
assert all_consolidated_frame_inds == input_frames_inds
|
| 743 |
+
# Record the first interacted frame index (for tracking start)
|
| 744 |
+
if inference_state["first_ann_frame_idx"] is None:
|
| 745 |
+
inference_state["first_ann_frame_idx"] = min(
|
| 746 |
+
input_frames_inds, default=None
|
| 747 |
+
)
|
| 748 |
+
# In case `first_ann_frame_idx` is not in the conditioning frames (e.g. because
|
| 749 |
+
# we cleared the input points on that frame), pick the first conditioning frame
|
| 750 |
+
if (
|
| 751 |
+
inference_state["first_ann_frame_idx"]
|
| 752 |
+
not in output_dict["cond_frame_outputs"]
|
| 753 |
+
):
|
| 754 |
+
inference_state["first_ann_frame_idx"] = min(
|
| 755 |
+
output_dict["cond_frame_outputs"], default=None
|
| 756 |
+
)
|
| 757 |
+
|
| 758 |
+
def _get_processing_order(
|
| 759 |
+
self, inference_state, start_frame_idx, max_frame_num_to_track, reverse
|
| 760 |
+
):
|
| 761 |
+
num_frames = inference_state["num_frames"]
|
| 762 |
+
# set start index, end index, and processing order
|
| 763 |
+
if self.always_start_from_first_ann_frame:
|
| 764 |
+
# in this case, we always start tracking from the frame where we receive
|
| 765 |
+
# the initial annotation and ignore the provided start_frame_idx
|
| 766 |
+
start_frame_idx = inference_state["first_ann_frame_idx"]
|
| 767 |
+
if start_frame_idx is None:
|
| 768 |
+
# default: start from the earliest frame with input points
|
| 769 |
+
start_frame_idx = min(inference_state["output_dict"]["cond_frame_outputs"])
|
| 770 |
+
if max_frame_num_to_track is None:
|
| 771 |
+
# default: track all the frames in the video
|
| 772 |
+
max_frame_num_to_track = num_frames
|
| 773 |
+
if reverse:
|
| 774 |
+
end_frame_idx = max(start_frame_idx - max_frame_num_to_track, 0)
|
| 775 |
+
if start_frame_idx > 0:
|
| 776 |
+
processing_order = range(start_frame_idx, end_frame_idx - 1, -1)
|
| 777 |
+
else:
|
| 778 |
+
# this is the edge case where we start from frame 0 and track in reverse order;
|
| 779 |
+
# in this case, we track a single frame (frame 0)
|
| 780 |
+
processing_order = [0]
|
| 781 |
+
else:
|
| 782 |
+
end_frame_idx = min(
|
| 783 |
+
start_frame_idx + max_frame_num_to_track, num_frames - 1
|
| 784 |
+
)
|
| 785 |
+
processing_order = range(start_frame_idx, end_frame_idx + 1)
|
| 786 |
+
return processing_order
|
| 787 |
+
|
| 788 |
+
@torch.inference_mode()
|
| 789 |
+
def propagate_in_video(
|
| 790 |
+
self,
|
| 791 |
+
inference_state,
|
| 792 |
+
start_frame_idx,
|
| 793 |
+
max_frame_num_to_track,
|
| 794 |
+
reverse,
|
| 795 |
+
tqdm_disable=False,
|
| 796 |
+
obj_ids=None,
|
| 797 |
+
run_mem_encoder=True,
|
| 798 |
+
propagate_preflight=False,
|
| 799 |
+
):
|
| 800 |
+
"""Propagate the input points across frames to track in the entire video."""
|
| 801 |
+
if propagate_preflight:
|
| 802 |
+
self.propagate_in_video_preflight(inference_state)
|
| 803 |
+
# NOTE: This is a copy from the parent class, except that we return object scores as well.
|
| 804 |
+
output_dict = inference_state["output_dict"]
|
| 805 |
+
consolidated_frame_inds = inference_state["consolidated_frame_inds"]
|
| 806 |
+
if obj_ids is not None:
|
| 807 |
+
raise NotImplementedError(
|
| 808 |
+
"Per-object tracking yet for batched inference if not implemented."
|
| 809 |
+
)
|
| 810 |
+
obj_ids = inference_state["obj_ids"]
|
| 811 |
+
batch_size = self._get_obj_num(inference_state)
|
| 812 |
+
if len(output_dict["cond_frame_outputs"]) == 0:
|
| 813 |
+
raise RuntimeError("No points are provided; please add points first")
|
| 814 |
+
clear_non_cond_mem = self.clear_non_cond_mem_around_input and (
|
| 815 |
+
self.clear_non_cond_mem_for_multi_obj or batch_size <= 1
|
| 816 |
+
)
|
| 817 |
+
|
| 818 |
+
processing_order = self._get_processing_order(
|
| 819 |
+
inference_state,
|
| 820 |
+
start_frame_idx,
|
| 821 |
+
max_frame_num_to_track,
|
| 822 |
+
reverse,
|
| 823 |
+
)
|
| 824 |
+
|
| 825 |
+
for frame_idx in tqdm(
|
| 826 |
+
processing_order, desc="propagate in video", disable=tqdm_disable
|
| 827 |
+
):
|
| 828 |
+
# We skip those frames already in consolidated outputs (these are frames
|
| 829 |
+
# that received input clicks or mask). Note that we cannot directly run
|
| 830 |
+
# batched forward on them via `_run_single_frame_inference` because the
|
| 831 |
+
# number of clicks on each object might be different.
|
| 832 |
+
if frame_idx in consolidated_frame_inds["cond_frame_outputs"]:
|
| 833 |
+
storage_key = "cond_frame_outputs"
|
| 834 |
+
current_out = output_dict[storage_key][frame_idx]
|
| 835 |
+
pred_masks = current_out["pred_masks"]
|
| 836 |
+
obj_scores = current_out["object_score_logits"]
|
| 837 |
+
if clear_non_cond_mem:
|
| 838 |
+
# clear non-conditioning memory of the surrounding frames
|
| 839 |
+
self._clear_non_cond_mem_around_input(inference_state, frame_idx)
|
| 840 |
+
elif frame_idx in consolidated_frame_inds["non_cond_frame_outputs"]:
|
| 841 |
+
storage_key = "non_cond_frame_outputs"
|
| 842 |
+
current_out = output_dict[storage_key][frame_idx]
|
| 843 |
+
pred_masks = current_out["pred_masks"]
|
| 844 |
+
obj_scores = current_out["object_score_logits"]
|
| 845 |
+
else:
|
| 846 |
+
storage_key = "non_cond_frame_outputs"
|
| 847 |
+
current_out, pred_masks = self._run_single_frame_inference(
|
| 848 |
+
inference_state=inference_state,
|
| 849 |
+
output_dict=output_dict,
|
| 850 |
+
frame_idx=frame_idx,
|
| 851 |
+
batch_size=batch_size,
|
| 852 |
+
is_init_cond_frame=False,
|
| 853 |
+
point_inputs=None,
|
| 854 |
+
mask_inputs=None,
|
| 855 |
+
reverse=reverse,
|
| 856 |
+
run_mem_encoder=run_mem_encoder,
|
| 857 |
+
)
|
| 858 |
+
obj_scores = current_out["object_score_logits"]
|
| 859 |
+
output_dict[storage_key][frame_idx] = current_out
|
| 860 |
+
# Create slices of per-object outputs for subsequent interaction with each
|
| 861 |
+
# individual object after tracking.
|
| 862 |
+
self._add_output_per_object(
|
| 863 |
+
inference_state, frame_idx, current_out, storage_key
|
| 864 |
+
)
|
| 865 |
+
inference_state["frames_already_tracked"][frame_idx] = {"reverse": reverse}
|
| 866 |
+
|
| 867 |
+
# Resize the output mask to the original video resolution (we directly use
|
| 868 |
+
# the mask scores on GPU for output to avoid any CPU conversion in between)
|
| 869 |
+
low_res_masks, video_res_masks = self._get_orig_video_res_output(
|
| 870 |
+
inference_state, pred_masks
|
| 871 |
+
)
|
| 872 |
+
yield frame_idx, obj_ids, low_res_masks, video_res_masks, obj_scores
|
| 873 |
+
|
| 874 |
+
def _add_output_per_object(
|
| 875 |
+
self, inference_state, frame_idx, current_out, storage_key
|
| 876 |
+
):
|
| 877 |
+
"""
|
| 878 |
+
Split a multi-object output into per-object output slices and add them into
|
| 879 |
+
`output_dict_per_obj`. The resulting slices share the same tensor storage.
|
| 880 |
+
"""
|
| 881 |
+
maskmem_features = current_out["maskmem_features"]
|
| 882 |
+
assert maskmem_features is None or isinstance(maskmem_features, torch.Tensor)
|
| 883 |
+
|
| 884 |
+
maskmem_pos_enc = current_out["maskmem_pos_enc"]
|
| 885 |
+
assert maskmem_pos_enc is None or isinstance(maskmem_pos_enc, list)
|
| 886 |
+
|
| 887 |
+
output_dict_per_obj = inference_state["output_dict_per_obj"]
|
| 888 |
+
for obj_idx, obj_output_dict in output_dict_per_obj.items():
|
| 889 |
+
obj_slice = slice(obj_idx, obj_idx + 1)
|
| 890 |
+
obj_out = {
|
| 891 |
+
"maskmem_features": None,
|
| 892 |
+
"maskmem_pos_enc": None,
|
| 893 |
+
"pred_masks": current_out["pred_masks"][obj_slice],
|
| 894 |
+
"obj_ptr": current_out["obj_ptr"][obj_slice],
|
| 895 |
+
"object_score_logits": current_out["object_score_logits"][obj_slice],
|
| 896 |
+
}
|
| 897 |
+
if self.use_memory_selection:
|
| 898 |
+
obj_out["iou_score"] = current_out["iou_score"][obj_slice]
|
| 899 |
+
if maskmem_features is not None:
|
| 900 |
+
obj_out["maskmem_features"] = maskmem_features[obj_slice]
|
| 901 |
+
if maskmem_pos_enc is not None:
|
| 902 |
+
obj_out["maskmem_pos_enc"] = [x[obj_slice] for x in maskmem_pos_enc]
|
| 903 |
+
obj_output_dict[storage_key][frame_idx] = obj_out
|
| 904 |
+
|
| 905 |
+
@torch.inference_mode()
|
| 906 |
+
def clear_all_points_in_frame(
|
| 907 |
+
self, inference_state, frame_idx, obj_id, need_output=True
|
| 908 |
+
):
|
| 909 |
+
"""Remove all input points or mask in a specific frame for a given object."""
|
| 910 |
+
obj_idx = self._obj_id_to_idx(inference_state, obj_id)
|
| 911 |
+
|
| 912 |
+
# Clear the conditioning information on the given frame
|
| 913 |
+
inference_state["point_inputs_per_obj"][obj_idx].pop(frame_idx, None)
|
| 914 |
+
inference_state["mask_inputs_per_obj"][obj_idx].pop(frame_idx, None)
|
| 915 |
+
|
| 916 |
+
temp_output_dict_per_obj = inference_state["temp_output_dict_per_obj"]
|
| 917 |
+
temp_output_dict_per_obj[obj_idx]["cond_frame_outputs"].pop(frame_idx, None)
|
| 918 |
+
temp_output_dict_per_obj[obj_idx]["non_cond_frame_outputs"].pop(frame_idx, None)
|
| 919 |
+
|
| 920 |
+
# Check and see if there are still any inputs left on this frame
|
| 921 |
+
batch_size = self._get_obj_num(inference_state)
|
| 922 |
+
frame_has_input = False
|
| 923 |
+
for obj_idx2 in range(batch_size):
|
| 924 |
+
if frame_idx in inference_state["point_inputs_per_obj"][obj_idx2]:
|
| 925 |
+
frame_has_input = True
|
| 926 |
+
break
|
| 927 |
+
if frame_idx in inference_state["mask_inputs_per_obj"][obj_idx2]:
|
| 928 |
+
frame_has_input = True
|
| 929 |
+
break
|
| 930 |
+
|
| 931 |
+
# If this frame has no remaining inputs for any objects, we further clear its
|
| 932 |
+
# conditioning frame status
|
| 933 |
+
if not frame_has_input:
|
| 934 |
+
output_dict = inference_state["output_dict"]
|
| 935 |
+
consolidated_frame_inds = inference_state["consolidated_frame_inds"]
|
| 936 |
+
consolidated_frame_inds["cond_frame_outputs"].discard(frame_idx)
|
| 937 |
+
consolidated_frame_inds["non_cond_frame_outputs"].discard(frame_idx)
|
| 938 |
+
# Remove the frame's conditioning output (possibly downgrading it to non-conditioning)
|
| 939 |
+
out = output_dict["cond_frame_outputs"].pop(frame_idx, None)
|
| 940 |
+
if out is not None:
|
| 941 |
+
# The frame is not a conditioning frame anymore since it's not receiving inputs,
|
| 942 |
+
# so we "downgrade" its output (if exists) to a non-conditioning frame output.
|
| 943 |
+
output_dict["non_cond_frame_outputs"][frame_idx] = out
|
| 944 |
+
inference_state["frames_already_tracked"].pop(frame_idx, None)
|
| 945 |
+
# Similarly, do it for the sliced output on each object.
|
| 946 |
+
for obj_idx2 in range(batch_size):
|
| 947 |
+
obj_output_dict = inference_state["output_dict_per_obj"][obj_idx2]
|
| 948 |
+
obj_out = obj_output_dict["cond_frame_outputs"].pop(frame_idx, None)
|
| 949 |
+
if obj_out is not None:
|
| 950 |
+
obj_output_dict["non_cond_frame_outputs"][frame_idx] = obj_out
|
| 951 |
+
|
| 952 |
+
# If all the conditioning frames have been removed, we also clear the tracking outputs
|
| 953 |
+
if len(output_dict["cond_frame_outputs"]) == 0:
|
| 954 |
+
self._reset_tracking_results(inference_state)
|
| 955 |
+
|
| 956 |
+
if not need_output:
|
| 957 |
+
return
|
| 958 |
+
# Finally, output updated masks per object (after removing the inputs above)
|
| 959 |
+
obj_ids = inference_state["obj_ids"]
|
| 960 |
+
is_cond = any(
|
| 961 |
+
frame_idx in obj_temp_output_dict["cond_frame_outputs"]
|
| 962 |
+
for obj_temp_output_dict in temp_output_dict_per_obj.values()
|
| 963 |
+
)
|
| 964 |
+
consolidated_out = self._consolidate_temp_output_across_obj(
|
| 965 |
+
inference_state,
|
| 966 |
+
frame_idx,
|
| 967 |
+
is_cond=is_cond,
|
| 968 |
+
run_mem_encoder=False,
|
| 969 |
+
consolidate_at_video_res=True,
|
| 970 |
+
)
|
| 971 |
+
_, video_res_masks = self._get_orig_video_res_output(
|
| 972 |
+
inference_state, consolidated_out["pred_masks_video_res"]
|
| 973 |
+
)
|
| 974 |
+
low_res_masks = None # not needed by the demo
|
| 975 |
+
return frame_idx, obj_ids, low_res_masks, video_res_masks
|
| 976 |
+
|
| 977 |
+
@torch.inference_mode()
|
| 978 |
+
def clear_all_points_in_video(self, inference_state):
|
| 979 |
+
"""Remove all input points or mask in all frames throughout the video."""
|
| 980 |
+
self._reset_tracking_results(inference_state)
|
| 981 |
+
# Remove all object ids
|
| 982 |
+
inference_state["obj_id_to_idx"].clear()
|
| 983 |
+
inference_state["obj_idx_to_id"].clear()
|
| 984 |
+
inference_state["obj_ids"].clear()
|
| 985 |
+
inference_state["point_inputs_per_obj"].clear()
|
| 986 |
+
inference_state["mask_inputs_per_obj"].clear()
|
| 987 |
+
inference_state["output_dict_per_obj"].clear()
|
| 988 |
+
inference_state["temp_output_dict_per_obj"].clear()
|
| 989 |
+
|
| 990 |
+
def _reset_tracking_results(self, inference_state):
|
| 991 |
+
"""Reset all tracking inputs and results across the videos."""
|
| 992 |
+
for v in inference_state["point_inputs_per_obj"].values():
|
| 993 |
+
v.clear()
|
| 994 |
+
for v in inference_state["mask_inputs_per_obj"].values():
|
| 995 |
+
v.clear()
|
| 996 |
+
for v in inference_state["output_dict_per_obj"].values():
|
| 997 |
+
v["cond_frame_outputs"].clear()
|
| 998 |
+
v["non_cond_frame_outputs"].clear()
|
| 999 |
+
for v in inference_state["temp_output_dict_per_obj"].values():
|
| 1000 |
+
v["cond_frame_outputs"].clear()
|
| 1001 |
+
v["non_cond_frame_outputs"].clear()
|
| 1002 |
+
inference_state["output_dict"]["cond_frame_outputs"].clear()
|
| 1003 |
+
inference_state["output_dict"]["non_cond_frame_outputs"].clear()
|
| 1004 |
+
inference_state["consolidated_frame_inds"]["cond_frame_outputs"].clear()
|
| 1005 |
+
inference_state["consolidated_frame_inds"]["non_cond_frame_outputs"].clear()
|
| 1006 |
+
inference_state["tracking_has_started"] = False
|
| 1007 |
+
inference_state["frames_already_tracked"].clear()
|
| 1008 |
+
inference_state["first_ann_frame_idx"] = None
|
| 1009 |
+
|
| 1010 |
+
def _get_image_feature(self, inference_state, frame_idx, batch_size):
|
| 1011 |
+
"""Compute the image features on a given frame."""
|
| 1012 |
+
# Look up in the cache
|
| 1013 |
+
image, backbone_out = inference_state["cached_features"].get(
|
| 1014 |
+
frame_idx, (None, None)
|
| 1015 |
+
)
|
| 1016 |
+
if backbone_out is None:
|
| 1017 |
+
if self.backbone is None:
|
| 1018 |
+
raise RuntimeError(
|
| 1019 |
+
f"Image features for frame {frame_idx} are not cached. "
|
| 1020 |
+
"Please run inference on this frame first."
|
| 1021 |
+
)
|
| 1022 |
+
else:
|
| 1023 |
+
# Cache miss -- we will run inference on a single image
|
| 1024 |
+
image = inference_state["images"][frame_idx].cuda().float().unsqueeze(0)
|
| 1025 |
+
backbone_out = self.forward_image(image)
|
| 1026 |
+
# Cache the most recent frame's feature (for repeated interactions with
|
| 1027 |
+
# a frame; we can use an LRU cache for more frames in the future).
|
| 1028 |
+
inference_state["cached_features"] = {frame_idx: (image, backbone_out)}
|
| 1029 |
+
if "tracker_backbone_out" in backbone_out:
|
| 1030 |
+
backbone_out = backbone_out["tracker_backbone_out"] # get backbone output
|
| 1031 |
+
|
| 1032 |
+
# expand the features to have the same dimension as the number of objects
|
| 1033 |
+
expanded_image = image.expand(batch_size, -1, -1, -1)
|
| 1034 |
+
expanded_backbone_out = {
|
| 1035 |
+
"backbone_fpn": backbone_out["backbone_fpn"].copy(),
|
| 1036 |
+
"vision_pos_enc": backbone_out["vision_pos_enc"].copy(),
|
| 1037 |
+
}
|
| 1038 |
+
for i, feat in enumerate(expanded_backbone_out["backbone_fpn"]):
|
| 1039 |
+
feat = feat.expand(batch_size, -1, -1, -1)
|
| 1040 |
+
expanded_backbone_out["backbone_fpn"][i] = feat
|
| 1041 |
+
for i, pos in enumerate(expanded_backbone_out["vision_pos_enc"]):
|
| 1042 |
+
pos = pos.expand(batch_size, -1, -1, -1)
|
| 1043 |
+
expanded_backbone_out["vision_pos_enc"][i] = pos
|
| 1044 |
+
|
| 1045 |
+
features = self._prepare_backbone_features(expanded_backbone_out)
|
| 1046 |
+
features = (expanded_image,) + features
|
| 1047 |
+
return features
|
| 1048 |
+
|
| 1049 |
+
def _run_single_frame_inference(
|
| 1050 |
+
self,
|
| 1051 |
+
inference_state,
|
| 1052 |
+
output_dict,
|
| 1053 |
+
frame_idx,
|
| 1054 |
+
batch_size,
|
| 1055 |
+
is_init_cond_frame,
|
| 1056 |
+
point_inputs,
|
| 1057 |
+
mask_inputs,
|
| 1058 |
+
reverse,
|
| 1059 |
+
run_mem_encoder,
|
| 1060 |
+
prev_sam_mask_logits=None,
|
| 1061 |
+
use_prev_mem_frame=True,
|
| 1062 |
+
):
|
| 1063 |
+
"""Run tracking on a single frame based on current inputs and previous memory."""
|
| 1064 |
+
# Retrieve correct image features
|
| 1065 |
+
(
|
| 1066 |
+
image,
|
| 1067 |
+
_,
|
| 1068 |
+
current_vision_feats,
|
| 1069 |
+
current_vision_pos_embeds,
|
| 1070 |
+
feat_sizes,
|
| 1071 |
+
) = self._get_image_feature(inference_state, frame_idx, batch_size)
|
| 1072 |
+
|
| 1073 |
+
# point and mask should not appear as input simultaneously on the same frame
|
| 1074 |
+
assert point_inputs is None or mask_inputs is None
|
| 1075 |
+
current_out = self.track_step(
|
| 1076 |
+
frame_idx=frame_idx,
|
| 1077 |
+
is_init_cond_frame=is_init_cond_frame,
|
| 1078 |
+
current_vision_feats=current_vision_feats,
|
| 1079 |
+
current_vision_pos_embeds=current_vision_pos_embeds,
|
| 1080 |
+
feat_sizes=feat_sizes,
|
| 1081 |
+
image=image,
|
| 1082 |
+
point_inputs=point_inputs,
|
| 1083 |
+
mask_inputs=mask_inputs,
|
| 1084 |
+
output_dict=output_dict,
|
| 1085 |
+
num_frames=inference_state["num_frames"],
|
| 1086 |
+
track_in_reverse=reverse,
|
| 1087 |
+
run_mem_encoder=run_mem_encoder,
|
| 1088 |
+
prev_sam_mask_logits=prev_sam_mask_logits,
|
| 1089 |
+
use_prev_mem_frame=use_prev_mem_frame,
|
| 1090 |
+
)
|
| 1091 |
+
|
| 1092 |
+
# optionally offload the output to CPU memory to save GPU space
|
| 1093 |
+
storage_device = inference_state["storage_device"]
|
| 1094 |
+
maskmem_features = current_out["maskmem_features"]
|
| 1095 |
+
if maskmem_features is not None:
|
| 1096 |
+
maskmem_features = maskmem_features.to(torch.bfloat16)
|
| 1097 |
+
maskmem_features = maskmem_features.to(storage_device, non_blocking=True)
|
| 1098 |
+
pred_masks_gpu = current_out["pred_masks"]
|
| 1099 |
+
pred_masks = pred_masks_gpu.to(storage_device, non_blocking=True)
|
| 1100 |
+
# "maskmem_pos_enc" is the same across frames, so we only need to store one copy of it
|
| 1101 |
+
maskmem_pos_enc = self._get_maskmem_pos_enc(inference_state, current_out)
|
| 1102 |
+
# object pointer is a small tensor, so we always keep it on GPU memory for fast access
|
| 1103 |
+
obj_ptr = current_out["obj_ptr"]
|
| 1104 |
+
object_score_logits = current_out["object_score_logits"]
|
| 1105 |
+
# make a compact version of this frame's output to reduce the state size
|
| 1106 |
+
compact_current_out = {
|
| 1107 |
+
"maskmem_features": maskmem_features,
|
| 1108 |
+
"maskmem_pos_enc": maskmem_pos_enc,
|
| 1109 |
+
"pred_masks": pred_masks,
|
| 1110 |
+
"obj_ptr": obj_ptr,
|
| 1111 |
+
"object_score_logits": object_score_logits,
|
| 1112 |
+
}
|
| 1113 |
+
if self.use_memory_selection:
|
| 1114 |
+
compact_current_out["iou_score"] = current_out["iou_score"]
|
| 1115 |
+
compact_current_out["eff_iou_score"] = current_out["eff_iou_score"]
|
| 1116 |
+
return compact_current_out, pred_masks_gpu
|
| 1117 |
+
|
| 1118 |
+
def _run_memory_encoder(
|
| 1119 |
+
self,
|
| 1120 |
+
inference_state,
|
| 1121 |
+
frame_idx,
|
| 1122 |
+
batch_size,
|
| 1123 |
+
high_res_masks,
|
| 1124 |
+
object_score_logits,
|
| 1125 |
+
is_mask_from_pts,
|
| 1126 |
+
):
|
| 1127 |
+
"""
|
| 1128 |
+
Run the memory encoder on `high_res_masks`. This is usually after applying
|
| 1129 |
+
non-overlapping constraints to object scores. Since their scores changed, their
|
| 1130 |
+
memory also need to be computed again with the memory encoder.
|
| 1131 |
+
"""
|
| 1132 |
+
# Retrieve correct image features
|
| 1133 |
+
image, _, current_vision_feats, _, feat_sizes = self._get_image_feature(
|
| 1134 |
+
inference_state, frame_idx, batch_size
|
| 1135 |
+
)
|
| 1136 |
+
maskmem_features, maskmem_pos_enc = self._encode_new_memory(
|
| 1137 |
+
image=image,
|
| 1138 |
+
current_vision_feats=current_vision_feats,
|
| 1139 |
+
feat_sizes=feat_sizes,
|
| 1140 |
+
pred_masks_high_res=high_res_masks,
|
| 1141 |
+
object_score_logits=object_score_logits,
|
| 1142 |
+
is_mask_from_pts=is_mask_from_pts,
|
| 1143 |
+
)
|
| 1144 |
+
|
| 1145 |
+
# optionally offload the output to CPU memory to save GPU space
|
| 1146 |
+
storage_device = inference_state["storage_device"]
|
| 1147 |
+
maskmem_features = maskmem_features.to(torch.bfloat16)
|
| 1148 |
+
maskmem_features = maskmem_features.to(storage_device, non_blocking=True)
|
| 1149 |
+
# "maskmem_pos_enc" is the same across frames, so we only need to store one copy of it
|
| 1150 |
+
maskmem_pos_enc = self._get_maskmem_pos_enc(
|
| 1151 |
+
inference_state, {"maskmem_pos_enc": maskmem_pos_enc}
|
| 1152 |
+
)
|
| 1153 |
+
return maskmem_features, maskmem_pos_enc
|
| 1154 |
+
|
| 1155 |
+
def _get_maskmem_pos_enc(self, inference_state, current_out):
|
| 1156 |
+
"""
|
| 1157 |
+
`maskmem_pos_enc` is the same across frames and objects, so we cache it as
|
| 1158 |
+
a constant in the inference session to reduce session storage size.
|
| 1159 |
+
"""
|
| 1160 |
+
model_constants = inference_state["constants"]
|
| 1161 |
+
# "out_maskmem_pos_enc" should be either a list of tensors or None
|
| 1162 |
+
out_maskmem_pos_enc = current_out["maskmem_pos_enc"]
|
| 1163 |
+
if out_maskmem_pos_enc is not None:
|
| 1164 |
+
if "maskmem_pos_enc" not in model_constants:
|
| 1165 |
+
assert isinstance(out_maskmem_pos_enc, list)
|
| 1166 |
+
# only take the slice for one object, since it's same across objects
|
| 1167 |
+
maskmem_pos_enc = [x[0:1].clone() for x in out_maskmem_pos_enc]
|
| 1168 |
+
model_constants["maskmem_pos_enc"] = maskmem_pos_enc
|
| 1169 |
+
else:
|
| 1170 |
+
maskmem_pos_enc = model_constants["maskmem_pos_enc"]
|
| 1171 |
+
# expand the cached maskmem_pos_enc to the actual batch size
|
| 1172 |
+
batch_size = out_maskmem_pos_enc[0].size(0)
|
| 1173 |
+
expanded_maskmem_pos_enc = [
|
| 1174 |
+
x.expand(batch_size, -1, -1, -1) for x in maskmem_pos_enc
|
| 1175 |
+
]
|
| 1176 |
+
else:
|
| 1177 |
+
expanded_maskmem_pos_enc = None
|
| 1178 |
+
return expanded_maskmem_pos_enc
|
| 1179 |
+
|
| 1180 |
+
@torch.inference_mode()
|
| 1181 |
+
def remove_object(self, inference_state, obj_id, strict=False, need_output=True):
|
| 1182 |
+
"""
|
| 1183 |
+
Remove an object id from the tracking state. If strict is True, we check whether
|
| 1184 |
+
the object id actually exists and raise an error if it doesn't exist.
|
| 1185 |
+
"""
|
| 1186 |
+
old_obj_idx_to_rm = inference_state["obj_id_to_idx"].get(obj_id, None)
|
| 1187 |
+
updated_frames = []
|
| 1188 |
+
# Check whether this object_id to remove actually exists and possibly raise an error.
|
| 1189 |
+
if old_obj_idx_to_rm is None:
|
| 1190 |
+
if not strict:
|
| 1191 |
+
return inference_state["obj_ids"], updated_frames
|
| 1192 |
+
raise RuntimeError(
|
| 1193 |
+
f"Cannot remove object id {obj_id} as it doesn't exist. "
|
| 1194 |
+
f"All existing object ids: {inference_state['obj_ids']}."
|
| 1195 |
+
)
|
| 1196 |
+
|
| 1197 |
+
# If this is the only remaining object id, we simply reset the state.
|
| 1198 |
+
if len(inference_state["obj_id_to_idx"]) == 1:
|
| 1199 |
+
self.clear_all_points_in_video(inference_state)
|
| 1200 |
+
return inference_state["obj_ids"], updated_frames
|
| 1201 |
+
|
| 1202 |
+
# There are still remaining objects after removing this object id. In this case,
|
| 1203 |
+
# we need to delete the object storage from inference state tensors.
|
| 1204 |
+
# Step 0: clear the input on those frames where this object id has point or mask input
|
| 1205 |
+
# (note that this step is required as it might downgrade conditioning frames to
|
| 1206 |
+
# non-conditioning ones)
|
| 1207 |
+
obj_input_frames_inds = set()
|
| 1208 |
+
obj_input_frames_inds.update(
|
| 1209 |
+
inference_state["point_inputs_per_obj"][old_obj_idx_to_rm]
|
| 1210 |
+
)
|
| 1211 |
+
obj_input_frames_inds.update(
|
| 1212 |
+
inference_state["mask_inputs_per_obj"][old_obj_idx_to_rm]
|
| 1213 |
+
)
|
| 1214 |
+
for frame_idx in obj_input_frames_inds:
|
| 1215 |
+
self.clear_all_points_in_frame(
|
| 1216 |
+
inference_state, frame_idx, obj_id, need_output=False
|
| 1217 |
+
)
|
| 1218 |
+
|
| 1219 |
+
# Step 1: Update the object id mapping (note that it must be done after Step 0,
|
| 1220 |
+
# since Step 0 still requires the old object id mappings in inference_state)
|
| 1221 |
+
old_obj_ids = inference_state["obj_ids"]
|
| 1222 |
+
old_obj_inds = list(range(len(old_obj_ids)))
|
| 1223 |
+
remain_old_obj_inds = old_obj_inds.copy()
|
| 1224 |
+
remain_old_obj_inds.remove(old_obj_idx_to_rm)
|
| 1225 |
+
new_obj_ids = [old_obj_ids[old_idx] for old_idx in remain_old_obj_inds]
|
| 1226 |
+
new_obj_inds = list(range(len(new_obj_ids)))
|
| 1227 |
+
# build new mappings
|
| 1228 |
+
old_idx_to_new_idx = dict(zip(remain_old_obj_inds, new_obj_inds))
|
| 1229 |
+
inference_state["obj_id_to_idx"] = dict(zip(new_obj_ids, new_obj_inds))
|
| 1230 |
+
inference_state["obj_idx_to_id"] = dict(zip(new_obj_inds, new_obj_ids))
|
| 1231 |
+
inference_state["obj_ids"] = new_obj_ids
|
| 1232 |
+
|
| 1233 |
+
# Step 2: For per-object tensor storage, we shift their obj_idx in the dict keys.
|
| 1234 |
+
# (note that "consolidated_frame_inds" doesn't need to be updated in this step as
|
| 1235 |
+
# it's already handled in Step 0)
|
| 1236 |
+
def _map_keys(container):
|
| 1237 |
+
new_kvs = []
|
| 1238 |
+
for k in old_obj_inds:
|
| 1239 |
+
v = container.pop(k)
|
| 1240 |
+
if k in old_idx_to_new_idx:
|
| 1241 |
+
new_kvs.append((old_idx_to_new_idx[k], v))
|
| 1242 |
+
container.update(new_kvs)
|
| 1243 |
+
|
| 1244 |
+
_map_keys(inference_state["point_inputs_per_obj"])
|
| 1245 |
+
_map_keys(inference_state["mask_inputs_per_obj"])
|
| 1246 |
+
_map_keys(inference_state["output_dict_per_obj"])
|
| 1247 |
+
_map_keys(inference_state["temp_output_dict_per_obj"])
|
| 1248 |
+
|
| 1249 |
+
# Step 3: For packed tensor storage, we index the remaining ids and rebuild the per-object slices.
|
| 1250 |
+
def _slice_state(output_dict, storage_key):
|
| 1251 |
+
for frame_idx, out in output_dict[storage_key].items():
|
| 1252 |
+
out["maskmem_features"] = out["maskmem_features"][remain_old_obj_inds]
|
| 1253 |
+
out["maskmem_pos_enc"] = [
|
| 1254 |
+
x[remain_old_obj_inds] for x in out["maskmem_pos_enc"]
|
| 1255 |
+
]
|
| 1256 |
+
# "maskmem_pos_enc" is the same across frames, so we only need to store one copy of it
|
| 1257 |
+
out["maskmem_pos_enc"] = self._get_maskmem_pos_enc(inference_state, out)
|
| 1258 |
+
out["pred_masks"] = out["pred_masks"][remain_old_obj_inds]
|
| 1259 |
+
out["obj_ptr"] = out["obj_ptr"][remain_old_obj_inds]
|
| 1260 |
+
out["object_score_logits"] = out["object_score_logits"][
|
| 1261 |
+
remain_old_obj_inds
|
| 1262 |
+
]
|
| 1263 |
+
if self.use_memory_selection:
|
| 1264 |
+
out["iou_score"] = out["iou_score"][remain_old_obj_inds]
|
| 1265 |
+
out["eff_iou_score"] = self.cal_mem_score(
|
| 1266 |
+
out["object_score_logits"], out["iou_score"]
|
| 1267 |
+
) # recalculate the memory frame score
|
| 1268 |
+
# also update the per-object slices
|
| 1269 |
+
self._add_output_per_object(
|
| 1270 |
+
inference_state, frame_idx, out, storage_key
|
| 1271 |
+
)
|
| 1272 |
+
|
| 1273 |
+
_slice_state(inference_state["output_dict"], "cond_frame_outputs")
|
| 1274 |
+
_slice_state(inference_state["output_dict"], "non_cond_frame_outputs")
|
| 1275 |
+
|
| 1276 |
+
# Step 4: Further collect the outputs on those frames in `obj_input_frames_inds`, which
|
| 1277 |
+
# could show an updated mask for objects previously occluded by the object being removed
|
| 1278 |
+
if need_output:
|
| 1279 |
+
temp_output_dict_per_obj = inference_state["temp_output_dict_per_obj"]
|
| 1280 |
+
for frame_idx in obj_input_frames_inds:
|
| 1281 |
+
is_cond = any(
|
| 1282 |
+
frame_idx in obj_temp_output_dict["cond_frame_outputs"]
|
| 1283 |
+
for obj_temp_output_dict in temp_output_dict_per_obj.values()
|
| 1284 |
+
)
|
| 1285 |
+
consolidated_out = self._consolidate_temp_output_across_obj(
|
| 1286 |
+
inference_state,
|
| 1287 |
+
frame_idx,
|
| 1288 |
+
is_cond=is_cond,
|
| 1289 |
+
run_mem_encoder=False,
|
| 1290 |
+
consolidate_at_video_res=True,
|
| 1291 |
+
)
|
| 1292 |
+
_, video_res_masks = self._get_orig_video_res_output(
|
| 1293 |
+
inference_state, consolidated_out["pred_masks_video_res"]
|
| 1294 |
+
)
|
| 1295 |
+
updated_frames.append((frame_idx, video_res_masks))
|
| 1296 |
+
|
| 1297 |
+
return inference_state["obj_ids"], updated_frames
|
| 1298 |
+
|
| 1299 |
+
def _clear_non_cond_mem_around_input(self, inference_state, frame_idx):
|
| 1300 |
+
"""
|
| 1301 |
+
Remove the non-conditioning memory around the input frame. When users provide
|
| 1302 |
+
correction clicks, the surrounding frames' non-conditioning memories can still
|
| 1303 |
+
contain outdated object appearance information and could confuse the model.
|
| 1304 |
+
|
| 1305 |
+
This method clears those non-conditioning memories surrounding the interacted
|
| 1306 |
+
frame to avoid giving the model both old and new information about the object.
|
| 1307 |
+
"""
|
| 1308 |
+
r = self.memory_temporal_stride_for_eval
|
| 1309 |
+
frame_idx_begin = frame_idx - r * self.num_maskmem
|
| 1310 |
+
frame_idx_end = frame_idx + r * self.num_maskmem
|
| 1311 |
+
batch_size = self._get_obj_num(inference_state)
|
| 1312 |
+
for obj_idx in range(batch_size):
|
| 1313 |
+
obj_output_dict = inference_state["output_dict_per_obj"][obj_idx]
|
| 1314 |
+
non_cond_frame_outputs = obj_output_dict["non_cond_frame_outputs"]
|
| 1315 |
+
for t in range(frame_idx_begin, frame_idx_end + 1):
|
| 1316 |
+
non_cond_frame_outputs.pop(t, None)
|
| 1317 |
+
|
| 1318 |
+
def _suppress_shrinked_masks(
|
| 1319 |
+
self, pred_masks, new_pred_masks, shrink_threshold=0.3
|
| 1320 |
+
):
|
| 1321 |
+
area_before = (pred_masks > 0).sum(dim=(-1, -2))
|
| 1322 |
+
area_after = (new_pred_masks > 0).sum(dim=(-1, -2))
|
| 1323 |
+
area_before = torch.clamp(area_before, min=1.0)
|
| 1324 |
+
area_ratio = area_after / area_before
|
| 1325 |
+
keep = area_ratio >= shrink_threshold
|
| 1326 |
+
keep_mask = keep[..., None, None].expand_as(pred_masks)
|
| 1327 |
+
pred_masks_after = torch.where(
|
| 1328 |
+
keep_mask, pred_masks, torch.clamp(pred_masks, max=-10.0)
|
| 1329 |
+
)
|
| 1330 |
+
return pred_masks_after
|
| 1331 |
+
|
| 1332 |
+
def _suppress_object_pw_area_shrinkage(self, pred_masks):
|
| 1333 |
+
"""
|
| 1334 |
+
This function suppresses masks that shrink in area after applying pixelwise non-overlapping constriants.
|
| 1335 |
+
Note that the final output can still be overlapping.
|
| 1336 |
+
"""
|
| 1337 |
+
# Apply pixel-wise non-overlapping constraint based on mask scores
|
| 1338 |
+
pixel_level_non_overlapping_masks = super()._apply_non_overlapping_constraints(
|
| 1339 |
+
pred_masks
|
| 1340 |
+
)
|
| 1341 |
+
# Fully suppress masks with high shrinkage (probably noisy) based on the pixel wise non-overlapping constraints
|
| 1342 |
+
# NOTE: The output of this function can be a no op if none of the masks shrinked by a large factor.
|
| 1343 |
+
pred_masks = self._suppress_shrinked_masks(
|
| 1344 |
+
pred_masks, pixel_level_non_overlapping_masks
|
| 1345 |
+
)
|
| 1346 |
+
return pred_masks
|
| 1347 |
+
|
| 1348 |
+
def _apply_object_wise_non_overlapping_constraints(
|
| 1349 |
+
self, pred_masks, obj_scores, background_value=-10.0
|
| 1350 |
+
):
|
| 1351 |
+
"""
|
| 1352 |
+
Applies non-overlapping constraints object wise (i.e. only one object can claim the overlapping region)
|
| 1353 |
+
"""
|
| 1354 |
+
# Replace pixel scores with object scores
|
| 1355 |
+
pred_masks_single_score = torch.where(
|
| 1356 |
+
pred_masks > 0, obj_scores[..., None, None], background_value
|
| 1357 |
+
)
|
| 1358 |
+
# Apply pixel-wise non-overlapping constraint based on mask scores
|
| 1359 |
+
pixel_level_non_overlapping_masks = super()._apply_non_overlapping_constraints(
|
| 1360 |
+
pred_masks_single_score
|
| 1361 |
+
)
|
| 1362 |
+
# Replace object scores with pixel scores. Note, that now only one object can claim the overlapping region
|
| 1363 |
+
pred_masks = torch.where(
|
| 1364 |
+
pixel_level_non_overlapping_masks > 0,
|
| 1365 |
+
pred_masks,
|
| 1366 |
+
torch.clamp(pred_masks, max=background_value),
|
| 1367 |
+
)
|
| 1368 |
+
return pred_masks
|
之前的代码版本/这一版注意力有问题/HuatuoGPT-Vision/MedSAM3/sam3/model/sam3_video_base.py
ADDED
|
@@ -0,0 +1,1767 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|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ved
|
| 2 |
+
|
| 3 |
+
import datetime
|
| 4 |
+
import logging
|
| 5 |
+
import math
|
| 6 |
+
import os
|
| 7 |
+
from collections import defaultdict
|
| 8 |
+
from copy import deepcopy
|
| 9 |
+
from enum import Enum
|
| 10 |
+
from typing import Any, Dict, List, Set
|
| 11 |
+
|
| 12 |
+
import numpy as np
|
| 13 |
+
import numpy.typing as npt
|
| 14 |
+
import torch
|
| 15 |
+
import torch.distributed as dist
|
| 16 |
+
import torch.nn.functional as F
|
| 17 |
+
|
| 18 |
+
from sam3 import perflib
|
| 19 |
+
from sam3.logger import get_logger
|
| 20 |
+
from sam3.model.box_ops import fast_diag_box_iou
|
| 21 |
+
from sam3.model.data_misc import BatchedDatapoint
|
| 22 |
+
from sam3.model.sam3_tracker_utils import fill_holes_in_mask_scores, mask_to_box
|
| 23 |
+
from sam3.perflib.masks_ops import mask_iou
|
| 24 |
+
from sam3.train.masks_ops import rle_encode
|
| 25 |
+
from torch import nn, Tensor
|
| 26 |
+
|
| 27 |
+
logger = get_logger(__name__)
|
| 28 |
+
|
| 29 |
+
|
| 30 |
+
class MaskletConfirmationStatus(Enum):
|
| 31 |
+
UNCONFIRMED = 1 # newly added masklet, not confirmed by any detection yet
|
| 32 |
+
CONFIRMED = 2 # confirmed by at least one detection
|
| 33 |
+
|
| 34 |
+
|
| 35 |
+
class Sam3VideoBase(nn.Module):
|
| 36 |
+
def __init__(
|
| 37 |
+
self,
|
| 38 |
+
detector: nn.Module,
|
| 39 |
+
tracker: nn.Module,
|
| 40 |
+
# prob threshold for detection outputs -- only keep detections above this threshold
|
| 41 |
+
# enters NMS and det-to-track matching
|
| 42 |
+
score_threshold_detection=0.5,
|
| 43 |
+
# IoU threshold for detection NMS
|
| 44 |
+
det_nms_thresh=0.0,
|
| 45 |
+
# IoU threshold for det-to-track matching -- a detection is considered "matched" to a tracklet it
|
| 46 |
+
# overlaps with a tracklet above this threshold -- it is often a loose threshold like 0.1
|
| 47 |
+
assoc_iou_thresh=0.5,
|
| 48 |
+
# IoU threshold for det-to-track matching, which is used to determine whether a masklet is "unmatched"
|
| 49 |
+
# by any detections -- it is often a stricter threshold like 0.5
|
| 50 |
+
trk_assoc_iou_thresh=0.5,
|
| 51 |
+
# prob threshold for a detection to be added as a new object
|
| 52 |
+
new_det_thresh=0.0,
|
| 53 |
+
# hotstart parameters: we hold off the outputs for `hotstart_delay` frames and
|
| 54 |
+
# 1) remove those tracklets unmatched by any detections based on `hotstart_unmatch_thresh`
|
| 55 |
+
# 2) remove those tracklets overlapping with one another based on `hotstart_dup_thresh`
|
| 56 |
+
hotstart_delay=0,
|
| 57 |
+
hotstart_unmatch_thresh=3,
|
| 58 |
+
hotstart_dup_thresh=3,
|
| 59 |
+
# Whether to suppress masks only within hotstart. If False, we can suppress masks even if they start before hotstart period.
|
| 60 |
+
suppress_unmatched_only_within_hotstart=True,
|
| 61 |
+
init_trk_keep_alive=0,
|
| 62 |
+
max_trk_keep_alive=8,
|
| 63 |
+
min_trk_keep_alive=-4,
|
| 64 |
+
# Threshold for suppressing overlapping objects based on recent occlusion
|
| 65 |
+
suppress_overlapping_based_on_recent_occlusion_threshold=0.0,
|
| 66 |
+
decrease_trk_keep_alive_for_empty_masklets=False,
|
| 67 |
+
o2o_matching_masklets_enable=False, # Enable hungarian matching to match existing masklets
|
| 68 |
+
suppress_det_close_to_boundary=False,
|
| 69 |
+
fill_hole_area=16,
|
| 70 |
+
# The maximum number of objects (masklets) to track across all GPUs (for no limit, set it to -1)
|
| 71 |
+
max_num_objects=-1,
|
| 72 |
+
recondition_every_nth_frame=-1,
|
| 73 |
+
# masket confirmation status (to suppress unconfirmed masklets)
|
| 74 |
+
masklet_confirmation_enable=False,
|
| 75 |
+
# a masklet is confirmed after being consecutively detected and matched for
|
| 76 |
+
# `masklet_confirmation_consecutive_det_thresh`
|
| 77 |
+
masklet_confirmation_consecutive_det_thresh=3,
|
| 78 |
+
# bbox heuristic parameters
|
| 79 |
+
reconstruction_bbox_iou_thresh=0.0,
|
| 80 |
+
reconstruction_bbox_det_score=0.0,
|
| 81 |
+
):
|
| 82 |
+
super().__init__()
|
| 83 |
+
self.detector = detector
|
| 84 |
+
self.tracker = tracker
|
| 85 |
+
self.score_threshold_detection = score_threshold_detection
|
| 86 |
+
self.det_nms_thresh = det_nms_thresh
|
| 87 |
+
self.assoc_iou_thresh = assoc_iou_thresh
|
| 88 |
+
self.trk_assoc_iou_thresh = trk_assoc_iou_thresh
|
| 89 |
+
self.new_det_thresh = new_det_thresh
|
| 90 |
+
|
| 91 |
+
# hotstart parameters
|
| 92 |
+
if hotstart_delay > 0:
|
| 93 |
+
assert hotstart_unmatch_thresh <= hotstart_delay
|
| 94 |
+
assert hotstart_dup_thresh <= hotstart_delay
|
| 95 |
+
self.hotstart_delay = hotstart_delay
|
| 96 |
+
self.hotstart_unmatch_thresh = hotstart_unmatch_thresh
|
| 97 |
+
self.hotstart_dup_thresh = hotstart_dup_thresh
|
| 98 |
+
self.suppress_unmatched_only_within_hotstart = (
|
| 99 |
+
suppress_unmatched_only_within_hotstart
|
| 100 |
+
)
|
| 101 |
+
self.init_trk_keep_alive = init_trk_keep_alive
|
| 102 |
+
self.max_trk_keep_alive = max_trk_keep_alive
|
| 103 |
+
self.min_trk_keep_alive = min_trk_keep_alive
|
| 104 |
+
self.suppress_overlapping_based_on_recent_occlusion_threshold = (
|
| 105 |
+
suppress_overlapping_based_on_recent_occlusion_threshold
|
| 106 |
+
)
|
| 107 |
+
self.suppress_det_close_to_boundary = suppress_det_close_to_boundary
|
| 108 |
+
self.decrease_trk_keep_alive_for_empty_masklets = (
|
| 109 |
+
decrease_trk_keep_alive_for_empty_masklets
|
| 110 |
+
)
|
| 111 |
+
self.o2o_matching_masklets_enable = o2o_matching_masklets_enable
|
| 112 |
+
self.fill_hole_area = fill_hole_area
|
| 113 |
+
self.eval()
|
| 114 |
+
self.rank = int(os.getenv("RANK", "0"))
|
| 115 |
+
self.world_size = int(os.getenv("WORLD_SIZE", "1"))
|
| 116 |
+
self._dist_pg_cpu = None # CPU process group (lazy-initialized on first use)
|
| 117 |
+
|
| 118 |
+
# the maximum object number
|
| 119 |
+
if max_num_objects > 0:
|
| 120 |
+
num_obj_for_compile = math.ceil(max_num_objects / self.world_size)
|
| 121 |
+
else:
|
| 122 |
+
max_num_objects = 10000 # no limit
|
| 123 |
+
num_obj_for_compile = 16
|
| 124 |
+
logger.info(f"setting {max_num_objects=} and {num_obj_for_compile=}")
|
| 125 |
+
self.max_num_objects = max_num_objects
|
| 126 |
+
self.num_obj_for_compile = num_obj_for_compile
|
| 127 |
+
self.recondition_every_nth_frame = recondition_every_nth_frame
|
| 128 |
+
self.masklet_confirmation_enable = masklet_confirmation_enable
|
| 129 |
+
self.masklet_confirmation_consecutive_det_thresh = (
|
| 130 |
+
masklet_confirmation_consecutive_det_thresh
|
| 131 |
+
)
|
| 132 |
+
self.reconstruction_bbox_iou_thresh = reconstruction_bbox_iou_thresh
|
| 133 |
+
self.reconstruction_bbox_det_score = reconstruction_bbox_det_score
|
| 134 |
+
|
| 135 |
+
@property
|
| 136 |
+
def device(self):
|
| 137 |
+
self._device = getattr(self, "_device", None) or next(self.parameters()).device
|
| 138 |
+
return self._device
|
| 139 |
+
|
| 140 |
+
def _init_dist_pg_cpu(self):
|
| 141 |
+
# a short 3-min timeout to quickly detect any synchronization failures
|
| 142 |
+
timeout_sec = int(os.getenv("SAM3_COLLECTIVE_OP_TIMEOUT_SEC", "180"))
|
| 143 |
+
timeout = datetime.timedelta(seconds=timeout_sec)
|
| 144 |
+
self._dist_pg_cpu = dist.new_group(backend="gloo", timeout=timeout)
|
| 145 |
+
|
| 146 |
+
def broadcast_python_obj_cpu(self, python_obj_list, src):
|
| 147 |
+
if self._dist_pg_cpu is None:
|
| 148 |
+
self._init_dist_pg_cpu()
|
| 149 |
+
dist.broadcast_object_list(python_obj_list, src=src, group=self._dist_pg_cpu)
|
| 150 |
+
|
| 151 |
+
def _det_track_one_frame(
|
| 152 |
+
self,
|
| 153 |
+
frame_idx: int,
|
| 154 |
+
num_frames: int,
|
| 155 |
+
reverse: bool,
|
| 156 |
+
input_batch: BatchedDatapoint,
|
| 157 |
+
geometric_prompt: Any,
|
| 158 |
+
tracker_states_local: List[Any],
|
| 159 |
+
tracker_metadata_prev: Dict[str, Any],
|
| 160 |
+
feature_cache: Dict,
|
| 161 |
+
orig_vid_height: int,
|
| 162 |
+
orig_vid_width: int,
|
| 163 |
+
is_image_only: bool = False,
|
| 164 |
+
allow_new_detections: bool = True,
|
| 165 |
+
):
|
| 166 |
+
"""
|
| 167 |
+
This function handles one-step inference for the DenseTracking model in an SPMD manner.
|
| 168 |
+
At a high-level, all GPUs execute the same function calls as if it's done on a single GPU,
|
| 169 |
+
while under the hood, some function calls involve distributed computation based on sharded
|
| 170 |
+
SAM2 states.
|
| 171 |
+
|
| 172 |
+
- `input_batch` contains image and other inputs on the entire video; it should be identical across GPUs
|
| 173 |
+
- `tracker_states_local` holds the local masklet information in this GPU shard
|
| 174 |
+
- `tracker_metadata_prev` manages the metadata for SAM2 objects, such as which masklet is hold on which GPUs
|
| 175 |
+
it contains both global and local masklet information
|
| 176 |
+
"""
|
| 177 |
+
|
| 178 |
+
# Step 1: run backbone and detector in a distributed manner -- this is done via Sam3ImageOnVideoMultiGPU,
|
| 179 |
+
# a MultiGPU model (assigned to `self.detector`) that shards frames in a round-robin manner.
|
| 180 |
+
# It returns a "det_out" dict for `frame_idx` and fills SAM2 backbone features for `frame_idx`
|
| 181 |
+
# into `feature_cache`. Despite its distributed inference under the hood, the results would be
|
| 182 |
+
# the same as if it is running backbone and detector for every frame on a single GPU.
|
| 183 |
+
det_out = self.run_backbone_and_detection(
|
| 184 |
+
frame_idx=frame_idx,
|
| 185 |
+
num_frames=num_frames,
|
| 186 |
+
reverse=reverse,
|
| 187 |
+
input_batch=input_batch,
|
| 188 |
+
geometric_prompt=geometric_prompt,
|
| 189 |
+
feature_cache=feature_cache,
|
| 190 |
+
allow_new_detections=allow_new_detections,
|
| 191 |
+
)
|
| 192 |
+
|
| 193 |
+
# Step 2: each GPU propagates its local SAM2 states to get the SAM2 prediction masks.
|
| 194 |
+
# the returned `tracker_low_res_masks_global` contains the concatenated masklet predictions
|
| 195 |
+
# gathered from all GPUs (as if they are propagated on a single GPU). Note that this step only
|
| 196 |
+
# runs the SAM2 propagation step, but doesn't encode new memory for the predicted masks;
|
| 197 |
+
# we defer memory encoding to `run_tracker_update_execution_phase` after resolving all heuristics.
|
| 198 |
+
if tracker_metadata_prev == {}:
|
| 199 |
+
# initialize masklet metadata if it's uninitialized (empty dict)
|
| 200 |
+
tracker_metadata_prev.update(self._initialize_metadata())
|
| 201 |
+
tracker_low_res_masks_global, tracker_obj_scores_global = (
|
| 202 |
+
self.run_tracker_propagation(
|
| 203 |
+
frame_idx=frame_idx,
|
| 204 |
+
num_frames=num_frames,
|
| 205 |
+
reverse=reverse,
|
| 206 |
+
tracker_states_local=tracker_states_local,
|
| 207 |
+
tracker_metadata_prev=tracker_metadata_prev,
|
| 208 |
+
)
|
| 209 |
+
)
|
| 210 |
+
|
| 211 |
+
# Step 3: based on detection outputs and the propagated SAM2 prediction masks, we make plans
|
| 212 |
+
# for SAM2 masklet updates (i.e. which objects to add and remove, how to load-balance them, etc).
|
| 213 |
+
# We also run SAM2 memory encoder globally in this step to resolve non-overlapping constraints.
|
| 214 |
+
# **This step should involve all the heuristics needed for any updates.** Most of the update
|
| 215 |
+
# planning will be done on the master rank (GPU 0) and the resulting plan `tracker_update_plan` is
|
| 216 |
+
# broadcasted to other GPUs (to be executed in a distributed manner). This step also generates the
|
| 217 |
+
# new masklet metadata `tracker_metadata_new` (based on its previous version `tracker_metadata_prev`).
|
| 218 |
+
tracker_update_plan, tracker_metadata_new = (
|
| 219 |
+
self.run_tracker_update_planning_phase(
|
| 220 |
+
frame_idx=frame_idx,
|
| 221 |
+
num_frames=num_frames,
|
| 222 |
+
reverse=reverse,
|
| 223 |
+
det_out=det_out,
|
| 224 |
+
tracker_low_res_masks_global=tracker_low_res_masks_global,
|
| 225 |
+
tracker_obj_scores_global=tracker_obj_scores_global,
|
| 226 |
+
tracker_metadata_prev=tracker_metadata_prev,
|
| 227 |
+
tracker_states_local=tracker_states_local,
|
| 228 |
+
is_image_only=is_image_only,
|
| 229 |
+
)
|
| 230 |
+
)
|
| 231 |
+
|
| 232 |
+
# Get reconditioning info from the update plan
|
| 233 |
+
reconditioned_obj_ids = tracker_update_plan.get("reconditioned_obj_ids", set())
|
| 234 |
+
det_to_matched_trk_obj_ids = tracker_update_plan.get(
|
| 235 |
+
"det_to_matched_trk_obj_ids", {}
|
| 236 |
+
)
|
| 237 |
+
|
| 238 |
+
# Step 4: based on `tracker_update_plan`, each GPU executes the update w.r.t. its local SAM2 inference states
|
| 239 |
+
tracker_states_local_new = self.run_tracker_update_execution_phase(
|
| 240 |
+
frame_idx=frame_idx,
|
| 241 |
+
num_frames=num_frames,
|
| 242 |
+
reverse=reverse,
|
| 243 |
+
det_out=det_out,
|
| 244 |
+
tracker_states_local=tracker_states_local,
|
| 245 |
+
tracker_update_plan=tracker_update_plan,
|
| 246 |
+
orig_vid_height=orig_vid_height,
|
| 247 |
+
orig_vid_width=orig_vid_width,
|
| 248 |
+
feature_cache=feature_cache,
|
| 249 |
+
)
|
| 250 |
+
|
| 251 |
+
# Step 5: finally, build the outputs for this frame (it only needs to be done on GPU 0 since
|
| 252 |
+
# only GPU 0 will send outputs to the server).
|
| 253 |
+
if self.rank == 0:
|
| 254 |
+
obj_id_to_mask = self.build_outputs(
|
| 255 |
+
frame_idx=frame_idx,
|
| 256 |
+
num_frames=num_frames,
|
| 257 |
+
reverse=reverse,
|
| 258 |
+
det_out=det_out,
|
| 259 |
+
tracker_low_res_masks_global=tracker_low_res_masks_global,
|
| 260 |
+
tracker_obj_scores_global=tracker_obj_scores_global,
|
| 261 |
+
tracker_metadata_prev=tracker_metadata_prev,
|
| 262 |
+
tracker_update_plan=tracker_update_plan,
|
| 263 |
+
orig_vid_height=orig_vid_height,
|
| 264 |
+
orig_vid_width=orig_vid_width,
|
| 265 |
+
reconditioned_obj_ids=reconditioned_obj_ids,
|
| 266 |
+
det_to_matched_trk_obj_ids=det_to_matched_trk_obj_ids,
|
| 267 |
+
)
|
| 268 |
+
obj_id_to_score = tracker_metadata_new["obj_id_to_score"]
|
| 269 |
+
else:
|
| 270 |
+
obj_id_to_mask, obj_id_to_score = {}, {} # dummy outputs on other GPUs
|
| 271 |
+
# a few statistics for the current frame as a part of the output
|
| 272 |
+
frame_stats = {
|
| 273 |
+
"num_obj_tracked": np.sum(tracker_metadata_new["num_obj_per_gpu"]),
|
| 274 |
+
"num_obj_dropped": tracker_update_plan["num_obj_dropped_due_to_limit"],
|
| 275 |
+
}
|
| 276 |
+
# add tracker scores to metadata, it should be fired for frames except the first frame
|
| 277 |
+
if tracker_obj_scores_global.shape[0] > 0:
|
| 278 |
+
# Convert tracker_obj_scores_global to sigmoid scores before updating
|
| 279 |
+
tracker_obj_scores_global = tracker_obj_scores_global.sigmoid().tolist()
|
| 280 |
+
tracker_obj_ids = tracker_metadata_prev["obj_ids_all_gpu"]
|
| 281 |
+
tracker_metadata_new["obj_id_to_tracker_score_frame_wise"][
|
| 282 |
+
frame_idx
|
| 283 |
+
].update(dict(zip(tracker_obj_ids, tracker_obj_scores_global)))
|
| 284 |
+
return (
|
| 285 |
+
obj_id_to_mask, # a dict: obj_id --> output mask
|
| 286 |
+
obj_id_to_score, # a dict: obj_id --> output score (prob)
|
| 287 |
+
tracker_states_local_new,
|
| 288 |
+
tracker_metadata_new,
|
| 289 |
+
frame_stats,
|
| 290 |
+
tracker_obj_scores_global, # a dict: obj_id --> tracker frame-level scores
|
| 291 |
+
)
|
| 292 |
+
|
| 293 |
+
def _suppress_detections_close_to_boundary(self, boxes, margin=0.025):
|
| 294 |
+
"""
|
| 295 |
+
Suppress detections too close to image edges (for normalized boxes).
|
| 296 |
+
|
| 297 |
+
boxes: (N, 4) in xyxy format, normalized [0,1]
|
| 298 |
+
margin: fraction of image
|
| 299 |
+
"""
|
| 300 |
+
x_min, y_min, x_max, y_max = boxes.unbind(-1)
|
| 301 |
+
x_c = (x_min + x_max) / 2
|
| 302 |
+
y_c = (y_min + y_max) / 2
|
| 303 |
+
keep = (
|
| 304 |
+
(x_c > margin)
|
| 305 |
+
& (x_c < 1.0 - margin)
|
| 306 |
+
& (y_c > margin)
|
| 307 |
+
& (y_c < 1.0 - margin)
|
| 308 |
+
)
|
| 309 |
+
|
| 310 |
+
return keep
|
| 311 |
+
|
| 312 |
+
def run_backbone_and_detection(
|
| 313 |
+
self,
|
| 314 |
+
frame_idx: int,
|
| 315 |
+
num_frames: int,
|
| 316 |
+
input_batch: BatchedDatapoint,
|
| 317 |
+
geometric_prompt: Any,
|
| 318 |
+
feature_cache: Dict,
|
| 319 |
+
reverse: bool,
|
| 320 |
+
allow_new_detections: bool,
|
| 321 |
+
):
|
| 322 |
+
# Step 1: if text feature is not cached in `feature_cache`, compute and cache it
|
| 323 |
+
text_batch_key = tuple(input_batch.find_text_batch)
|
| 324 |
+
if "text" not in feature_cache or text_batch_key not in feature_cache["text"]:
|
| 325 |
+
text_outputs = self.detector.backbone.forward_text(
|
| 326 |
+
input_batch.find_text_batch, device=self.device
|
| 327 |
+
)
|
| 328 |
+
# note: we only cache the text feature of the most recent prompt
|
| 329 |
+
feature_cache["text"] = {text_batch_key: text_outputs}
|
| 330 |
+
else:
|
| 331 |
+
text_outputs = feature_cache["text"][text_batch_key]
|
| 332 |
+
|
| 333 |
+
# Step 2: run backbone, detector, and post-processing with NMS
|
| 334 |
+
if "multigpu_buffer" not in feature_cache:
|
| 335 |
+
# "multigpu_buffer" is a buffer cache used by `self.detector` and it needs
|
| 336 |
+
# to be passed to `forward_video_grounding_multigpu` for every call
|
| 337 |
+
feature_cache["multigpu_buffer"] = {}
|
| 338 |
+
|
| 339 |
+
# Extract max_frame_num_to_track from feature_cache if available
|
| 340 |
+
tracking_bounds = feature_cache.get("tracking_bounds", {})
|
| 341 |
+
max_frame_num_to_track = tracking_bounds.get("max_frame_num_to_track")
|
| 342 |
+
start_frame_idx = tracking_bounds.get("propagate_in_video_start_frame_idx")
|
| 343 |
+
|
| 344 |
+
sam3_image_out, _ = self.detector.forward_video_grounding_multigpu(
|
| 345 |
+
backbone_out={
|
| 346 |
+
"img_batch_all_stages": input_batch.img_batch,
|
| 347 |
+
**text_outputs,
|
| 348 |
+
},
|
| 349 |
+
find_inputs=input_batch.find_inputs,
|
| 350 |
+
geometric_prompt=geometric_prompt,
|
| 351 |
+
frame_idx=frame_idx,
|
| 352 |
+
num_frames=num_frames,
|
| 353 |
+
multigpu_buffer=feature_cache["multigpu_buffer"],
|
| 354 |
+
track_in_reverse=reverse,
|
| 355 |
+
# also get the SAM2 backbone features
|
| 356 |
+
return_tracker_backbone_feats=True,
|
| 357 |
+
# run NMS as a part of distributed computation
|
| 358 |
+
run_nms=self.det_nms_thresh > 0.0,
|
| 359 |
+
nms_prob_thresh=self.score_threshold_detection,
|
| 360 |
+
nms_iou_thresh=self.det_nms_thresh,
|
| 361 |
+
# pass max_frame_num_to_track to respect tracking limits
|
| 362 |
+
max_frame_num_to_track=max_frame_num_to_track,
|
| 363 |
+
propagate_in_video_start_frame_idx=start_frame_idx,
|
| 364 |
+
)
|
| 365 |
+
# note: detections in `sam3_image_out` has already gone through NMS
|
| 366 |
+
pred_probs = sam3_image_out["pred_logits"].squeeze(-1).sigmoid()
|
| 367 |
+
if not allow_new_detections:
|
| 368 |
+
pred_probs = pred_probs - 1e8 # make sure no detections are kept
|
| 369 |
+
pred_boxes_xyxy = sam3_image_out["pred_boxes_xyxy"]
|
| 370 |
+
pred_masks = sam3_image_out["pred_masks"]
|
| 371 |
+
# get the positive detection outputs above threshold
|
| 372 |
+
pos_pred_idx = torch.where(pred_probs > self.score_threshold_detection)
|
| 373 |
+
det_out = {
|
| 374 |
+
"bbox": pred_boxes_xyxy[pos_pred_idx[0], pos_pred_idx[1]],
|
| 375 |
+
"mask": pred_masks[pos_pred_idx[0], pos_pred_idx[1]],
|
| 376 |
+
"scores": pred_probs[pos_pred_idx[0], pos_pred_idx[1]],
|
| 377 |
+
}
|
| 378 |
+
|
| 379 |
+
# Step 3: build SAM2 backbone features and store them in `feature_cache`
|
| 380 |
+
backbone_cache = {}
|
| 381 |
+
sam_mask_decoder = self.tracker.sam_mask_decoder
|
| 382 |
+
tracker_backbone_fpn = [
|
| 383 |
+
sam_mask_decoder.conv_s0(sam3_image_out["tracker_backbone_fpn_0"]),
|
| 384 |
+
sam_mask_decoder.conv_s1(sam3_image_out["tracker_backbone_fpn_1"]),
|
| 385 |
+
sam3_image_out["tracker_backbone_fpn_2"], # fpn_2 doesn't need conv
|
| 386 |
+
]
|
| 387 |
+
tracker_backbone_out = {
|
| 388 |
+
"vision_features": tracker_backbone_fpn[-1], # top-level feature
|
| 389 |
+
"vision_pos_enc": sam3_image_out["tracker_backbone_pos_enc"],
|
| 390 |
+
"backbone_fpn": tracker_backbone_fpn,
|
| 391 |
+
}
|
| 392 |
+
backbone_cache["tracker_backbone_out"] = tracker_backbone_out
|
| 393 |
+
feature_cache[frame_idx] = (
|
| 394 |
+
input_batch.img_batch[frame_idx],
|
| 395 |
+
backbone_cache,
|
| 396 |
+
)
|
| 397 |
+
# remove from `feature_cache` old features to save GPU memory
|
| 398 |
+
feature_cache.pop(frame_idx - 1 if not reverse else frame_idx + 1, None)
|
| 399 |
+
return det_out
|
| 400 |
+
|
| 401 |
+
def run_tracker_propagation(
|
| 402 |
+
self,
|
| 403 |
+
frame_idx: int,
|
| 404 |
+
num_frames: int,
|
| 405 |
+
reverse: bool,
|
| 406 |
+
tracker_states_local: List[Any],
|
| 407 |
+
tracker_metadata_prev: Dict[str, npt.NDArray],
|
| 408 |
+
):
|
| 409 |
+
# Step 1: propagate the local SAM2 states to get the current frame's prediction
|
| 410 |
+
# `low_res_masks_local` of the existing masklets on this GPU
|
| 411 |
+
# - obj_ids_local: List[int] -- list of object IDs
|
| 412 |
+
# - low_res_masks_local: Tensor -- (num_local_obj, H_mask, W_mask)
|
| 413 |
+
obj_ids_local, low_res_masks_local, obj_scores_local = (
|
| 414 |
+
self._propogate_tracker_one_frame_local_gpu(
|
| 415 |
+
tracker_states_local, frame_idx=frame_idx, reverse=reverse
|
| 416 |
+
)
|
| 417 |
+
)
|
| 418 |
+
|
| 419 |
+
assert np.all(
|
| 420 |
+
obj_ids_local == tracker_metadata_prev["obj_ids_per_gpu"][self.rank]
|
| 421 |
+
), "{} != {}".format(
|
| 422 |
+
obj_ids_local, tracker_metadata_prev["obj_ids_per_gpu"][self.rank]
|
| 423 |
+
)
|
| 424 |
+
|
| 425 |
+
# Step 2: all-gather `low_res_masks_local` into `low_res_masks_global`
|
| 426 |
+
# - low_res_masks_global: Tensor -- (num_global_obj, H_mask, W_mask)
|
| 427 |
+
_, H_mask, W_mask = low_res_masks_local.shape
|
| 428 |
+
if self.world_size > 1:
|
| 429 |
+
# `low_res_masks_local` and `obj_scores_local` need to be contiguous and float32
|
| 430 |
+
# (they could be non-contiguous due to slicing and/or bfloat16 due to autocast)
|
| 431 |
+
low_res_masks_local = low_res_masks_local.float().contiguous()
|
| 432 |
+
obj_scores_local = obj_scores_local.float().contiguous()
|
| 433 |
+
num_obj_this_gpu = tracker_metadata_prev["num_obj_per_gpu"][self.rank]
|
| 434 |
+
assert low_res_masks_local.size(0) == num_obj_this_gpu
|
| 435 |
+
assert obj_scores_local.size(0) == num_obj_this_gpu
|
| 436 |
+
low_res_masks_peers = [
|
| 437 |
+
low_res_masks_local.new_empty(num_obj, H_mask, W_mask)
|
| 438 |
+
for num_obj in tracker_metadata_prev["num_obj_per_gpu"]
|
| 439 |
+
]
|
| 440 |
+
obj_scores_peers = [
|
| 441 |
+
obj_scores_local.new_empty(num_obj)
|
| 442 |
+
for num_obj in tracker_metadata_prev["num_obj_per_gpu"]
|
| 443 |
+
]
|
| 444 |
+
dist.all_gather(low_res_masks_peers, low_res_masks_local)
|
| 445 |
+
dist.all_gather(obj_scores_peers, obj_scores_local)
|
| 446 |
+
low_res_masks_global = torch.cat(low_res_masks_peers, dim=0)
|
| 447 |
+
obj_scores_global = torch.cat(obj_scores_peers, dim=0)
|
| 448 |
+
else:
|
| 449 |
+
low_res_masks_global = low_res_masks_local
|
| 450 |
+
obj_scores_global = obj_scores_local
|
| 451 |
+
return low_res_masks_global, obj_scores_global
|
| 452 |
+
|
| 453 |
+
def _recondition_masklets(
|
| 454 |
+
self,
|
| 455 |
+
frame_idx,
|
| 456 |
+
det_out: Dict[str, Tensor],
|
| 457 |
+
trk_id_to_max_iou_high_conf_det: List[int],
|
| 458 |
+
tracker_states_local: List[Any],
|
| 459 |
+
tracker_metadata: Dict[str, npt.NDArray],
|
| 460 |
+
tracker_obj_scores_global: Tensor,
|
| 461 |
+
):
|
| 462 |
+
# Recondition the masklets based on the new detections
|
| 463 |
+
for trk_obj_id, det_idx in trk_id_to_max_iou_high_conf_det.items():
|
| 464 |
+
new_mask = det_out["mask"][det_idx : det_idx + 1]
|
| 465 |
+
input_mask_res = self.tracker.input_mask_size
|
| 466 |
+
new_mask_binary = (
|
| 467 |
+
F.interpolate(
|
| 468 |
+
new_mask.unsqueeze(1),
|
| 469 |
+
size=(input_mask_res, input_mask_res),
|
| 470 |
+
mode="bilinear",
|
| 471 |
+
align_corners=False,
|
| 472 |
+
).squeeze(1)[0]
|
| 473 |
+
> 0
|
| 474 |
+
)
|
| 475 |
+
HIGH_CONF_THRESH = 0.8
|
| 476 |
+
reconditioned_states_idx = set()
|
| 477 |
+
obj_idx = np.where(tracker_metadata["obj_ids_all_gpu"] == trk_obj_id)[
|
| 478 |
+
0
|
| 479 |
+
].item()
|
| 480 |
+
obj_score = tracker_obj_scores_global[obj_idx]
|
| 481 |
+
for state_idx, inference_state in enumerate(tracker_states_local):
|
| 482 |
+
if (
|
| 483 |
+
trk_obj_id in inference_state["obj_ids"]
|
| 484 |
+
# NOTE: Goal of this condition is to avoid reconditioning masks that are occluded/low qualiy.
|
| 485 |
+
# Unfortunately, these can get reconditioned anyway due to batching. We should consider removing these heuristics.
|
| 486 |
+
and obj_score > HIGH_CONF_THRESH
|
| 487 |
+
):
|
| 488 |
+
logger.debug(
|
| 489 |
+
f"Adding new mask for track {trk_obj_id} at frame {frame_idx}. Objects {inference_state['obj_ids']} are all reconditioned."
|
| 490 |
+
)
|
| 491 |
+
self.tracker.add_new_mask(
|
| 492 |
+
inference_state=inference_state,
|
| 493 |
+
frame_idx=frame_idx,
|
| 494 |
+
obj_id=trk_obj_id,
|
| 495 |
+
mask=new_mask_binary,
|
| 496 |
+
)
|
| 497 |
+
reconditioned_states_idx.add(state_idx)
|
| 498 |
+
|
| 499 |
+
for idx in reconditioned_states_idx:
|
| 500 |
+
self.tracker.propagate_in_video_preflight(
|
| 501 |
+
tracker_states_local[idx], run_mem_encoder=True
|
| 502 |
+
)
|
| 503 |
+
return tracker_states_local
|
| 504 |
+
|
| 505 |
+
def run_tracker_update_planning_phase(
|
| 506 |
+
self,
|
| 507 |
+
frame_idx: int,
|
| 508 |
+
num_frames: int,
|
| 509 |
+
reverse: bool,
|
| 510 |
+
det_out: Dict[str, Tensor],
|
| 511 |
+
tracker_low_res_masks_global: Tensor,
|
| 512 |
+
tracker_obj_scores_global: Tensor,
|
| 513 |
+
tracker_metadata_prev: Dict[str, npt.NDArray],
|
| 514 |
+
tracker_states_local: List[Any],
|
| 515 |
+
is_image_only: bool = False,
|
| 516 |
+
):
|
| 517 |
+
# initialize new metadata from previous metadata (its values will be updated later)
|
| 518 |
+
tracker_metadata_new = {
|
| 519 |
+
"obj_ids_per_gpu": deepcopy(tracker_metadata_prev["obj_ids_per_gpu"]),
|
| 520 |
+
"obj_ids_all_gpu": None, # will be filled later
|
| 521 |
+
"num_obj_per_gpu": deepcopy(tracker_metadata_prev["num_obj_per_gpu"]),
|
| 522 |
+
"obj_id_to_score": deepcopy(tracker_metadata_prev["obj_id_to_score"]),
|
| 523 |
+
"obj_id_to_tracker_score_frame_wise": deepcopy(
|
| 524 |
+
tracker_metadata_prev["obj_id_to_tracker_score_frame_wise"]
|
| 525 |
+
),
|
| 526 |
+
"obj_id_to_last_occluded": {}, # will be filled later
|
| 527 |
+
"max_obj_id": deepcopy(tracker_metadata_prev["max_obj_id"]),
|
| 528 |
+
}
|
| 529 |
+
|
| 530 |
+
# Initialize reconditioned_obj_ids early to avoid UnboundLocalError
|
| 531 |
+
reconditioned_obj_ids = set()
|
| 532 |
+
|
| 533 |
+
# Step 1: make the update plan and resolve heuristics on GPU 0
|
| 534 |
+
det_mask_preds: Tensor = det_out["mask"] # low-res mask logits
|
| 535 |
+
det_scores_np: npt.NDArray = det_out["scores"].float().cpu().numpy()
|
| 536 |
+
det_bbox_xyxy: Tensor = det_out["bbox"]
|
| 537 |
+
if self.rank == 0:
|
| 538 |
+
# a) match detector and tracker masks and find new objects
|
| 539 |
+
(
|
| 540 |
+
new_det_fa_inds,
|
| 541 |
+
unmatched_trk_obj_ids,
|
| 542 |
+
det_to_matched_trk_obj_ids,
|
| 543 |
+
trk_id_to_max_iou_high_conf_det,
|
| 544 |
+
empty_trk_obj_ids,
|
| 545 |
+
) = self._associate_det_trk(
|
| 546 |
+
det_masks=det_mask_preds,
|
| 547 |
+
det_scores_np=det_scores_np,
|
| 548 |
+
trk_masks=tracker_low_res_masks_global,
|
| 549 |
+
trk_obj_ids=tracker_metadata_prev["obj_ids_all_gpu"],
|
| 550 |
+
)
|
| 551 |
+
if self.suppress_det_close_to_boundary:
|
| 552 |
+
keep = self._suppress_detections_close_to_boundary(
|
| 553 |
+
det_bbox_xyxy[new_det_fa_inds]
|
| 554 |
+
)
|
| 555 |
+
new_det_fa_inds = new_det_fa_inds[keep.cpu().numpy()]
|
| 556 |
+
|
| 557 |
+
# check whether we've hit the maximum number of objects we can track (and if so, drop some detections)
|
| 558 |
+
prev_obj_num = np.sum(tracker_metadata_prev["num_obj_per_gpu"])
|
| 559 |
+
new_det_num = len(new_det_fa_inds)
|
| 560 |
+
num_obj_dropped_due_to_limit = 0
|
| 561 |
+
if not is_image_only and prev_obj_num + new_det_num > self.max_num_objects:
|
| 562 |
+
logger.warning(
|
| 563 |
+
f"hitting {self.max_num_objects=} with {new_det_num=} and {prev_obj_num=}"
|
| 564 |
+
)
|
| 565 |
+
new_det_num_to_keep = self.max_num_objects - prev_obj_num
|
| 566 |
+
num_obj_dropped_due_to_limit = new_det_num - new_det_num_to_keep
|
| 567 |
+
new_det_fa_inds = self._drop_new_det_with_obj_limit(
|
| 568 |
+
new_det_fa_inds, det_scores_np, new_det_num_to_keep
|
| 569 |
+
)
|
| 570 |
+
assert len(new_det_fa_inds) == new_det_num_to_keep
|
| 571 |
+
new_det_num = len(new_det_fa_inds)
|
| 572 |
+
|
| 573 |
+
# assign object IDs to new detections and decide which GPU to place them
|
| 574 |
+
new_det_start_obj_id = tracker_metadata_prev["max_obj_id"] + 1
|
| 575 |
+
new_det_obj_ids = new_det_start_obj_id + np.arange(new_det_num)
|
| 576 |
+
prev_workload_per_gpu = tracker_metadata_prev["num_obj_per_gpu"]
|
| 577 |
+
new_det_gpu_ids = self._assign_new_det_to_gpus(
|
| 578 |
+
new_det_num=new_det_num,
|
| 579 |
+
prev_workload_per_gpu=prev_workload_per_gpu,
|
| 580 |
+
)
|
| 581 |
+
|
| 582 |
+
# b) handle hotstart heuristics to remove objects
|
| 583 |
+
# here `rank0_metadata` contains metadata stored on (and only accessible to) GPU 0;
|
| 584 |
+
# we avoid broadcasting them to other GPUs to save communication cost, assuming
|
| 585 |
+
# that `rank0_metadata` is not needed by other GPUs
|
| 586 |
+
rank0_metadata_new = deepcopy(tracker_metadata_prev["rank0_metadata"])
|
| 587 |
+
if not hasattr(self, "_warm_up_complete") or self._warm_up_complete:
|
| 588 |
+
obj_ids_newly_removed, rank0_metadata_new = self._process_hotstart(
|
| 589 |
+
frame_idx=frame_idx,
|
| 590 |
+
num_frames=num_frames,
|
| 591 |
+
reverse=reverse,
|
| 592 |
+
det_to_matched_trk_obj_ids=det_to_matched_trk_obj_ids,
|
| 593 |
+
new_det_obj_ids=new_det_obj_ids,
|
| 594 |
+
empty_trk_obj_ids=empty_trk_obj_ids,
|
| 595 |
+
unmatched_trk_obj_ids=unmatched_trk_obj_ids,
|
| 596 |
+
rank0_metadata=rank0_metadata_new,
|
| 597 |
+
tracker_metadata=tracker_metadata_prev,
|
| 598 |
+
)
|
| 599 |
+
else:
|
| 600 |
+
# if warm-up is not complete, we don't remove any objects
|
| 601 |
+
obj_ids_newly_removed = set()
|
| 602 |
+
tracker_metadata_new["rank0_metadata"] = rank0_metadata_new
|
| 603 |
+
|
| 604 |
+
# Step 2: broadcast the update plan to other GPUs
|
| 605 |
+
NUM_BROADCAST_ITEMS = 9
|
| 606 |
+
if self.rank == 0 and self.world_size > 1:
|
| 607 |
+
# `num_obj_per_gpu_on_rank0` is used for metadata consistency check on other GPUs
|
| 608 |
+
# (it's a small array with length==self.world_size, so broadcasting it is cheap)
|
| 609 |
+
num_obj_per_gpu_on_rank0 = tracker_metadata_prev["num_obj_per_gpu"]
|
| 610 |
+
update_plan = [
|
| 611 |
+
new_det_fa_inds,
|
| 612 |
+
new_det_obj_ids,
|
| 613 |
+
new_det_gpu_ids,
|
| 614 |
+
num_obj_per_gpu_on_rank0,
|
| 615 |
+
unmatched_trk_obj_ids,
|
| 616 |
+
det_to_matched_trk_obj_ids,
|
| 617 |
+
obj_ids_newly_removed,
|
| 618 |
+
num_obj_dropped_due_to_limit,
|
| 619 |
+
trk_id_to_max_iou_high_conf_det,
|
| 620 |
+
]
|
| 621 |
+
assert (
|
| 622 |
+
len(update_plan) == NUM_BROADCAST_ITEMS
|
| 623 |
+
), f"Manually update NUM_BROADCAST_ITEMS to be: {len(update_plan)}"
|
| 624 |
+
self.broadcast_python_obj_cpu(update_plan, src=0)
|
| 625 |
+
elif self.rank > 0 and self.world_size > 1:
|
| 626 |
+
update_plan = [
|
| 627 |
+
None
|
| 628 |
+
] * NUM_BROADCAST_ITEMS # other ranks receive the plan from rank 0
|
| 629 |
+
self.broadcast_python_obj_cpu(update_plan, src=0)
|
| 630 |
+
(
|
| 631 |
+
new_det_fa_inds,
|
| 632 |
+
new_det_obj_ids,
|
| 633 |
+
new_det_gpu_ids,
|
| 634 |
+
num_obj_per_gpu_on_rank0,
|
| 635 |
+
unmatched_trk_obj_ids,
|
| 636 |
+
det_to_matched_trk_obj_ids,
|
| 637 |
+
obj_ids_newly_removed,
|
| 638 |
+
num_obj_dropped_due_to_limit,
|
| 639 |
+
trk_id_to_max_iou_high_conf_det,
|
| 640 |
+
) = update_plan
|
| 641 |
+
# metadata consistency check: verify that the received `num_obj_per_gpu_on_rank0` is consistent with the local metadata
|
| 642 |
+
# it's critical that all GPUs agree on the previous number of objects (otherwise the inference might hang or fail silently)
|
| 643 |
+
if not np.all(
|
| 644 |
+
num_obj_per_gpu_on_rank0 == tracker_metadata_prev["num_obj_per_gpu"]
|
| 645 |
+
):
|
| 646 |
+
raise RuntimeError(
|
| 647 |
+
f"{self.rank=} received {num_obj_per_gpu_on_rank0=}, which is inconsistent with local record "
|
| 648 |
+
f"{tracker_metadata_prev['num_obj_per_gpu']=}. There's likely a bug in update planning or execution."
|
| 649 |
+
)
|
| 650 |
+
|
| 651 |
+
# `tracker_update_plan` should be identical on all GPUs after broadcasting
|
| 652 |
+
tracker_update_plan = {
|
| 653 |
+
"new_det_fa_inds": new_det_fa_inds, # npt.NDArray
|
| 654 |
+
"new_det_obj_ids": new_det_obj_ids, # npt.NDArray
|
| 655 |
+
"new_det_gpu_ids": new_det_gpu_ids, # npt.NDArray
|
| 656 |
+
"unmatched_trk_obj_ids": unmatched_trk_obj_ids, # npt.NDArray
|
| 657 |
+
"det_to_matched_trk_obj_ids": det_to_matched_trk_obj_ids, # dict
|
| 658 |
+
"obj_ids_newly_removed": obj_ids_newly_removed, # set
|
| 659 |
+
"num_obj_dropped_due_to_limit": num_obj_dropped_due_to_limit, # int
|
| 660 |
+
"trk_id_to_max_iou_high_conf_det": trk_id_to_max_iou_high_conf_det, # dict
|
| 661 |
+
"reconditioned_obj_ids": reconditioned_obj_ids, # set
|
| 662 |
+
}
|
| 663 |
+
|
| 664 |
+
# Step 3 (optional): recondition masklets based on high-confidence detections before memory encoding
|
| 665 |
+
# NOTE: Running this in execution phase (after memory encoding) can lead to suboptimal results
|
| 666 |
+
should_recondition_iou = False
|
| 667 |
+
|
| 668 |
+
# Evaluate tracklets for reconditioning based on bbox IoU mismatch with detections
|
| 669 |
+
if (
|
| 670 |
+
self.reconstruction_bbox_iou_thresh > 0
|
| 671 |
+
and len(trk_id_to_max_iou_high_conf_det) > 0
|
| 672 |
+
):
|
| 673 |
+
for trk_obj_id, det_idx in trk_id_to_max_iou_high_conf_det.items():
|
| 674 |
+
det_box = det_out["bbox"][det_idx]
|
| 675 |
+
det_score = det_out["scores"][det_idx]
|
| 676 |
+
|
| 677 |
+
try:
|
| 678 |
+
trk_idx = list(tracker_metadata_prev["obj_ids_all_gpu"]).index(
|
| 679 |
+
trk_obj_id
|
| 680 |
+
)
|
| 681 |
+
except ValueError:
|
| 682 |
+
continue # Skip if tracklet not found
|
| 683 |
+
|
| 684 |
+
tracker_mask = tracker_low_res_masks_global[trk_idx]
|
| 685 |
+
mask_binary = tracker_mask > 0
|
| 686 |
+
mask_area = mask_binary.sum().item()
|
| 687 |
+
|
| 688 |
+
if mask_area == 0:
|
| 689 |
+
continue # Skip tracklets with zero mask area
|
| 690 |
+
|
| 691 |
+
# Get bounding box from SAM2 mask and convert to normalized coordinates
|
| 692 |
+
tracker_box_pixels = (
|
| 693 |
+
mask_to_box(mask_binary.unsqueeze(0).unsqueeze(0))
|
| 694 |
+
.squeeze(0)
|
| 695 |
+
.squeeze(0)
|
| 696 |
+
)
|
| 697 |
+
mask_height, mask_width = tracker_mask.shape[-2:]
|
| 698 |
+
tracker_box_normalized = torch.tensor(
|
| 699 |
+
[
|
| 700 |
+
tracker_box_pixels[0] / mask_width,
|
| 701 |
+
tracker_box_pixels[1] / mask_height,
|
| 702 |
+
tracker_box_pixels[2] / mask_width,
|
| 703 |
+
tracker_box_pixels[3] / mask_height,
|
| 704 |
+
],
|
| 705 |
+
device=tracker_box_pixels.device,
|
| 706 |
+
)
|
| 707 |
+
|
| 708 |
+
# Compute IoU between detection and SAM2 tracklet bounding boxes
|
| 709 |
+
det_box_batch = det_box.unsqueeze(0)
|
| 710 |
+
tracker_box_batch = tracker_box_normalized.unsqueeze(0)
|
| 711 |
+
iou = fast_diag_box_iou(det_box_batch, tracker_box_batch)[0]
|
| 712 |
+
|
| 713 |
+
if (
|
| 714 |
+
iou < self.reconstruction_bbox_iou_thresh
|
| 715 |
+
and det_score >= self.reconstruction_bbox_det_score
|
| 716 |
+
):
|
| 717 |
+
should_recondition_iou = True
|
| 718 |
+
reconditioned_obj_ids.add(trk_obj_id)
|
| 719 |
+
|
| 720 |
+
should_recondition_periodic = (
|
| 721 |
+
self.recondition_every_nth_frame > 0
|
| 722 |
+
and frame_idx % self.recondition_every_nth_frame == 0
|
| 723 |
+
and len(trk_id_to_max_iou_high_conf_det) > 0
|
| 724 |
+
)
|
| 725 |
+
|
| 726 |
+
# Recondition if periodic or IoU condition met
|
| 727 |
+
if should_recondition_periodic or should_recondition_iou:
|
| 728 |
+
self._recondition_masklets(
|
| 729 |
+
frame_idx,
|
| 730 |
+
det_out,
|
| 731 |
+
trk_id_to_max_iou_high_conf_det,
|
| 732 |
+
tracker_states_local,
|
| 733 |
+
tracker_metadata_prev,
|
| 734 |
+
tracker_obj_scores_global,
|
| 735 |
+
)
|
| 736 |
+
|
| 737 |
+
# Step 4: Run SAM2 memory encoder on the current frame's prediction masks
|
| 738 |
+
# This is done on all GPUs
|
| 739 |
+
batch_size = tracker_low_res_masks_global.size(0)
|
| 740 |
+
if batch_size > 0:
|
| 741 |
+
if not hasattr(self, "_warm_up_complete") or self._warm_up_complete:
|
| 742 |
+
if self.suppress_overlapping_based_on_recent_occlusion_threshold > 0.0:
|
| 743 |
+
# NOTE: tracker_low_res_masks_global is updated in-place then returned
|
| 744 |
+
tracker_low_res_masks_global = (
|
| 745 |
+
self._suppress_overlapping_based_on_recent_occlusion(
|
| 746 |
+
frame_idx,
|
| 747 |
+
tracker_low_res_masks_global,
|
| 748 |
+
tracker_metadata_prev,
|
| 749 |
+
tracker_metadata_new,
|
| 750 |
+
obj_ids_newly_removed,
|
| 751 |
+
reverse,
|
| 752 |
+
)
|
| 753 |
+
)
|
| 754 |
+
|
| 755 |
+
self._tracker_update_memories(
|
| 756 |
+
tracker_states_local,
|
| 757 |
+
frame_idx,
|
| 758 |
+
tracker_metadata=tracker_metadata_prev,
|
| 759 |
+
low_res_masks=tracker_low_res_masks_global,
|
| 760 |
+
)
|
| 761 |
+
|
| 762 |
+
# Step 4: update the SAM2 metadata based on the update plan
|
| 763 |
+
# note: except for "rank0_metadata" (that is only available on GPU 0),
|
| 764 |
+
# the updated `tracker_metadata_new` should be identical on all GPUs
|
| 765 |
+
for rank in range(self.world_size):
|
| 766 |
+
new_det_obj_ids_this_gpu = new_det_obj_ids[new_det_gpu_ids == rank]
|
| 767 |
+
updated_obj_ids_this_gpu = tracker_metadata_new["obj_ids_per_gpu"][rank]
|
| 768 |
+
if len(new_det_obj_ids_this_gpu) > 0:
|
| 769 |
+
updated_obj_ids_this_gpu = np.concatenate(
|
| 770 |
+
[updated_obj_ids_this_gpu, new_det_obj_ids_this_gpu]
|
| 771 |
+
)
|
| 772 |
+
if len(obj_ids_newly_removed) > 0:
|
| 773 |
+
is_removed = np.isin(
|
| 774 |
+
updated_obj_ids_this_gpu, list(obj_ids_newly_removed)
|
| 775 |
+
)
|
| 776 |
+
updated_obj_ids_this_gpu = updated_obj_ids_this_gpu[~is_removed]
|
| 777 |
+
tracker_metadata_new["obj_ids_per_gpu"][rank] = updated_obj_ids_this_gpu
|
| 778 |
+
tracker_metadata_new["num_obj_per_gpu"][rank] = len(
|
| 779 |
+
updated_obj_ids_this_gpu
|
| 780 |
+
)
|
| 781 |
+
tracker_metadata_new["obj_ids_all_gpu"] = np.concatenate(
|
| 782 |
+
tracker_metadata_new["obj_ids_per_gpu"]
|
| 783 |
+
)
|
| 784 |
+
# update object scores and the maximum object ID assigned so far
|
| 785 |
+
if len(new_det_obj_ids) > 0:
|
| 786 |
+
tracker_metadata_new["obj_id_to_score"].update(
|
| 787 |
+
zip(new_det_obj_ids, det_scores_np[new_det_fa_inds])
|
| 788 |
+
)
|
| 789 |
+
# tracker scores are not available for new objects, use det score instead.
|
| 790 |
+
tracker_metadata_new["obj_id_to_tracker_score_frame_wise"][
|
| 791 |
+
frame_idx
|
| 792 |
+
].update(zip(new_det_obj_ids, det_scores_np[new_det_fa_inds]))
|
| 793 |
+
tracker_metadata_new["max_obj_id"] = max(
|
| 794 |
+
tracker_metadata_new["max_obj_id"],
|
| 795 |
+
np.max(new_det_obj_ids),
|
| 796 |
+
)
|
| 797 |
+
# for removed objects, we set their scores to a very low value (-1e4) but still
|
| 798 |
+
# keep them in "obj_id_to_score" (it's easier to handle outputs this way)
|
| 799 |
+
for obj_id in obj_ids_newly_removed:
|
| 800 |
+
tracker_metadata_new["obj_id_to_score"][obj_id] = -1e4
|
| 801 |
+
tracker_metadata_new["obj_id_to_tracker_score_frame_wise"][frame_idx][
|
| 802 |
+
obj_id
|
| 803 |
+
] = -1e4
|
| 804 |
+
tracker_metadata_new["obj_id_to_last_occluded"].pop(obj_id, None)
|
| 805 |
+
# check that "rank0_metadata" is in tracker_metadata_new if and only if it's GPU 0
|
| 806 |
+
assert ("rank0_metadata" in tracker_metadata_new) == (self.rank == 0)
|
| 807 |
+
if self.rank == 0 and self.masklet_confirmation_enable:
|
| 808 |
+
rank0_metadata = self.update_masklet_confirmation_status(
|
| 809 |
+
rank0_metadata=tracker_metadata_new["rank0_metadata"],
|
| 810 |
+
obj_ids_all_gpu_prev=tracker_metadata_prev["obj_ids_all_gpu"],
|
| 811 |
+
obj_ids_all_gpu_updated=tracker_metadata_new["obj_ids_all_gpu"],
|
| 812 |
+
det_to_matched_trk_obj_ids=det_to_matched_trk_obj_ids,
|
| 813 |
+
new_det_obj_ids=new_det_obj_ids,
|
| 814 |
+
)
|
| 815 |
+
tracker_metadata_new["rank0_metadata"] = rank0_metadata
|
| 816 |
+
|
| 817 |
+
return tracker_update_plan, tracker_metadata_new
|
| 818 |
+
|
| 819 |
+
def _suppress_overlapping_based_on_recent_occlusion(
|
| 820 |
+
self,
|
| 821 |
+
frame_idx: int,
|
| 822 |
+
tracker_low_res_masks_global: Tensor,
|
| 823 |
+
tracker_metadata_prev: Dict[str, Any],
|
| 824 |
+
tracker_metadata_new: Dict[str, Any],
|
| 825 |
+
obj_ids_newly_removed: Set[int],
|
| 826 |
+
reverse: bool = False,
|
| 827 |
+
):
|
| 828 |
+
"""
|
| 829 |
+
Suppress overlapping masks based on the most recent occlusion information. If an object is removed by hotstart, we always suppress it if it overlaps with any other object.
|
| 830 |
+
Args:
|
| 831 |
+
frame_idx (int): The current frame index.
|
| 832 |
+
tracker_low_res_masks_global (Tensor): The low-resolution masks for the current frame.
|
| 833 |
+
tracker_metadata_prev (Dict[str, Any]): The metadata from the previous frame.
|
| 834 |
+
tracker_metadata_new (Dict[str, Any]): The metadata for the current frame.
|
| 835 |
+
obj_ids_newly_removed (Set[int]): The object IDs that have been removed.
|
| 836 |
+
Return:
|
| 837 |
+
Tensor: The updated low-resolution masks with some objects suppressed.
|
| 838 |
+
"""
|
| 839 |
+
obj_ids_global = tracker_metadata_prev["obj_ids_all_gpu"]
|
| 840 |
+
binary_tracker_low_res_masks_global = tracker_low_res_masks_global > 0
|
| 841 |
+
batch_size = tracker_low_res_masks_global.size(0)
|
| 842 |
+
if batch_size > 0:
|
| 843 |
+
assert (
|
| 844 |
+
len(obj_ids_global) == batch_size
|
| 845 |
+
), f"Mismatch in number of objects: {len(obj_ids_global)} vs {batch_size}"
|
| 846 |
+
NEVER_OCCLUDED = -1
|
| 847 |
+
ALWAYS_OCCLUDED = 100000 # This value should be larger than any possible frame index, indicates that the object was removed by hotstart logic
|
| 848 |
+
last_occluded_prev = torch.cat(
|
| 849 |
+
[
|
| 850 |
+
tracker_metadata_prev["obj_id_to_last_occluded"].get(
|
| 851 |
+
obj_id,
|
| 852 |
+
torch.full(
|
| 853 |
+
(1,),
|
| 854 |
+
fill_value=(
|
| 855 |
+
NEVER_OCCLUDED
|
| 856 |
+
if obj_id not in obj_ids_newly_removed
|
| 857 |
+
else ALWAYS_OCCLUDED
|
| 858 |
+
),
|
| 859 |
+
device=binary_tracker_low_res_masks_global.device,
|
| 860 |
+
dtype=torch.long,
|
| 861 |
+
),
|
| 862 |
+
)
|
| 863 |
+
for obj_id in obj_ids_global
|
| 864 |
+
],
|
| 865 |
+
dim=0,
|
| 866 |
+
)
|
| 867 |
+
to_suppress = self._get_objects_to_suppress_based_on_most_recently_occluded(
|
| 868 |
+
binary_tracker_low_res_masks_global,
|
| 869 |
+
last_occluded_prev,
|
| 870 |
+
obj_ids_global,
|
| 871 |
+
frame_idx,
|
| 872 |
+
reverse,
|
| 873 |
+
)
|
| 874 |
+
|
| 875 |
+
# Update metadata with occlusion information
|
| 876 |
+
is_obj_occluded = ~(binary_tracker_low_res_masks_global.any(dim=(-1, -2)))
|
| 877 |
+
is_obj_occluded_or_suppressed = is_obj_occluded | to_suppress
|
| 878 |
+
last_occluded_new = last_occluded_prev.clone()
|
| 879 |
+
last_occluded_new[is_obj_occluded_or_suppressed] = frame_idx
|
| 880 |
+
# Slice out the last occluded frame for each object
|
| 881 |
+
tracker_metadata_new["obj_id_to_last_occluded"] = {
|
| 882 |
+
obj_id: last_occluded_new[obj_idx : obj_idx + 1]
|
| 883 |
+
for obj_idx, obj_id in enumerate(obj_ids_global)
|
| 884 |
+
}
|
| 885 |
+
|
| 886 |
+
# Zero out suppressed masks before memory encoding
|
| 887 |
+
NO_OBJ_LOGIT = -10
|
| 888 |
+
tracker_low_res_masks_global[to_suppress] = NO_OBJ_LOGIT
|
| 889 |
+
|
| 890 |
+
return tracker_low_res_masks_global
|
| 891 |
+
|
| 892 |
+
def run_tracker_update_execution_phase(
|
| 893 |
+
self,
|
| 894 |
+
frame_idx: int,
|
| 895 |
+
num_frames: int,
|
| 896 |
+
reverse: bool,
|
| 897 |
+
det_out: Dict[str, Tensor],
|
| 898 |
+
tracker_states_local: List[Any],
|
| 899 |
+
tracker_update_plan: Dict[str, npt.NDArray],
|
| 900 |
+
orig_vid_height: int,
|
| 901 |
+
orig_vid_width: int,
|
| 902 |
+
feature_cache: Dict,
|
| 903 |
+
):
|
| 904 |
+
# initialize tracking scores with detection scores
|
| 905 |
+
new_det_fa_inds: npt.NDArray = tracker_update_plan["new_det_fa_inds"]
|
| 906 |
+
new_det_obj_ids: npt.NDArray = tracker_update_plan["new_det_obj_ids"]
|
| 907 |
+
new_det_gpu_ids: npt.NDArray = tracker_update_plan["new_det_gpu_ids"]
|
| 908 |
+
is_on_this_gpu: npt.NDArray = new_det_gpu_ids == self.rank
|
| 909 |
+
new_det_obj_ids_local: npt.NDArray = new_det_obj_ids[is_on_this_gpu]
|
| 910 |
+
new_det_fa_inds_local: npt.NDArray = new_det_fa_inds[is_on_this_gpu]
|
| 911 |
+
obj_ids_newly_removed: Set[int] = tracker_update_plan["obj_ids_newly_removed"]
|
| 912 |
+
|
| 913 |
+
# Step 1: add new objects from the detector to SAM2 inference states
|
| 914 |
+
if len(new_det_fa_inds_local) > 0:
|
| 915 |
+
new_det_fa_inds_local_t = torch.from_numpy(new_det_fa_inds_local)
|
| 916 |
+
new_det_masks: Tensor = det_out["mask"][new_det_fa_inds_local_t]
|
| 917 |
+
# initialize SAM2 with new object masks
|
| 918 |
+
tracker_states_local = self._tracker_add_new_objects(
|
| 919 |
+
frame_idx=frame_idx,
|
| 920 |
+
num_frames=num_frames,
|
| 921 |
+
new_obj_ids=new_det_obj_ids_local,
|
| 922 |
+
new_obj_masks=new_det_masks,
|
| 923 |
+
tracker_states_local=tracker_states_local,
|
| 924 |
+
orig_vid_height=orig_vid_height,
|
| 925 |
+
orig_vid_width=orig_vid_width,
|
| 926 |
+
feature_cache=feature_cache,
|
| 927 |
+
)
|
| 928 |
+
|
| 929 |
+
# Step 2: remove from SAM2 inference states those objects removed by heuristics
|
| 930 |
+
if len(obj_ids_newly_removed) > 0:
|
| 931 |
+
self._tracker_remove_objects(tracker_states_local, obj_ids_newly_removed)
|
| 932 |
+
|
| 933 |
+
return tracker_states_local
|
| 934 |
+
|
| 935 |
+
def build_outputs(
|
| 936 |
+
self,
|
| 937 |
+
frame_idx: int,
|
| 938 |
+
num_frames: int,
|
| 939 |
+
reverse: bool,
|
| 940 |
+
det_out: Dict[str, Tensor],
|
| 941 |
+
tracker_low_res_masks_global: Tensor,
|
| 942 |
+
tracker_obj_scores_global: Tensor,
|
| 943 |
+
tracker_metadata_prev: Dict[str, npt.NDArray],
|
| 944 |
+
tracker_update_plan: Dict[str, npt.NDArray],
|
| 945 |
+
orig_vid_height: int,
|
| 946 |
+
orig_vid_width: int,
|
| 947 |
+
reconditioned_obj_ids: set = None,
|
| 948 |
+
det_to_matched_trk_obj_ids: dict = None,
|
| 949 |
+
):
|
| 950 |
+
new_det_fa_inds: npt.NDArray = tracker_update_plan["new_det_fa_inds"]
|
| 951 |
+
new_det_obj_ids: npt.NDArray = tracker_update_plan["new_det_obj_ids"]
|
| 952 |
+
obj_id_to_mask = {} # obj_id --> output mask tensor
|
| 953 |
+
|
| 954 |
+
# Part 1: masks from previous SAM2 propagation
|
| 955 |
+
existing_masklet_obj_ids = tracker_metadata_prev["obj_ids_all_gpu"]
|
| 956 |
+
existing_masklet_video_res_masks = F.interpolate(
|
| 957 |
+
tracker_low_res_masks_global.unsqueeze(1),
|
| 958 |
+
size=(orig_vid_height, orig_vid_width),
|
| 959 |
+
mode="bilinear",
|
| 960 |
+
align_corners=False,
|
| 961 |
+
) # (num_obj, 1, H_video, W_video)
|
| 962 |
+
existing_masklet_binary = existing_masklet_video_res_masks > 0
|
| 963 |
+
assert len(existing_masklet_obj_ids) == len(existing_masklet_binary)
|
| 964 |
+
for obj_id, mask in zip(existing_masklet_obj_ids, existing_masklet_binary):
|
| 965 |
+
obj_id_to_mask[obj_id] = mask # (1, H_video, W_video)
|
| 966 |
+
|
| 967 |
+
# Part 2: masks from new detections
|
| 968 |
+
new_det_fa_inds_t = torch.from_numpy(new_det_fa_inds)
|
| 969 |
+
new_det_low_res_masks = det_out["mask"][new_det_fa_inds_t].unsqueeze(1)
|
| 970 |
+
new_det_low_res_masks = fill_holes_in_mask_scores(
|
| 971 |
+
new_det_low_res_masks,
|
| 972 |
+
max_area=self.fill_hole_area,
|
| 973 |
+
fill_holes=True,
|
| 974 |
+
remove_sprinkles=True,
|
| 975 |
+
)
|
| 976 |
+
new_masklet_video_res_masks = F.interpolate(
|
| 977 |
+
new_det_low_res_masks,
|
| 978 |
+
size=(orig_vid_height, orig_vid_width),
|
| 979 |
+
mode="bilinear",
|
| 980 |
+
align_corners=False,
|
| 981 |
+
) # (num_obj, 1, H_video, W_video)
|
| 982 |
+
|
| 983 |
+
new_masklet_binary = new_masklet_video_res_masks > 0
|
| 984 |
+
assert len(new_det_obj_ids) == len(new_masklet_video_res_masks)
|
| 985 |
+
for obj_id, mask in zip(new_det_obj_ids, new_masklet_binary):
|
| 986 |
+
obj_id_to_mask[obj_id] = mask # (1, H_video, W_video)
|
| 987 |
+
|
| 988 |
+
# Part 3: Override masks for reconditioned objects using detection masks
|
| 989 |
+
if reconditioned_obj_ids is not None and len(reconditioned_obj_ids) > 0:
|
| 990 |
+
trk_id_to_max_iou_high_conf_det = tracker_update_plan.get(
|
| 991 |
+
"trk_id_to_max_iou_high_conf_det", {}
|
| 992 |
+
)
|
| 993 |
+
|
| 994 |
+
for obj_id in reconditioned_obj_ids:
|
| 995 |
+
det_idx = trk_id_to_max_iou_high_conf_det.get(obj_id)
|
| 996 |
+
|
| 997 |
+
if det_idx is not None:
|
| 998 |
+
det_mask = det_out["mask"][det_idx]
|
| 999 |
+
det_mask = det_mask.unsqueeze(0).unsqueeze(0)
|
| 1000 |
+
det_mask_resized = (
|
| 1001 |
+
F.interpolate(
|
| 1002 |
+
det_mask.float(),
|
| 1003 |
+
size=(orig_vid_height, orig_vid_width),
|
| 1004 |
+
mode="bilinear",
|
| 1005 |
+
align_corners=False,
|
| 1006 |
+
)
|
| 1007 |
+
> 0
|
| 1008 |
+
)
|
| 1009 |
+
|
| 1010 |
+
det_mask_final = det_mask_resized.squeeze(0)
|
| 1011 |
+
obj_id_to_mask[obj_id] = det_mask_final
|
| 1012 |
+
|
| 1013 |
+
return obj_id_to_mask
|
| 1014 |
+
|
| 1015 |
+
def _get_objects_to_suppress_based_on_most_recently_occluded(
|
| 1016 |
+
self,
|
| 1017 |
+
binary_low_res_masks: Tensor,
|
| 1018 |
+
last_occluded: List[int],
|
| 1019 |
+
obj_ids: List[int],
|
| 1020 |
+
frame_idx: int = None,
|
| 1021 |
+
reverse: bool = False,
|
| 1022 |
+
):
|
| 1023 |
+
# Suppress overlapping masks for objects that were most recently occluded
|
| 1024 |
+
assert (
|
| 1025 |
+
binary_low_res_masks.dtype == torch.bool
|
| 1026 |
+
), f"Expected boolean tensor, got {binary_low_res_masks.dtype}"
|
| 1027 |
+
to_suppress = torch.zeros(
|
| 1028 |
+
binary_low_res_masks.size(0),
|
| 1029 |
+
device=binary_low_res_masks.device,
|
| 1030 |
+
dtype=torch.bool,
|
| 1031 |
+
)
|
| 1032 |
+
if len(obj_ids) <= 1:
|
| 1033 |
+
return to_suppress
|
| 1034 |
+
|
| 1035 |
+
iou = mask_iou(binary_low_res_masks, binary_low_res_masks) # [N,N]
|
| 1036 |
+
|
| 1037 |
+
# Create masks for upper triangular matrix (i < j) and IoU threshold
|
| 1038 |
+
mask_iou_thresh = (
|
| 1039 |
+
iou >= self.suppress_overlapping_based_on_recent_occlusion_threshold
|
| 1040 |
+
)
|
| 1041 |
+
overlapping_pairs = torch.triu(mask_iou_thresh, diagonal=1) # [N,N]
|
| 1042 |
+
|
| 1043 |
+
last_occ_expanded_i = last_occluded.unsqueeze(1) # (N, 1)
|
| 1044 |
+
last_occ_expanded_j = last_occluded.unsqueeze(0) # (1, N)
|
| 1045 |
+
# Suppress most recently occluded
|
| 1046 |
+
cmp_op = torch.gt if not reverse else torch.lt
|
| 1047 |
+
suppress_i_mask = (
|
| 1048 |
+
overlapping_pairs
|
| 1049 |
+
& cmp_op(
|
| 1050 |
+
last_occ_expanded_i, last_occ_expanded_j
|
| 1051 |
+
) # (last_occ_expanded_i > last_occ_expanded_j)
|
| 1052 |
+
& (
|
| 1053 |
+
last_occ_expanded_j > -1
|
| 1054 |
+
) # j can suppress i only if i was previously occluded
|
| 1055 |
+
)
|
| 1056 |
+
suppress_j_mask = (
|
| 1057 |
+
overlapping_pairs
|
| 1058 |
+
& cmp_op(last_occ_expanded_j, last_occ_expanded_i)
|
| 1059 |
+
& (
|
| 1060 |
+
last_occ_expanded_i > -1
|
| 1061 |
+
) # i can suppress j only if j was previously occluded
|
| 1062 |
+
)
|
| 1063 |
+
# Apply suppression
|
| 1064 |
+
to_suppress = suppress_i_mask.any(dim=1) | suppress_j_mask.any(dim=0)
|
| 1065 |
+
|
| 1066 |
+
# Log for debugging
|
| 1067 |
+
if (
|
| 1068 |
+
self.rank == 0
|
| 1069 |
+
and logger.isEnabledFor(logging.DEBUG)
|
| 1070 |
+
and frame_idx is not None
|
| 1071 |
+
):
|
| 1072 |
+
suppress_i_mask = suppress_i_mask.cpu().numpy()
|
| 1073 |
+
suppress_j_mask = suppress_j_mask.cpu().numpy()
|
| 1074 |
+
last_occluded = last_occluded.cpu().numpy()
|
| 1075 |
+
|
| 1076 |
+
# Find all suppression pairs without using torch.where
|
| 1077 |
+
batch_size = suppress_i_mask.shape[0]
|
| 1078 |
+
|
| 1079 |
+
# Log i-suppression cases (where i gets suppressed in favor of j)
|
| 1080 |
+
for i in range(batch_size):
|
| 1081 |
+
for j in range(batch_size):
|
| 1082 |
+
if suppress_i_mask[i, j]:
|
| 1083 |
+
logger.debug(
|
| 1084 |
+
f"{frame_idx=}: Suppressing obj {obj_ids[i]} last occluded {last_occluded[i]} in favor of {obj_ids[j]} last occluded {last_occluded[j]}"
|
| 1085 |
+
)
|
| 1086 |
+
|
| 1087 |
+
# Log j-suppression cases (where j gets suppressed in favor of i)
|
| 1088 |
+
for i in range(batch_size):
|
| 1089 |
+
for j in range(batch_size):
|
| 1090 |
+
if suppress_j_mask[i, j]:
|
| 1091 |
+
logger.debug(
|
| 1092 |
+
f"{frame_idx=}: Suppressing obj {obj_ids[j]} last occluded {last_occluded[j]} in favor of {obj_ids[i]} last occluded {last_occluded[i]}"
|
| 1093 |
+
)
|
| 1094 |
+
|
| 1095 |
+
return to_suppress
|
| 1096 |
+
|
| 1097 |
+
def _propogate_tracker_one_frame_local_gpu(
|
| 1098 |
+
self,
|
| 1099 |
+
inference_states: List[Any],
|
| 1100 |
+
frame_idx: int,
|
| 1101 |
+
reverse: bool,
|
| 1102 |
+
# by default, we disable memory encoding until we gather all outputs
|
| 1103 |
+
run_mem_encoder: bool = False,
|
| 1104 |
+
):
|
| 1105 |
+
"""
|
| 1106 |
+
inference_states: List of inference states, each state corresponds to a different set of objects.
|
| 1107 |
+
"""
|
| 1108 |
+
obj_ids_local = []
|
| 1109 |
+
low_res_masks_list = []
|
| 1110 |
+
obj_scores_list = []
|
| 1111 |
+
for inference_state in inference_states:
|
| 1112 |
+
if len(inference_state["obj_ids"]) == 0:
|
| 1113 |
+
continue # skip propagation on empty inference states
|
| 1114 |
+
|
| 1115 |
+
# propagate one frame
|
| 1116 |
+
num_frames_propagated = 0
|
| 1117 |
+
for out in self.tracker.propagate_in_video(
|
| 1118 |
+
inference_state,
|
| 1119 |
+
start_frame_idx=frame_idx,
|
| 1120 |
+
# end_frame_idx = start_frame_idx + max_frame_num_to_track
|
| 1121 |
+
# (i.e. propagating 1 frame since end_frame_idx is inclusive)
|
| 1122 |
+
max_frame_num_to_track=0,
|
| 1123 |
+
reverse=reverse,
|
| 1124 |
+
tqdm_disable=True,
|
| 1125 |
+
run_mem_encoder=run_mem_encoder,
|
| 1126 |
+
):
|
| 1127 |
+
out_frame_idx, out_obj_ids, out_low_res_masks, _, out_obj_scores = out
|
| 1128 |
+
num_frames_propagated += 1
|
| 1129 |
+
|
| 1130 |
+
# only 1 frames should be propagated
|
| 1131 |
+
assert (
|
| 1132 |
+
num_frames_propagated == 1 and out_frame_idx == frame_idx
|
| 1133 |
+
), f"num_frames_propagated: {num_frames_propagated}, out_frame_idx: {out_frame_idx}, frame_idx: {frame_idx}"
|
| 1134 |
+
assert isinstance(out_obj_ids, list)
|
| 1135 |
+
obj_ids_local.extend(out_obj_ids)
|
| 1136 |
+
low_res_masks_list.append(out_low_res_masks.squeeze(1))
|
| 1137 |
+
obj_scores_list.append(out_obj_scores.squeeze(1))
|
| 1138 |
+
|
| 1139 |
+
# concatenate the output masklets from all local inference states
|
| 1140 |
+
H_mask = W_mask = self.tracker.low_res_mask_size
|
| 1141 |
+
if len(low_res_masks_list) > 0:
|
| 1142 |
+
low_res_masks_local = torch.cat(low_res_masks_list, dim=0)
|
| 1143 |
+
obj_scores_local = torch.cat(obj_scores_list, dim=0)
|
| 1144 |
+
assert low_res_masks_local.shape[1:] == (H_mask, W_mask)
|
| 1145 |
+
|
| 1146 |
+
# Apply hole filling to the masks
|
| 1147 |
+
low_res_masks_local = fill_holes_in_mask_scores(
|
| 1148 |
+
low_res_masks_local.unsqueeze(1),
|
| 1149 |
+
max_area=self.fill_hole_area,
|
| 1150 |
+
fill_holes=True,
|
| 1151 |
+
remove_sprinkles=True,
|
| 1152 |
+
)
|
| 1153 |
+
low_res_masks_local = low_res_masks_local.squeeze(1)
|
| 1154 |
+
else:
|
| 1155 |
+
low_res_masks_local = torch.zeros(0, H_mask, W_mask, device=self.device)
|
| 1156 |
+
obj_scores_local = torch.zeros(0, device=self.device)
|
| 1157 |
+
|
| 1158 |
+
return obj_ids_local, low_res_masks_local, obj_scores_local
|
| 1159 |
+
|
| 1160 |
+
def _associate_det_trk(
|
| 1161 |
+
self,
|
| 1162 |
+
det_masks: Tensor,
|
| 1163 |
+
det_scores_np: npt.NDArray,
|
| 1164 |
+
trk_masks: Tensor,
|
| 1165 |
+
trk_obj_ids: npt.NDArray,
|
| 1166 |
+
):
|
| 1167 |
+
"""
|
| 1168 |
+
Match detections on the current frame with the existing masklets.
|
| 1169 |
+
|
| 1170 |
+
Args:
|
| 1171 |
+
- det_masks: (N, H, W) tensor of predicted masks
|
| 1172 |
+
- det_scores_np: (N,) array of detection scores
|
| 1173 |
+
- trk_masks: (M, H, W) tensor of track masks
|
| 1174 |
+
- trk_obj_ids: (M,) array of object IDs corresponding to trk_masks
|
| 1175 |
+
|
| 1176 |
+
Returns:
|
| 1177 |
+
- new_det_fa_inds: array of new object indices.
|
| 1178 |
+
- unmatched_trk_obj_ids: array of existing masklet object IDs that are not matched
|
| 1179 |
+
to any detections on this frame (for unmatched, we only count masklets with >0 area)
|
| 1180 |
+
- det_to_matched_trk_obj_ids: dict[int, npt.NDArray]: mapping from detector's detection indices
|
| 1181 |
+
to the list of matched tracklet object IDs
|
| 1182 |
+
- empty_trk_obj_ids: array of existing masklet object IDs with zero area in SAM2 prediction
|
| 1183 |
+
"""
|
| 1184 |
+
iou_threshold = self.assoc_iou_thresh
|
| 1185 |
+
iou_threshold_trk = self.trk_assoc_iou_thresh
|
| 1186 |
+
new_det_thresh = self.new_det_thresh
|
| 1187 |
+
|
| 1188 |
+
assert det_masks.is_floating_point(), "float tensor expected (do not binarize)"
|
| 1189 |
+
assert trk_masks.is_floating_point(), "float tensor expected (do not binarize)"
|
| 1190 |
+
assert (
|
| 1191 |
+
trk_masks.size(0) == len(trk_obj_ids)
|
| 1192 |
+
), f"trk_masks and trk_obj_ids should have the same length, {trk_masks.size(0)} vs {len(trk_obj_ids)}"
|
| 1193 |
+
if trk_masks.size(0) == 0:
|
| 1194 |
+
# all detections are new
|
| 1195 |
+
new_det_fa_inds = np.arange(det_masks.size(0))
|
| 1196 |
+
unmatched_trk_obj_ids = np.array([], np.int64)
|
| 1197 |
+
empty_trk_obj_ids = np.array([], np.int64)
|
| 1198 |
+
det_to_matched_trk_obj_ids = {}
|
| 1199 |
+
trk_id_to_max_iou_high_conf_det = {}
|
| 1200 |
+
return (
|
| 1201 |
+
new_det_fa_inds,
|
| 1202 |
+
unmatched_trk_obj_ids,
|
| 1203 |
+
det_to_matched_trk_obj_ids,
|
| 1204 |
+
trk_id_to_max_iou_high_conf_det,
|
| 1205 |
+
empty_trk_obj_ids,
|
| 1206 |
+
)
|
| 1207 |
+
elif det_masks.size(0) == 0:
|
| 1208 |
+
# all previous tracklets are unmatched if they have a non-zero area
|
| 1209 |
+
new_det_fa_inds = np.array([], np.int64)
|
| 1210 |
+
trk_is_nonempty = (trk_masks > 0).any(dim=(1, 2)).cpu().numpy()
|
| 1211 |
+
unmatched_trk_obj_ids = trk_obj_ids[trk_is_nonempty]
|
| 1212 |
+
empty_trk_obj_ids = trk_obj_ids[~trk_is_nonempty]
|
| 1213 |
+
det_to_matched_trk_obj_ids = {}
|
| 1214 |
+
trk_id_to_max_iou_high_conf_det = {}
|
| 1215 |
+
return (
|
| 1216 |
+
new_det_fa_inds,
|
| 1217 |
+
unmatched_trk_obj_ids,
|
| 1218 |
+
det_to_matched_trk_obj_ids,
|
| 1219 |
+
trk_id_to_max_iou_high_conf_det,
|
| 1220 |
+
empty_trk_obj_ids,
|
| 1221 |
+
)
|
| 1222 |
+
|
| 1223 |
+
if det_masks.shape[-2:] != trk_masks.shape[-2:]:
|
| 1224 |
+
# resize to the smaller size to save GPU memory
|
| 1225 |
+
if np.prod(det_masks.shape[-2:]) < np.prod(trk_masks.shape[-2:]):
|
| 1226 |
+
trk_masks = F.interpolate(
|
| 1227 |
+
trk_masks.unsqueeze(1),
|
| 1228 |
+
size=det_masks.shape[-2:],
|
| 1229 |
+
mode="bilinear",
|
| 1230 |
+
align_corners=False,
|
| 1231 |
+
).squeeze(1)
|
| 1232 |
+
else:
|
| 1233 |
+
# resize detections to track size
|
| 1234 |
+
det_masks = F.interpolate(
|
| 1235 |
+
det_masks.unsqueeze(1),
|
| 1236 |
+
size=trk_masks.shape[-2:],
|
| 1237 |
+
mode="bilinear",
|
| 1238 |
+
align_corners=False,
|
| 1239 |
+
).squeeze(1)
|
| 1240 |
+
|
| 1241 |
+
det_masks_binary = det_masks > 0
|
| 1242 |
+
trk_masks_binary = trk_masks > 0
|
| 1243 |
+
ious = mask_iou(det_masks_binary, trk_masks_binary) # (N, M)
|
| 1244 |
+
|
| 1245 |
+
ious_np = ious.cpu().numpy()
|
| 1246 |
+
if self.o2o_matching_masklets_enable:
|
| 1247 |
+
from scipy.optimize import linear_sum_assignment
|
| 1248 |
+
|
| 1249 |
+
# Hungarian matching for tracks (one-to-one: each track matches at most one detection)
|
| 1250 |
+
cost_matrix = 1 - ious_np # Hungarian solves for minimum cost
|
| 1251 |
+
row_ind, col_ind = linear_sum_assignment(cost_matrix)
|
| 1252 |
+
trk_is_matched = np.zeros(trk_masks.size(0), dtype=bool)
|
| 1253 |
+
for d, t in zip(row_ind, col_ind):
|
| 1254 |
+
if ious_np[d, t] >= iou_threshold_trk:
|
| 1255 |
+
trk_is_matched[t] = True
|
| 1256 |
+
else:
|
| 1257 |
+
trk_is_matched = (ious_np >= iou_threshold_trk).any(axis=0)
|
| 1258 |
+
# Non-empty tracks not matched by Hungarian assignment above threshold are unmatched
|
| 1259 |
+
trk_is_nonempty = trk_masks_binary.any(dim=(1, 2)).cpu().numpy()
|
| 1260 |
+
trk_is_unmatched = np.logical_and(trk_is_nonempty, ~trk_is_matched)
|
| 1261 |
+
unmatched_trk_obj_ids = trk_obj_ids[trk_is_unmatched]
|
| 1262 |
+
# also record masklets that have zero area in SAM 2 prediction
|
| 1263 |
+
empty_trk_obj_ids = trk_obj_ids[~trk_is_nonempty]
|
| 1264 |
+
|
| 1265 |
+
# For detections: allow many tracks to match to the same detection (many-to-one)
|
| 1266 |
+
# So, a detection is 'new' if it does not match any track above threshold
|
| 1267 |
+
is_new_det = np.logical_and(
|
| 1268 |
+
det_scores_np >= new_det_thresh,
|
| 1269 |
+
np.logical_not(np.any(ious_np >= iou_threshold, axis=1)),
|
| 1270 |
+
)
|
| 1271 |
+
new_det_fa_inds = np.nonzero(is_new_det)[0]
|
| 1272 |
+
|
| 1273 |
+
# for each detection, which tracks it matched to (above threshold)
|
| 1274 |
+
det_to_matched_trk_obj_ids = {}
|
| 1275 |
+
trk_id_to_max_iou_high_conf_det = {} # trk id --> exactly one detection idx
|
| 1276 |
+
HIGH_CONF_THRESH = 0.8
|
| 1277 |
+
HIGH_IOU_THRESH = 0.8
|
| 1278 |
+
det_to_max_iou_trk_idx = np.argmax(ious_np, axis=1)
|
| 1279 |
+
det_is_high_conf = (det_scores_np >= HIGH_CONF_THRESH) & ~is_new_det
|
| 1280 |
+
det_is_high_iou = np.max(ious_np, axis=1) >= HIGH_IOU_THRESH
|
| 1281 |
+
det_is_high_conf_and_iou = set(
|
| 1282 |
+
np.nonzero(det_is_high_conf & det_is_high_iou)[0]
|
| 1283 |
+
)
|
| 1284 |
+
for d in range(det_masks.size(0)):
|
| 1285 |
+
det_to_matched_trk_obj_ids[d] = trk_obj_ids[ious_np[d, :] >= iou_threshold]
|
| 1286 |
+
if d in det_is_high_conf_and_iou:
|
| 1287 |
+
trk_obj_id = trk_obj_ids[det_to_max_iou_trk_idx[d]].item()
|
| 1288 |
+
trk_id_to_max_iou_high_conf_det[trk_obj_id] = d
|
| 1289 |
+
|
| 1290 |
+
return (
|
| 1291 |
+
new_det_fa_inds,
|
| 1292 |
+
unmatched_trk_obj_ids,
|
| 1293 |
+
det_to_matched_trk_obj_ids,
|
| 1294 |
+
trk_id_to_max_iou_high_conf_det,
|
| 1295 |
+
empty_trk_obj_ids,
|
| 1296 |
+
)
|
| 1297 |
+
|
| 1298 |
+
def _assign_new_det_to_gpus(self, new_det_num, prev_workload_per_gpu):
|
| 1299 |
+
"""Distribute the new objects to the GPUs with the least workload."""
|
| 1300 |
+
workload_per_gpu: npt.NDArray = prev_workload_per_gpu.copy()
|
| 1301 |
+
new_det_gpu_ids = np.zeros(new_det_num, np.int64)
|
| 1302 |
+
|
| 1303 |
+
# assign the objects one by one
|
| 1304 |
+
for i in range(len(new_det_gpu_ids)):
|
| 1305 |
+
# find the GPU with the least workload
|
| 1306 |
+
min_gpu = np.argmin(workload_per_gpu)
|
| 1307 |
+
new_det_gpu_ids[i] = min_gpu
|
| 1308 |
+
workload_per_gpu[min_gpu] += 1
|
| 1309 |
+
return new_det_gpu_ids
|
| 1310 |
+
|
| 1311 |
+
def _process_hotstart(
|
| 1312 |
+
self,
|
| 1313 |
+
frame_idx: int,
|
| 1314 |
+
num_frames: int,
|
| 1315 |
+
reverse: bool,
|
| 1316 |
+
det_to_matched_trk_obj_ids: Dict[int, npt.NDArray],
|
| 1317 |
+
new_det_obj_ids: npt.NDArray,
|
| 1318 |
+
empty_trk_obj_ids: npt.NDArray,
|
| 1319 |
+
unmatched_trk_obj_ids: npt.NDArray,
|
| 1320 |
+
rank0_metadata: Dict[str, Any],
|
| 1321 |
+
tracker_metadata: Dict[str, Any],
|
| 1322 |
+
):
|
| 1323 |
+
"""Handle hotstart heuristics to remove unmatched or duplicated objects."""
|
| 1324 |
+
# obj_id --> first frame index where the object was detected
|
| 1325 |
+
obj_first_frame_idx = rank0_metadata["obj_first_frame_idx"]
|
| 1326 |
+
# obj_id --> [mismatched frame indices]
|
| 1327 |
+
unmatched_frame_inds = rank0_metadata["unmatched_frame_inds"]
|
| 1328 |
+
trk_keep_alive = rank0_metadata["trk_keep_alive"]
|
| 1329 |
+
# (first_appear_obj_id, obj_id) --> [overlap frame indices]
|
| 1330 |
+
overlap_pair_to_frame_inds = rank0_metadata["overlap_pair_to_frame_inds"]
|
| 1331 |
+
# removed_obj_ids: object IDs that are suppressed via hot-start
|
| 1332 |
+
removed_obj_ids = rank0_metadata["removed_obj_ids"]
|
| 1333 |
+
suppressed_obj_ids = rank0_metadata["suppressed_obj_ids"][frame_idx]
|
| 1334 |
+
|
| 1335 |
+
obj_ids_newly_removed = set() # object IDs to be newly removed on this frame
|
| 1336 |
+
hotstart_diff = (
|
| 1337 |
+
frame_idx - self.hotstart_delay
|
| 1338 |
+
if not reverse
|
| 1339 |
+
else frame_idx + self.hotstart_delay
|
| 1340 |
+
)
|
| 1341 |
+
|
| 1342 |
+
# Step 1: log the frame index where each object ID first appears
|
| 1343 |
+
for obj_id in new_det_obj_ids:
|
| 1344 |
+
if obj_id not in obj_first_frame_idx:
|
| 1345 |
+
obj_first_frame_idx[obj_id] = frame_idx
|
| 1346 |
+
assert obj_id not in trk_keep_alive
|
| 1347 |
+
trk_keep_alive[obj_id] = self.init_trk_keep_alive
|
| 1348 |
+
|
| 1349 |
+
matched_trks = set()
|
| 1350 |
+
# We use the det-->tracks list to check for matched objects. Otherwise, we need to compute areas to decide whether they're occluded
|
| 1351 |
+
for matched_trks_per_det in det_to_matched_trk_obj_ids.values():
|
| 1352 |
+
matched_trks.update(matched_trks_per_det)
|
| 1353 |
+
for obj_id in matched_trks:
|
| 1354 |
+
# NOTE: To minimize number of configurable params, we use the hotstart_unmatch_thresh to set the max value of trk_keep_alive
|
| 1355 |
+
trk_keep_alive[obj_id] = min(
|
| 1356 |
+
self.max_trk_keep_alive, trk_keep_alive[obj_id] + 1
|
| 1357 |
+
)
|
| 1358 |
+
for obj_id in unmatched_trk_obj_ids:
|
| 1359 |
+
unmatched_frame_inds[obj_id].append(frame_idx)
|
| 1360 |
+
# NOTE: To minimize number of configurable params, we use the hotstart_unmatch_thresh to set the min value of trk_keep_alive
|
| 1361 |
+
# The max keep alive is 2x the min, means the model prefers to keep the prediction rather than suppress it if it was matched long enough.
|
| 1362 |
+
trk_keep_alive[obj_id] = max(
|
| 1363 |
+
self.min_trk_keep_alive, trk_keep_alive[obj_id] - 1
|
| 1364 |
+
)
|
| 1365 |
+
if self.decrease_trk_keep_alive_for_empty_masklets:
|
| 1366 |
+
for obj_id in empty_trk_obj_ids:
|
| 1367 |
+
# NOTE: To minimize number of configurable params, we use the hotstart_unmatch_thresh to set the min value of trk_keep_alive
|
| 1368 |
+
trk_keep_alive[obj_id] = max(
|
| 1369 |
+
self.min_trk_keep_alive, trk_keep_alive[obj_id] - 1
|
| 1370 |
+
)
|
| 1371 |
+
|
| 1372 |
+
# Step 2: removed tracks that has not matched with detections for `hotstart_unmatch_thresh` frames with hotstart period
|
| 1373 |
+
# a) add unmatched frame indices for each existing object ID
|
| 1374 |
+
# note that `unmatched_trk_obj_ids` contains those frames where the SAM2 output mask
|
| 1375 |
+
# doesn't match any detection; it excludes those frames where SAM2 gives an empty mask
|
| 1376 |
+
# b) remove a masklet if it first appears after `hotstart_diff` and is unmatched for more
|
| 1377 |
+
# than `self.hotstart_unmatch_thresh` frames
|
| 1378 |
+
for obj_id, frame_indices in unmatched_frame_inds.items():
|
| 1379 |
+
if obj_id in removed_obj_ids or obj_id in obj_ids_newly_removed:
|
| 1380 |
+
continue # skip if the object is already removed
|
| 1381 |
+
if len(frame_indices) >= self.hotstart_unmatch_thresh:
|
| 1382 |
+
is_within_hotstart = (
|
| 1383 |
+
obj_first_frame_idx[obj_id] > hotstart_diff and not reverse
|
| 1384 |
+
) or (obj_first_frame_idx[obj_id] < hotstart_diff and reverse)
|
| 1385 |
+
if is_within_hotstart:
|
| 1386 |
+
obj_ids_newly_removed.add(obj_id)
|
| 1387 |
+
logger.debug(
|
| 1388 |
+
f"Removing object {obj_id} at frame {frame_idx} "
|
| 1389 |
+
f"since it is unmatched for frames: {frame_indices}"
|
| 1390 |
+
)
|
| 1391 |
+
if (
|
| 1392 |
+
trk_keep_alive[obj_id] <= 0 # Object has not been matched for too long
|
| 1393 |
+
and not self.suppress_unmatched_only_within_hotstart
|
| 1394 |
+
and obj_id not in removed_obj_ids
|
| 1395 |
+
and obj_id not in obj_ids_newly_removed
|
| 1396 |
+
):
|
| 1397 |
+
logger.debug(
|
| 1398 |
+
f"Suppressing object {obj_id} at frame {frame_idx}, due to being unmatched"
|
| 1399 |
+
)
|
| 1400 |
+
suppressed_obj_ids.add(obj_id)
|
| 1401 |
+
|
| 1402 |
+
# Step 3: removed tracks that overlaps with another track for `hotstart_dup_thresh` frames
|
| 1403 |
+
# a) find overlaps tracks -- we consider overlap if they match to the same detection
|
| 1404 |
+
for _, matched_trk_obj_ids in det_to_matched_trk_obj_ids.items():
|
| 1405 |
+
if len(matched_trk_obj_ids) < 2:
|
| 1406 |
+
continue # only count detections that are matched to multiple (>=2) masklets
|
| 1407 |
+
# if there are multiple matched track ids, we need to find the one that appeared first;
|
| 1408 |
+
# these later appearing ids may be removed since they may be considered as duplicates
|
| 1409 |
+
first_appear_obj_id = (
|
| 1410 |
+
min(matched_trk_obj_ids, key=lambda x: obj_first_frame_idx[x])
|
| 1411 |
+
if not reverse
|
| 1412 |
+
else max(matched_trk_obj_ids, key=lambda x: obj_first_frame_idx[x])
|
| 1413 |
+
)
|
| 1414 |
+
for obj_id in matched_trk_obj_ids:
|
| 1415 |
+
if obj_id != first_appear_obj_id:
|
| 1416 |
+
key = (first_appear_obj_id, obj_id)
|
| 1417 |
+
overlap_pair_to_frame_inds[key].append(frame_idx)
|
| 1418 |
+
|
| 1419 |
+
# b) remove a masklet if it first appears after `hotstart_diff` and it overlaps with another
|
| 1420 |
+
# masklet (that appears earlier) for more than `self.hotstart_dup_thresh` frames
|
| 1421 |
+
for (first_obj_id, obj_id), frame_indices in overlap_pair_to_frame_inds.items():
|
| 1422 |
+
if obj_id in removed_obj_ids or obj_id in obj_ids_newly_removed:
|
| 1423 |
+
continue # skip if the object is already removed
|
| 1424 |
+
if (obj_first_frame_idx[obj_id] > hotstart_diff and not reverse) or (
|
| 1425 |
+
obj_first_frame_idx[obj_id] < hotstart_diff and reverse
|
| 1426 |
+
):
|
| 1427 |
+
if len(frame_indices) >= self.hotstart_dup_thresh:
|
| 1428 |
+
obj_ids_newly_removed.add(obj_id)
|
| 1429 |
+
logger.debug(
|
| 1430 |
+
f"Removing object {obj_id} at frame {frame_idx} "
|
| 1431 |
+
f"since it overlaps with another track {first_obj_id} at frames: {frame_indices}"
|
| 1432 |
+
)
|
| 1433 |
+
|
| 1434 |
+
removed_obj_ids.update(obj_ids_newly_removed)
|
| 1435 |
+
return obj_ids_newly_removed, rank0_metadata
|
| 1436 |
+
|
| 1437 |
+
def _tracker_update_memories(
|
| 1438 |
+
self,
|
| 1439 |
+
tracker_inference_states: List[Any],
|
| 1440 |
+
frame_idx: int,
|
| 1441 |
+
tracker_metadata: Dict[str, Any],
|
| 1442 |
+
low_res_masks: Tensor,
|
| 1443 |
+
):
|
| 1444 |
+
"""
|
| 1445 |
+
Run Sam2 memory encoder, enforcing non-overlapping constraints globally.
|
| 1446 |
+
"""
|
| 1447 |
+
if len(tracker_inference_states) == 0:
|
| 1448 |
+
return
|
| 1449 |
+
# Avoid an extra interpolation step by directly interpolating to `interpol_size`
|
| 1450 |
+
high_res_H, high_res_W = (
|
| 1451 |
+
self.tracker.maskmem_backbone.mask_downsampler.interpol_size
|
| 1452 |
+
)
|
| 1453 |
+
# NOTE: inspect this part if we observe OOMs in the demo
|
| 1454 |
+
high_res_masks = F.interpolate(
|
| 1455 |
+
low_res_masks.unsqueeze(1),
|
| 1456 |
+
size=(high_res_H, high_res_W),
|
| 1457 |
+
mode="bilinear",
|
| 1458 |
+
align_corners=False,
|
| 1459 |
+
)
|
| 1460 |
+
# We first apply non-overlapping constraints before memory encoding. This may include some suppression heuristics.
|
| 1461 |
+
if not hasattr(self, "_warm_up_complete") or self._warm_up_complete:
|
| 1462 |
+
high_res_masks = self.tracker._suppress_object_pw_area_shrinkage(
|
| 1463 |
+
high_res_masks
|
| 1464 |
+
)
|
| 1465 |
+
# Instead of gathering the predicted object scores, we use mask areas as a proxy.
|
| 1466 |
+
object_score_logits = torch.where(
|
| 1467 |
+
(high_res_masks > 0).any(dim=(-1, -2)), 10.0, -10.0
|
| 1468 |
+
)
|
| 1469 |
+
|
| 1470 |
+
# Run the memory encoder on local slices for each GPU
|
| 1471 |
+
start_idx_gpu = sum(tracker_metadata["num_obj_per_gpu"][: self.rank])
|
| 1472 |
+
start_idx_state = start_idx_gpu
|
| 1473 |
+
for tracker_state in tracker_inference_states:
|
| 1474 |
+
num_obj_per_state = len(tracker_state["obj_ids"])
|
| 1475 |
+
if num_obj_per_state == 0:
|
| 1476 |
+
continue
|
| 1477 |
+
# Get the local high-res masks and object score logits for this inference state
|
| 1478 |
+
end_idx_state = start_idx_state + num_obj_per_state
|
| 1479 |
+
local_high_res_masks = high_res_masks[start_idx_state:end_idx_state]
|
| 1480 |
+
local_object_score_logits = object_score_logits[
|
| 1481 |
+
start_idx_state:end_idx_state
|
| 1482 |
+
]
|
| 1483 |
+
local_batch_size = local_high_res_masks.size(0)
|
| 1484 |
+
# Run Sam2 memory encoder. Note that we do not re-enforce the non-overlapping constraint as it is turned off by default
|
| 1485 |
+
|
| 1486 |
+
encoded_mem = self.tracker._run_memory_encoder(
|
| 1487 |
+
tracker_state,
|
| 1488 |
+
frame_idx,
|
| 1489 |
+
local_batch_size,
|
| 1490 |
+
local_high_res_masks,
|
| 1491 |
+
local_object_score_logits,
|
| 1492 |
+
is_mask_from_pts=False,
|
| 1493 |
+
)
|
| 1494 |
+
local_maskmem_features, local_maskmem_pos_enc = encoded_mem
|
| 1495 |
+
# Store encoded memories in the local inference state
|
| 1496 |
+
output_dict = tracker_state["output_dict"]
|
| 1497 |
+
for storage_key in ["cond_frame_outputs", "non_cond_frame_outputs"]:
|
| 1498 |
+
if frame_idx not in output_dict[storage_key]:
|
| 1499 |
+
continue
|
| 1500 |
+
output_dict[storage_key][frame_idx]["maskmem_features"] = (
|
| 1501 |
+
local_maskmem_features
|
| 1502 |
+
)
|
| 1503 |
+
output_dict[storage_key][frame_idx]["maskmem_pos_enc"] = [
|
| 1504 |
+
pos for pos in local_maskmem_pos_enc
|
| 1505 |
+
]
|
| 1506 |
+
# for batched inference state, we also need to add per-object
|
| 1507 |
+
# memory slides to support instance interactivity
|
| 1508 |
+
self.tracker._add_output_per_object(
|
| 1509 |
+
inference_state=tracker_state,
|
| 1510 |
+
frame_idx=frame_idx,
|
| 1511 |
+
current_out=output_dict[storage_key][frame_idx],
|
| 1512 |
+
storage_key=storage_key,
|
| 1513 |
+
)
|
| 1514 |
+
start_idx_state += num_obj_per_state
|
| 1515 |
+
|
| 1516 |
+
def _tracker_add_new_objects(
|
| 1517 |
+
self,
|
| 1518 |
+
frame_idx: int,
|
| 1519 |
+
num_frames: int,
|
| 1520 |
+
new_obj_ids: List[int],
|
| 1521 |
+
new_obj_masks: Tensor,
|
| 1522 |
+
tracker_states_local: List[Any],
|
| 1523 |
+
orig_vid_height: int,
|
| 1524 |
+
orig_vid_width: int,
|
| 1525 |
+
feature_cache: Dict,
|
| 1526 |
+
):
|
| 1527 |
+
"""Add a new object to SAM2 inference states."""
|
| 1528 |
+
prev_tracker_state = (
|
| 1529 |
+
tracker_states_local[0] if len(tracker_states_local) > 0 else None
|
| 1530 |
+
)
|
| 1531 |
+
|
| 1532 |
+
# prepare inference_state
|
| 1533 |
+
# batch objects that first appear on the same frame together
|
| 1534 |
+
# Clear inference state. Keep the cached image features if available.
|
| 1535 |
+
new_tracker_state = self.tracker.init_state(
|
| 1536 |
+
cached_features=feature_cache,
|
| 1537 |
+
video_height=orig_vid_height,
|
| 1538 |
+
video_width=orig_vid_width,
|
| 1539 |
+
num_frames=num_frames,
|
| 1540 |
+
)
|
| 1541 |
+
new_tracker_state["backbone_out"] = (
|
| 1542 |
+
prev_tracker_state.get("backbone_out", None)
|
| 1543 |
+
if prev_tracker_state is not None
|
| 1544 |
+
else None
|
| 1545 |
+
)
|
| 1546 |
+
|
| 1547 |
+
assert len(new_obj_ids) == new_obj_masks.size(0)
|
| 1548 |
+
assert new_obj_masks.is_floating_point()
|
| 1549 |
+
input_mask_res = self.tracker.input_mask_size
|
| 1550 |
+
new_obj_masks = F.interpolate(
|
| 1551 |
+
new_obj_masks.unsqueeze(1),
|
| 1552 |
+
size=(input_mask_res, input_mask_res),
|
| 1553 |
+
mode="bilinear",
|
| 1554 |
+
align_corners=False,
|
| 1555 |
+
).squeeze(1)
|
| 1556 |
+
new_obj_masks = new_obj_masks > 0
|
| 1557 |
+
|
| 1558 |
+
# add object one by one
|
| 1559 |
+
for new_obj_id, new_mask in zip(new_obj_ids, new_obj_masks):
|
| 1560 |
+
self.tracker.add_new_mask(
|
| 1561 |
+
inference_state=new_tracker_state,
|
| 1562 |
+
frame_idx=frame_idx,
|
| 1563 |
+
obj_id=new_obj_id,
|
| 1564 |
+
mask=new_mask,
|
| 1565 |
+
add_mask_to_memory=True,
|
| 1566 |
+
)
|
| 1567 |
+
# NOTE: we skip enforcing the non-overlapping constraint **globally** when adding new objects.
|
| 1568 |
+
self.tracker.propagate_in_video_preflight(
|
| 1569 |
+
new_tracker_state, run_mem_encoder=True
|
| 1570 |
+
)
|
| 1571 |
+
tracker_states_local.append(new_tracker_state)
|
| 1572 |
+
return tracker_states_local
|
| 1573 |
+
|
| 1574 |
+
def _tracker_remove_object(self, tracker_states_local: List[Any], obj_id: int):
|
| 1575 |
+
"""
|
| 1576 |
+
Remove an object from SAM2 inference states. This would remove the object from
|
| 1577 |
+
all frames in the video.
|
| 1578 |
+
"""
|
| 1579 |
+
tracker_states_local_before_removal = tracker_states_local.copy()
|
| 1580 |
+
tracker_states_local.clear()
|
| 1581 |
+
for tracker_inference_state in tracker_states_local_before_removal:
|
| 1582 |
+
# we try to remove `obj_id` on every inference state with `strict=False`
|
| 1583 |
+
# it will not do anything if an inference state doesn't contain `obj_id`
|
| 1584 |
+
new_obj_ids, _ = self.tracker.remove_object(
|
| 1585 |
+
tracker_inference_state, obj_id, strict=False, need_output=False
|
| 1586 |
+
)
|
| 1587 |
+
# only keep an inference state if it's non-empty after object removal
|
| 1588 |
+
if len(new_obj_ids) > 0:
|
| 1589 |
+
tracker_states_local.append(tracker_inference_state)
|
| 1590 |
+
|
| 1591 |
+
def _tracker_remove_objects(
|
| 1592 |
+
self, tracker_states_local: List[Any], obj_ids: list[int]
|
| 1593 |
+
):
|
| 1594 |
+
"""
|
| 1595 |
+
Remove an object from SAM2 inference states. This would remove the object from
|
| 1596 |
+
all frames in the video.
|
| 1597 |
+
"""
|
| 1598 |
+
for obj_id in obj_ids:
|
| 1599 |
+
self._tracker_remove_object(tracker_states_local, obj_id)
|
| 1600 |
+
|
| 1601 |
+
def _initialize_metadata(self):
|
| 1602 |
+
"""Initialize metadata for the masklets."""
|
| 1603 |
+
tracker_metadata = {
|
| 1604 |
+
"obj_ids_per_gpu": [np.array([], np.int64) for _ in range(self.world_size)],
|
| 1605 |
+
"obj_ids_all_gpu": np.array([], np.int64),
|
| 1606 |
+
"num_obj_per_gpu": np.zeros(self.world_size, np.int64),
|
| 1607 |
+
"max_obj_id": -1,
|
| 1608 |
+
"obj_id_to_score": {},
|
| 1609 |
+
"obj_id_to_tracker_score_frame_wise": defaultdict(dict),
|
| 1610 |
+
"obj_id_to_last_occluded": {},
|
| 1611 |
+
}
|
| 1612 |
+
if self.rank == 0:
|
| 1613 |
+
# "rank0_metadata" contains metadata that is only stored on (and accessible to) GPU 0
|
| 1614 |
+
# - obj_first_frame_idx: obj_id --> first frame index where the object was detected
|
| 1615 |
+
# - unmatched_frame_inds: obj_id --> [mismatched frame indices]
|
| 1616 |
+
# - overlap_pair_to_frame_inds: (first_appear_obj_id, obj_id) --> [overlap frame indices]
|
| 1617 |
+
# - removed_obj_ids: object IDs that are suppressed via hot-start
|
| 1618 |
+
rank0_metadata = {
|
| 1619 |
+
"obj_first_frame_idx": {},
|
| 1620 |
+
"unmatched_frame_inds": defaultdict(list),
|
| 1621 |
+
"trk_keep_alive": defaultdict(
|
| 1622 |
+
int
|
| 1623 |
+
), # This is used only for object suppression not for removal
|
| 1624 |
+
"overlap_pair_to_frame_inds": defaultdict(list),
|
| 1625 |
+
"removed_obj_ids": set(),
|
| 1626 |
+
"suppressed_obj_ids": defaultdict(
|
| 1627 |
+
set
|
| 1628 |
+
), # frame_idx --> set of objects with suppressed outputs, but still continue to be tracked
|
| 1629 |
+
}
|
| 1630 |
+
if self.masklet_confirmation_enable:
|
| 1631 |
+
# all the following are npt.NDArray with the same shape as `obj_ids_all_gpu`
|
| 1632 |
+
rank0_metadata["masklet_confirmation"] = {
|
| 1633 |
+
# "status" is the confirmation status of each masklet (in `MaskletConfirmationStatus`)
|
| 1634 |
+
"status": np.array([], np.int64),
|
| 1635 |
+
# "consecutive_det_num" is the number of consecutive frames where the masklet is
|
| 1636 |
+
# detected by the detector (with a matched detection)
|
| 1637 |
+
"consecutive_det_num": np.array([], np.int64),
|
| 1638 |
+
}
|
| 1639 |
+
tracker_metadata["rank0_metadata"] = rank0_metadata
|
| 1640 |
+
|
| 1641 |
+
return tracker_metadata
|
| 1642 |
+
|
| 1643 |
+
def update_masklet_confirmation_status(
|
| 1644 |
+
self,
|
| 1645 |
+
rank0_metadata: Dict[str, Any],
|
| 1646 |
+
obj_ids_all_gpu_prev: npt.NDArray,
|
| 1647 |
+
obj_ids_all_gpu_updated: npt.NDArray,
|
| 1648 |
+
det_to_matched_trk_obj_ids: Dict[int, npt.NDArray],
|
| 1649 |
+
new_det_obj_ids: npt.NDArray,
|
| 1650 |
+
):
|
| 1651 |
+
confirmation_data = rank0_metadata["masklet_confirmation"]
|
| 1652 |
+
|
| 1653 |
+
# a) first, expand "confirmation_data" to include new masklets added in this frame
|
| 1654 |
+
status_prev = confirmation_data["status"]
|
| 1655 |
+
consecutive_det_num_prev = confirmation_data["consecutive_det_num"]
|
| 1656 |
+
assert (
|
| 1657 |
+
status_prev.shape == obj_ids_all_gpu_prev.shape
|
| 1658 |
+
), f"Got {status_prev.shape} vs {obj_ids_all_gpu_prev.shape}"
|
| 1659 |
+
|
| 1660 |
+
obj_id_to_updated_idx = {
|
| 1661 |
+
obj_id: idx for idx, obj_id in enumerate(obj_ids_all_gpu_updated)
|
| 1662 |
+
}
|
| 1663 |
+
prev_elem_is_in_updated = np.isin(obj_ids_all_gpu_prev, obj_ids_all_gpu_updated)
|
| 1664 |
+
prev_elem_obj_ids_in_updated = obj_ids_all_gpu_prev[prev_elem_is_in_updated]
|
| 1665 |
+
prev_elem_inds_in_updated = np.array(
|
| 1666 |
+
[obj_id_to_updated_idx[obj_id] for obj_id in prev_elem_obj_ids_in_updated],
|
| 1667 |
+
dtype=np.int64,
|
| 1668 |
+
)
|
| 1669 |
+
# newly added masklets are initialized to "UNCONFIRMED" status
|
| 1670 |
+
unconfirmed_val = MaskletConfirmationStatus.UNCONFIRMED.value
|
| 1671 |
+
status = np.full_like(obj_ids_all_gpu_updated, fill_value=unconfirmed_val)
|
| 1672 |
+
status[prev_elem_inds_in_updated] = status_prev[prev_elem_is_in_updated]
|
| 1673 |
+
consecutive_det_num = np.zeros_like(obj_ids_all_gpu_updated)
|
| 1674 |
+
consecutive_det_num[prev_elem_inds_in_updated] = consecutive_det_num_prev[
|
| 1675 |
+
prev_elem_is_in_updated
|
| 1676 |
+
]
|
| 1677 |
+
|
| 1678 |
+
# b) update the confirmation status of all masklets based on the current frame
|
| 1679 |
+
# b.1) update "consecutive_det_num"
|
| 1680 |
+
# "is_matched": whether a masklet is matched to a detection on this frame
|
| 1681 |
+
is_matched = np.isin(obj_ids_all_gpu_updated, new_det_obj_ids)
|
| 1682 |
+
for matched_trk_obj_ids in det_to_matched_trk_obj_ids.values():
|
| 1683 |
+
is_matched |= np.isin(obj_ids_all_gpu_updated, matched_trk_obj_ids)
|
| 1684 |
+
consecutive_det_num = np.where(is_matched, consecutive_det_num + 1, 0)
|
| 1685 |
+
|
| 1686 |
+
# b.2) update "status"
|
| 1687 |
+
change_to_confirmed = (
|
| 1688 |
+
consecutive_det_num >= self.masklet_confirmation_consecutive_det_thresh
|
| 1689 |
+
)
|
| 1690 |
+
status[change_to_confirmed] = MaskletConfirmationStatus.CONFIRMED.value
|
| 1691 |
+
|
| 1692 |
+
confirmation_data["status"] = status
|
| 1693 |
+
confirmation_data["consecutive_det_num"] = consecutive_det_num
|
| 1694 |
+
return rank0_metadata
|
| 1695 |
+
|
| 1696 |
+
def forward(self, input: BatchedDatapoint, is_inference: bool = False):
|
| 1697 |
+
raise NotImplementedError("Evaluation outside demo is not implemented yet")
|
| 1698 |
+
|
| 1699 |
+
def _load_checkpoint(self, ckpt_path: str, strict: bool = True):
|
| 1700 |
+
sd = torch.load(ckpt_path, map_location="cpu", weights_only=True)["model"]
|
| 1701 |
+
missing_keys, unexpected_keys = self.load_state_dict(sd, strict=strict)
|
| 1702 |
+
if len(missing_keys) > 0 or len(unexpected_keys) > 0:
|
| 1703 |
+
logger.warning(f"Loaded ckpt with {missing_keys=}, {unexpected_keys=}")
|
| 1704 |
+
else:
|
| 1705 |
+
logger.info("Loaded ckpt successfully without missing or unexpected keys")
|
| 1706 |
+
|
| 1707 |
+
def prep_for_evaluator(self, video_frames, tracking_res, scores_labels):
|
| 1708 |
+
"""This method is only used for benchmark eval (not used in the demo)."""
|
| 1709 |
+
num_frames = len(video_frames)
|
| 1710 |
+
w, h = video_frames[0].size
|
| 1711 |
+
zero_mask = torch.zeros((1, h, w), dtype=torch.bool)
|
| 1712 |
+
object_ids = list(scores_labels.keys())
|
| 1713 |
+
preds = {"scores": [], "labels": [], "boxes": [], "masks_rle": []}
|
| 1714 |
+
for oid in object_ids:
|
| 1715 |
+
o_masks = []
|
| 1716 |
+
o_score = scores_labels[oid][0].item()
|
| 1717 |
+
o_label = scores_labels[oid][1]
|
| 1718 |
+
for frame_idx in range(num_frames):
|
| 1719 |
+
if frame_idx not in tracking_res:
|
| 1720 |
+
o_masks.append(zero_mask)
|
| 1721 |
+
else:
|
| 1722 |
+
o_masks.append(tracking_res[frame_idx].get(oid, zero_mask))
|
| 1723 |
+
|
| 1724 |
+
o_masks = torch.cat(o_masks, dim=0) # (n_frames, H, W)
|
| 1725 |
+
preds["scores"].append(o_score)
|
| 1726 |
+
preds["labels"].append(o_label)
|
| 1727 |
+
preds["boxes"].append(mask_to_box(o_masks.unsqueeze(1)).squeeze())
|
| 1728 |
+
preds["masks_rle"].append(rle_encode(o_masks, return_areas=True))
|
| 1729 |
+
|
| 1730 |
+
preds["boxes"] = (
|
| 1731 |
+
torch.stack(preds["boxes"], dim=0)
|
| 1732 |
+
if len(preds["boxes"]) > 0
|
| 1733 |
+
else torch.empty(
|
| 1734 |
+
(0, num_frames, 4), dtype=torch.float32, device=self.device
|
| 1735 |
+
)
|
| 1736 |
+
)
|
| 1737 |
+
preds["scores"] = (
|
| 1738 |
+
torch.tensor(preds["scores"], device=self.device)
|
| 1739 |
+
if len(preds["scores"]) > 0
|
| 1740 |
+
else torch.empty((0,), device=self.device)
|
| 1741 |
+
)
|
| 1742 |
+
preds["per_frame_scores"] = preds["scores"]
|
| 1743 |
+
preds["labels"] = (
|
| 1744 |
+
torch.tensor(preds["labels"], device=self.device)
|
| 1745 |
+
if len(preds["labels"]) > 0
|
| 1746 |
+
else torch.empty((0,), device=self.device)
|
| 1747 |
+
)
|
| 1748 |
+
return preds
|
| 1749 |
+
|
| 1750 |
+
def _encode_prompt(self, **kwargs):
|
| 1751 |
+
return self.detector._encode_prompt(**kwargs)
|
| 1752 |
+
|
| 1753 |
+
def _drop_new_det_with_obj_limit(self, new_det_fa_inds, det_scores_np, num_to_keep):
|
| 1754 |
+
"""
|
| 1755 |
+
Drop a few new detections based on the maximum number of objects. We drop new objects based
|
| 1756 |
+
on their detection scores, keeping the high-scoring ones and dropping the low-scoring ones.
|
| 1757 |
+
"""
|
| 1758 |
+
assert 0 <= num_to_keep <= len(new_det_fa_inds)
|
| 1759 |
+
if num_to_keep == 0:
|
| 1760 |
+
return np.array([], np.int64) # keep none
|
| 1761 |
+
if num_to_keep == len(new_det_fa_inds):
|
| 1762 |
+
return new_det_fa_inds # keep all
|
| 1763 |
+
|
| 1764 |
+
# keep the top-scoring detections
|
| 1765 |
+
score_order = np.argsort(det_scores_np[new_det_fa_inds])[::-1]
|
| 1766 |
+
new_det_fa_inds = new_det_fa_inds[score_order[:num_to_keep]]
|
| 1767 |
+
return new_det_fa_inds
|
之前的代码版本/这一版注意力有问题/HuatuoGPT-Vision/MedSAM3/sam3/model/sam3_video_predictor.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
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
# Copyright (c) Meta Platforms, Inc. and affiliates. All Rights Reserved
|
| 2 |
+
|
| 3 |
+
import datetime
|
| 4 |
+
import gc
|
| 5 |
+
import multiprocessing as mp
|
| 6 |
+
import os
|
| 7 |
+
import queue
|
| 8 |
+
import socket
|
| 9 |
+
import sys
|
| 10 |
+
import time
|
| 11 |
+
import uuid
|
| 12 |
+
from contextlib import closing
|
| 13 |
+
from typing import List, Optional
|
| 14 |
+
|
| 15 |
+
import psutil
|
| 16 |
+
import torch
|
| 17 |
+
|
| 18 |
+
from sam3.logger import get_logger
|
| 19 |
+
|
| 20 |
+
logger = get_logger(__name__)
|
| 21 |
+
|
| 22 |
+
|
| 23 |
+
class Sam3VideoPredictor:
|
| 24 |
+
# a global dictionary that holds all inference states for this model (key is session_id)
|
| 25 |
+
_ALL_INFERENCE_STATES = {}
|
| 26 |
+
|
| 27 |
+
def __init__(
|
| 28 |
+
self,
|
| 29 |
+
checkpoint_path=None,
|
| 30 |
+
bpe_path=None,
|
| 31 |
+
has_presence_token=True,
|
| 32 |
+
geo_encoder_use_img_cross_attn=True,
|
| 33 |
+
strict_state_dict_loading=True,
|
| 34 |
+
async_loading_frames=False,
|
| 35 |
+
video_loader_type="cv2",
|
| 36 |
+
apply_temporal_disambiguation: bool = True,
|
| 37 |
+
):
|
| 38 |
+
self.async_loading_frames = async_loading_frames
|
| 39 |
+
self.video_loader_type = video_loader_type
|
| 40 |
+
from sam3.model_builder import build_sam3_video_model
|
| 41 |
+
|
| 42 |
+
self.model = (
|
| 43 |
+
build_sam3_video_model(
|
| 44 |
+
checkpoint_path=checkpoint_path,
|
| 45 |
+
bpe_path=bpe_path,
|
| 46 |
+
has_presence_token=has_presence_token,
|
| 47 |
+
geo_encoder_use_img_cross_attn=geo_encoder_use_img_cross_attn,
|
| 48 |
+
strict_state_dict_loading=strict_state_dict_loading,
|
| 49 |
+
apply_temporal_disambiguation=apply_temporal_disambiguation,
|
| 50 |
+
)
|
| 51 |
+
.cuda()
|
| 52 |
+
.eval()
|
| 53 |
+
)
|
| 54 |
+
|
| 55 |
+
@torch.inference_mode()
|
| 56 |
+
def handle_request(self, request):
|
| 57 |
+
"""Dispatch a request based on its type."""
|
| 58 |
+
request_type = request["type"]
|
| 59 |
+
if request_type == "start_session":
|
| 60 |
+
return self.start_session(
|
| 61 |
+
resource_path=request["resource_path"],
|
| 62 |
+
session_id=request.get("session_id", None),
|
| 63 |
+
)
|
| 64 |
+
elif request_type == "add_prompt":
|
| 65 |
+
return self.add_prompt(
|
| 66 |
+
session_id=request["session_id"],
|
| 67 |
+
frame_idx=request["frame_index"],
|
| 68 |
+
text=request.get("text", None),
|
| 69 |
+
points=request.get("points", None),
|
| 70 |
+
point_labels=request.get("point_labels", None),
|
| 71 |
+
bounding_boxes=request.get("bounding_boxes", None),
|
| 72 |
+
bounding_box_labels=request.get("bounding_box_labels", None),
|
| 73 |
+
obj_id=request.get("obj_id", None),
|
| 74 |
+
)
|
| 75 |
+
elif request_type == "remove_object":
|
| 76 |
+
return self.remove_object(
|
| 77 |
+
session_id=request["session_id"],
|
| 78 |
+
obj_id=request["obj_id"],
|
| 79 |
+
is_user_action=request.get("is_user_action", True),
|
| 80 |
+
)
|
| 81 |
+
elif request_type == "reset_session":
|
| 82 |
+
return self.reset_session(session_id=request["session_id"])
|
| 83 |
+
elif request_type == "close_session":
|
| 84 |
+
return self.close_session(session_id=request["session_id"])
|
| 85 |
+
else:
|
| 86 |
+
raise RuntimeError(f"invalid request type: {request_type}")
|
| 87 |
+
|
| 88 |
+
@torch.inference_mode()
|
| 89 |
+
def handle_stream_request(self, request):
|
| 90 |
+
"""Dispatch a stream request based on its type."""
|
| 91 |
+
request_type = request["type"]
|
| 92 |
+
if request_type == "propagate_in_video":
|
| 93 |
+
yield from self.propagate_in_video(
|
| 94 |
+
session_id=request["session_id"],
|
| 95 |
+
propagation_direction=request.get("propagation_direction", "both"),
|
| 96 |
+
start_frame_idx=request.get("start_frame_index", None),
|
| 97 |
+
max_frame_num_to_track=request.get("max_frame_num_to_track", None),
|
| 98 |
+
)
|
| 99 |
+
else:
|
| 100 |
+
raise RuntimeError(f"invalid request type: {request_type}")
|
| 101 |
+
|
| 102 |
+
def start_session(self, resource_path, session_id=None):
|
| 103 |
+
"""
|
| 104 |
+
Start a new inference session on an image or a video. Here `resource_path`
|
| 105 |
+
can be either a path to an image file (for image inference) or an MP4 file
|
| 106 |
+
or directory with JPEG video frames (for video inference).
|
| 107 |
+
|
| 108 |
+
If `session_id` is defined, it will be used as identifier for the
|
| 109 |
+
session. If it is not defined, the start_session function will create
|
| 110 |
+
a session id and return it.
|
| 111 |
+
"""
|
| 112 |
+
# get an initial inference_state from the model
|
| 113 |
+
inference_state = self.model.init_state(
|
| 114 |
+
resource_path=resource_path,
|
| 115 |
+
async_loading_frames=self.async_loading_frames,
|
| 116 |
+
video_loader_type=self.video_loader_type,
|
| 117 |
+
)
|
| 118 |
+
if not session_id:
|
| 119 |
+
session_id = str(uuid.uuid4())
|
| 120 |
+
self._ALL_INFERENCE_STATES[session_id] = {
|
| 121 |
+
"state": inference_state,
|
| 122 |
+
"session_id": session_id,
|
| 123 |
+
"start_time": time.time(),
|
| 124 |
+
}
|
| 125 |
+
logger.debug(
|
| 126 |
+
f"started new session {session_id}; {self._get_session_stats()}; "
|
| 127 |
+
f"{self._get_torch_and_gpu_properties()}"
|
| 128 |
+
)
|
| 129 |
+
return {"session_id": session_id}
|
| 130 |
+
|
| 131 |
+
def add_prompt(
|
| 132 |
+
self,
|
| 133 |
+
session_id: str,
|
| 134 |
+
frame_idx: int,
|
| 135 |
+
text: Optional[str] = None,
|
| 136 |
+
points: Optional[List[List[float]]] = None,
|
| 137 |
+
point_labels: Optional[List[int]] = None,
|
| 138 |
+
bounding_boxes: Optional[List[List[float]]] = None,
|
| 139 |
+
bounding_box_labels: Optional[List[int]] = None,
|
| 140 |
+
obj_id: Optional[int] = None,
|
| 141 |
+
):
|
| 142 |
+
"""Add text, box and/or point prompt on a specific video frame."""
|
| 143 |
+
logger.debug(
|
| 144 |
+
f"add prompt on frame {frame_idx} in session {session_id}: "
|
| 145 |
+
f"{text=}, {points=}, {point_labels=}, "
|
| 146 |
+
f"{bounding_boxes=}, {bounding_box_labels=}"
|
| 147 |
+
)
|
| 148 |
+
session = self._get_session(session_id)
|
| 149 |
+
inference_state = session["state"]
|
| 150 |
+
|
| 151 |
+
frame_idx, outputs = self.model.add_prompt(
|
| 152 |
+
inference_state=inference_state,
|
| 153 |
+
frame_idx=frame_idx,
|
| 154 |
+
text_str=text,
|
| 155 |
+
points=points,
|
| 156 |
+
point_labels=point_labels,
|
| 157 |
+
boxes_xywh=bounding_boxes,
|
| 158 |
+
box_labels=bounding_box_labels,
|
| 159 |
+
obj_id=obj_id,
|
| 160 |
+
)
|
| 161 |
+
return {"frame_index": frame_idx, "outputs": outputs}
|
| 162 |
+
|
| 163 |
+
def remove_object(
|
| 164 |
+
self,
|
| 165 |
+
session_id: str,
|
| 166 |
+
obj_id: int,
|
| 167 |
+
is_user_action: bool = True,
|
| 168 |
+
):
|
| 169 |
+
"""Remove an object from tracking."""
|
| 170 |
+
logger.debug(
|
| 171 |
+
f"remove object {obj_id} in session {session_id}: " f"{is_user_action=}"
|
| 172 |
+
)
|
| 173 |
+
session = self._get_session(session_id)
|
| 174 |
+
inference_state = session["state"]
|
| 175 |
+
|
| 176 |
+
self.model.remove_object(
|
| 177 |
+
inference_state=inference_state,
|
| 178 |
+
obj_id=obj_id,
|
| 179 |
+
is_user_action=is_user_action,
|
| 180 |
+
)
|
| 181 |
+
return {"is_success": True}
|
| 182 |
+
|
| 183 |
+
def propagate_in_video(
|
| 184 |
+
self,
|
| 185 |
+
session_id,
|
| 186 |
+
propagation_direction,
|
| 187 |
+
start_frame_idx,
|
| 188 |
+
max_frame_num_to_track,
|
| 189 |
+
):
|
| 190 |
+
"""Propagate the added prompts to get grounding results on all video frames."""
|
| 191 |
+
logger.debug(
|
| 192 |
+
f"propagate in video in session {session_id}: "
|
| 193 |
+
f"{propagation_direction=}, {start_frame_idx=}, {max_frame_num_to_track=}"
|
| 194 |
+
)
|
| 195 |
+
try:
|
| 196 |
+
session = self._get_session(session_id)
|
| 197 |
+
inference_state = session["state"]
|
| 198 |
+
if propagation_direction not in ["both", "forward", "backward"]:
|
| 199 |
+
raise ValueError(
|
| 200 |
+
f"invalid propagation direction: {propagation_direction}"
|
| 201 |
+
)
|
| 202 |
+
|
| 203 |
+
# First doing the forward propagation
|
| 204 |
+
if propagation_direction in ["both", "forward"]:
|
| 205 |
+
for frame_idx, outputs in self.model.propagate_in_video(
|
| 206 |
+
inference_state=inference_state,
|
| 207 |
+
start_frame_idx=start_frame_idx,
|
| 208 |
+
max_frame_num_to_track=max_frame_num_to_track,
|
| 209 |
+
reverse=False,
|
| 210 |
+
):
|
| 211 |
+
yield {"frame_index": frame_idx, "outputs": outputs}
|
| 212 |
+
# Then doing the backward propagation (reverse in time)
|
| 213 |
+
if propagation_direction in ["both", "backward"]:
|
| 214 |
+
for frame_idx, outputs in self.model.propagate_in_video(
|
| 215 |
+
inference_state=inference_state,
|
| 216 |
+
start_frame_idx=start_frame_idx,
|
| 217 |
+
max_frame_num_to_track=max_frame_num_to_track,
|
| 218 |
+
reverse=True,
|
| 219 |
+
):
|
| 220 |
+
yield {"frame_index": frame_idx, "outputs": outputs}
|
| 221 |
+
finally:
|
| 222 |
+
# Log upon completion (so that e.g. we can see if two propagations happen in parallel).
|
| 223 |
+
# Using `finally` here to log even when the tracking is aborted with GeneratorExit.
|
| 224 |
+
logger.debug(
|
| 225 |
+
f"propagation ended in session {session_id}; {self._get_session_stats()}"
|
| 226 |
+
)
|
| 227 |
+
|
| 228 |
+
def reset_session(self, session_id):
|
| 229 |
+
"""Reset the session to its initial state (as when it's initial opened)."""
|
| 230 |
+
logger.debug(f"reset session {session_id}")
|
| 231 |
+
session = self._get_session(session_id)
|
| 232 |
+
inference_state = session["state"]
|
| 233 |
+
self.model.reset_state(inference_state)
|
| 234 |
+
return {"is_success": True}
|
| 235 |
+
|
| 236 |
+
def close_session(self, session_id):
|
| 237 |
+
"""
|
| 238 |
+
Close a session. This method is idempotent and can be called multiple
|
| 239 |
+
times on the same "session_id".
|
| 240 |
+
"""
|
| 241 |
+
session = self._ALL_INFERENCE_STATES.pop(session_id, None)
|
| 242 |
+
if session is None:
|
| 243 |
+
logger.warning(
|
| 244 |
+
f"cannot close session {session_id} as it does not exist (it might have expired); "
|
| 245 |
+
f"{self._get_session_stats()}"
|
| 246 |
+
)
|
| 247 |
+
else:
|
| 248 |
+
del session
|
| 249 |
+
gc.collect()
|
| 250 |
+
logger.info(f"removed session {session_id}; {self._get_session_stats()}")
|
| 251 |
+
return {"is_success": True}
|
| 252 |
+
|
| 253 |
+
def _get_session(self, session_id):
|
| 254 |
+
session = self._ALL_INFERENCE_STATES.get(session_id, None)
|
| 255 |
+
if session is None:
|
| 256 |
+
raise RuntimeError(
|
| 257 |
+
f"Cannot find session {session_id}; it might have expired"
|
| 258 |
+
)
|
| 259 |
+
return session
|
| 260 |
+
|
| 261 |
+
def _get_session_stats(self):
|
| 262 |
+
"""Get a statistics string for live sessions and their GPU usage."""
|
| 263 |
+
# print both the session ids and their video frame numbers
|
| 264 |
+
live_session_strs = [
|
| 265 |
+
f"'{session_id}' ({session['state']['num_frames']} frames)"
|
| 266 |
+
for session_id, session in self._ALL_INFERENCE_STATES.items()
|
| 267 |
+
]
|
| 268 |
+
session_stats_str = (
|
| 269 |
+
f"live sessions: [{', '.join(live_session_strs)}], GPU memory: "
|
| 270 |
+
f"{torch.cuda.memory_allocated() // 1024**2} MiB used and "
|
| 271 |
+
f"{torch.cuda.memory_reserved() // 1024**2} MiB reserved"
|
| 272 |
+
f" (max over time: {torch.cuda.max_memory_allocated() // 1024**2} MiB used "
|
| 273 |
+
f"and {torch.cuda.max_memory_reserved() // 1024**2} MiB reserved)"
|
| 274 |
+
)
|
| 275 |
+
return session_stats_str
|
| 276 |
+
|
| 277 |
+
def _get_torch_and_gpu_properties(self):
|
| 278 |
+
"""Get a string for PyTorch and GPU properties (for logging and debugging)."""
|
| 279 |
+
torch_and_gpu_str = (
|
| 280 |
+
f"torch: {torch.__version__} with CUDA arch {torch.cuda.get_arch_list()}, "
|
| 281 |
+
f"GPU device: {torch.cuda.get_device_properties(torch.cuda.current_device())}"
|
| 282 |
+
)
|
| 283 |
+
return torch_and_gpu_str
|
| 284 |
+
|
| 285 |
+
def shutdown(self):
|
| 286 |
+
"""Shutdown the predictor and clear all sessions."""
|
| 287 |
+
self._ALL_INFERENCE_STATES.clear()
|
| 288 |
+
|
| 289 |
+
|
| 290 |
+
class Sam3VideoPredictorMultiGPU(Sam3VideoPredictor):
|
| 291 |
+
def __init__(self, *model_args, gpus_to_use=None, **model_kwargs):
|
| 292 |
+
if gpus_to_use is None:
|
| 293 |
+
# if not specified, use only the current GPU by default
|
| 294 |
+
gpus_to_use = [torch.cuda.current_device()]
|
| 295 |
+
|
| 296 |
+
IS_MAIN_PROCESS = os.getenv("IS_MAIN_PROCESS", "1") == "1"
|
| 297 |
+
if IS_MAIN_PROCESS:
|
| 298 |
+
gpus_to_use = sorted(set(gpus_to_use))
|
| 299 |
+
logger.info(f"using the following GPU IDs: {gpus_to_use}")
|
| 300 |
+
assert len(gpus_to_use) > 0 and all(isinstance(i, int) for i in gpus_to_use)
|
| 301 |
+
assert all(0 <= i < torch.cuda.device_count() for i in gpus_to_use)
|
| 302 |
+
os.environ["MASTER_ADDR"] = "localhost"
|
| 303 |
+
os.environ["MASTER_PORT"] = f"{self._find_free_port()}"
|
| 304 |
+
os.environ["RANK"] = "0"
|
| 305 |
+
os.environ["WORLD_SIZE"] = f"{len(gpus_to_use)}"
|
| 306 |
+
|
| 307 |
+
self.gpus_to_use = gpus_to_use
|
| 308 |
+
self.rank = int(os.environ["RANK"])
|
| 309 |
+
self.world_size = int(os.environ["WORLD_SIZE"])
|
| 310 |
+
self.rank_str = f"rank={self.rank} with world_size={self.world_size}"
|
| 311 |
+
self.device = torch.device(f"cuda:{self.gpus_to_use[self.rank]}")
|
| 312 |
+
torch.cuda.set_device(self.device)
|
| 313 |
+
self.has_shutdown = False
|
| 314 |
+
if self.rank == 0:
|
| 315 |
+
logger.info("\n\n\n\t*** START loading model on all ranks ***\n\n")
|
| 316 |
+
|
| 317 |
+
logger.info(f"loading model on {self.rank_str} -- this could take a while ...")
|
| 318 |
+
super().__init__(*model_args, **model_kwargs)
|
| 319 |
+
logger.info(f"loading model on {self.rank_str} -- DONE locally")
|
| 320 |
+
|
| 321 |
+
if self.world_size > 1 and self.rank == 0:
|
| 322 |
+
# start the worker processes *after* the model is loaded in the main process
|
| 323 |
+
# so that the main process can run torch.compile and fill the cache first
|
| 324 |
+
self._start_worker_processes(*model_args, **model_kwargs)
|
| 325 |
+
for rank in range(1, self.world_size):
|
| 326 |
+
self.command_queues[rank].put(("start_nccl_process_group", None))
|
| 327 |
+
self._start_nccl_process_group()
|
| 328 |
+
|
| 329 |
+
if self.rank == 0:
|
| 330 |
+
logger.info("\n\n\n\t*** DONE loading model on all ranks ***\n\n")
|
| 331 |
+
|
| 332 |
+
@torch.inference_mode()
|
| 333 |
+
def handle_request(self, request):
|
| 334 |
+
"""Dispatch a request based on its type."""
|
| 335 |
+
if self.has_shutdown:
|
| 336 |
+
raise RuntimeError(
|
| 337 |
+
"cannot handle request after the predictor has shutdown; please create a new predictor"
|
| 338 |
+
)
|
| 339 |
+
|
| 340 |
+
# when starting a session, we need to create a session id before dispatching
|
| 341 |
+
# the request to the workers
|
| 342 |
+
if request["type"] == "start_session" and request.get("session_id") is None:
|
| 343 |
+
request["session_id"] = str(uuid.uuid4())
|
| 344 |
+
# dispatch the request to all worker processes
|
| 345 |
+
if self.world_size > 1 and self.rank == 0:
|
| 346 |
+
for rank in range(1, self.world_size):
|
| 347 |
+
self.command_queues[rank].put((request, False))
|
| 348 |
+
|
| 349 |
+
response = super().handle_request(request)
|
| 350 |
+
|
| 351 |
+
if self.world_size > 1:
|
| 352 |
+
torch.distributed.barrier() # wait for all ranks to finish
|
| 353 |
+
return response
|
| 354 |
+
|
| 355 |
+
@torch.inference_mode()
|
| 356 |
+
def handle_stream_request(self, request):
|
| 357 |
+
"""Dispatch a stream request based on its type."""
|
| 358 |
+
if self.has_shutdown:
|
| 359 |
+
raise RuntimeError(
|
| 360 |
+
"cannot handle request after the predictor has shutdown; please create a new predictor"
|
| 361 |
+
)
|
| 362 |
+
|
| 363 |
+
# dispatch the request to all worker processes
|
| 364 |
+
if self.world_size > 1 and self.rank == 0:
|
| 365 |
+
for rank in range(1, self.world_size):
|
| 366 |
+
self.command_queues[rank].put((request, True))
|
| 367 |
+
|
| 368 |
+
yield from super().handle_stream_request(request)
|
| 369 |
+
|
| 370 |
+
if self.world_size > 1:
|
| 371 |
+
torch.distributed.barrier() # wait for all ranks to finish
|
| 372 |
+
|
| 373 |
+
def _start_worker_processes(self, *model_args, **model_kwargs):
|
| 374 |
+
"""Start worker processes for handling model inference."""
|
| 375 |
+
world_size = self.world_size
|
| 376 |
+
logger.info(f"spawning {world_size - 1} worker processes")
|
| 377 |
+
# Use "spawn" (instead of "fork") for different PyTorch or CUDA context
|
| 378 |
+
mp_ctx = mp.get_context("spawn")
|
| 379 |
+
self.command_queues = {rank: mp_ctx.Queue() for rank in range(1, world_size)}
|
| 380 |
+
self.result_queues = {rank: mp_ctx.Queue() for rank in range(1, world_size)}
|
| 381 |
+
parent_pid = os.getpid()
|
| 382 |
+
for rank in range(1, world_size):
|
| 383 |
+
# set the environment variables for each worker process
|
| 384 |
+
os.environ["IS_MAIN_PROCESS"] = "0" # mark this as a worker process
|
| 385 |
+
os.environ["RANK"] = f"{rank}"
|
| 386 |
+
worker_process = mp_ctx.Process(
|
| 387 |
+
target=Sam3VideoPredictorMultiGPU._worker_process_command_loop,
|
| 388 |
+
args=(
|
| 389 |
+
rank,
|
| 390 |
+
world_size,
|
| 391 |
+
self.command_queues[rank],
|
| 392 |
+
self.result_queues[rank],
|
| 393 |
+
model_args,
|
| 394 |
+
model_kwargs,
|
| 395 |
+
self.gpus_to_use,
|
| 396 |
+
parent_pid,
|
| 397 |
+
),
|
| 398 |
+
daemon=True,
|
| 399 |
+
)
|
| 400 |
+
worker_process.start()
|
| 401 |
+
# revert the environment variables for the main process
|
| 402 |
+
os.environ["IS_MAIN_PROCESS"] = "1"
|
| 403 |
+
os.environ["RANK"] = "0"
|
| 404 |
+
# wait for all the worker processes to load the model and collect their PIDs
|
| 405 |
+
self.worker_pids = {}
|
| 406 |
+
for rank in range(1, self.world_size):
|
| 407 |
+
# a large timeout to cover potentially long model loading time due to compilation
|
| 408 |
+
_, worker_pid = self.result_queues[rank].get(timeout=7200)
|
| 409 |
+
self.worker_pids[rank] = worker_pid
|
| 410 |
+
logger.info(f"spawned {world_size - 1} worker processes")
|
| 411 |
+
|
| 412 |
+
def _start_nccl_process_group(self):
|
| 413 |
+
rank = int(os.environ["RANK"])
|
| 414 |
+
world_size = int(os.environ["WORLD_SIZE"])
|
| 415 |
+
if world_size == 1:
|
| 416 |
+
return
|
| 417 |
+
|
| 418 |
+
logger.debug(f"starting NCCL process group on {rank=} with {world_size=}")
|
| 419 |
+
assert not torch.distributed.is_initialized()
|
| 420 |
+
# use the "env://" init method with environment variables set in start_worker_processes
|
| 421 |
+
# a short 3-min timeout to quickly detect any synchronization failures
|
| 422 |
+
timeout_sec = int(os.getenv("SAM3_COLLECTIVE_OP_TIMEOUT_SEC", "180"))
|
| 423 |
+
timeout = datetime.timedelta(seconds=timeout_sec)
|
| 424 |
+
torch.distributed.init_process_group(
|
| 425 |
+
backend="nccl",
|
| 426 |
+
init_method="env://",
|
| 427 |
+
timeout=timeout,
|
| 428 |
+
device_id=self.device,
|
| 429 |
+
)
|
| 430 |
+
# warm-up the NCCL process group by running a dummy all-reduce
|
| 431 |
+
tensor = torch.ones(1024, 1024).cuda()
|
| 432 |
+
torch.distributed.all_reduce(tensor)
|
| 433 |
+
logger.debug(f"started NCCL process group on {rank=} with {world_size=}")
|
| 434 |
+
|
| 435 |
+
def _find_free_port(self) -> int:
|
| 436 |
+
"""
|
| 437 |
+
Find a free port (a random free port from 1024 to 65535 will be selected)
|
| 438 |
+
https://stackoverflow.com/questions/1365265/on-localhost-how-do-i-pick-a-free-port-number)
|
| 439 |
+
"""
|
| 440 |
+
with closing(socket.socket(socket.AF_INET, socket.SOCK_STREAM)) as s:
|
| 441 |
+
s.bind(("", 0))
|
| 442 |
+
s.setsockopt(socket.SOL_SOCKET, socket.SO_REUSEADDR, 1)
|
| 443 |
+
return s.getsockname()[1]
|
| 444 |
+
|
| 445 |
+
@staticmethod
|
| 446 |
+
def _worker_process_command_loop(
|
| 447 |
+
rank,
|
| 448 |
+
world_size,
|
| 449 |
+
command_queue,
|
| 450 |
+
result_queue,
|
| 451 |
+
model_args,
|
| 452 |
+
model_kwargs,
|
| 453 |
+
gpus_to_use,
|
| 454 |
+
parent_pid,
|
| 455 |
+
):
|
| 456 |
+
"""
|
| 457 |
+
The command loop for each worker process. It listens to commands from the main process
|
| 458 |
+
and executes them using the model.
|
| 459 |
+
"""
|
| 460 |
+
logger.info(f"starting worker process {rank=} with {world_size=}")
|
| 461 |
+
# verify that the environment variables are set correctly
|
| 462 |
+
assert int(os.environ["IS_MAIN_PROCESS"]) == 0
|
| 463 |
+
assert int(os.environ["RANK"]) == rank
|
| 464 |
+
assert int(os.environ["WORLD_SIZE"]) == world_size
|
| 465 |
+
# load the model in this worker process
|
| 466 |
+
predictor = Sam3VideoPredictorMultiGPU(
|
| 467 |
+
*model_args, gpus_to_use=gpus_to_use, **model_kwargs
|
| 468 |
+
)
|
| 469 |
+
logger.info(f"started worker {rank=} with {world_size=}")
|
| 470 |
+
# return the worker process id to the main process for bookkeeping
|
| 471 |
+
worker_pid = os.getpid()
|
| 472 |
+
result_queue.put(("load_model", worker_pid))
|
| 473 |
+
|
| 474 |
+
# wait for the command to start the NCCL process group
|
| 475 |
+
request_type, _ = command_queue.get(timeout=7200)
|
| 476 |
+
assert request_type == "start_nccl_process_group"
|
| 477 |
+
predictor._start_nccl_process_group()
|
| 478 |
+
|
| 479 |
+
# keep listening to commands from the main process
|
| 480 |
+
while True:
|
| 481 |
+
try:
|
| 482 |
+
request, is_stream_request = command_queue.get(timeout=5.0)
|
| 483 |
+
if request == "shutdown":
|
| 484 |
+
logger.info(f"worker {rank=} shutting down")
|
| 485 |
+
torch.distributed.destroy_process_group()
|
| 486 |
+
result_queue.put(("shutdown", True)) # acknowledge the shutdown
|
| 487 |
+
sys.exit(0)
|
| 488 |
+
|
| 489 |
+
logger.debug(f"worker {rank=} received request {request['type']=}")
|
| 490 |
+
if is_stream_request:
|
| 491 |
+
for _ in predictor.handle_stream_request(request):
|
| 492 |
+
pass # handle stream requests in a generator fashion
|
| 493 |
+
else:
|
| 494 |
+
predictor.handle_request(request)
|
| 495 |
+
except queue.Empty:
|
| 496 |
+
# Usually Python's multiprocessing module will shutdown all the daemon worker
|
| 497 |
+
# processes when the main process exits gracefully. However, the user may kill
|
| 498 |
+
# the main process using SIGKILL and thereby leaving no chance for the main process
|
| 499 |
+
# to clean up its daemon child processes. So here we manually check whether the
|
| 500 |
+
# parent process still exists (every 5 sec as in `command_queue.get` timeout).
|
| 501 |
+
if not psutil.pid_exists(parent_pid):
|
| 502 |
+
logger.info(
|
| 503 |
+
f"stopping worker {rank=} as its parent process has exited"
|
| 504 |
+
)
|
| 505 |
+
sys.exit(1)
|
| 506 |
+
except Exception as e:
|
| 507 |
+
logger.error(f"worker {rank=} exception: {e}", exc_info=True)
|
| 508 |
+
|
| 509 |
+
def shutdown(self):
|
| 510 |
+
"""Shutdown all worker processes."""
|
| 511 |
+
if self.rank == 0 and self.world_size > 1:
|
| 512 |
+
logger.info(f"shutting down {self.world_size - 1} worker processes")
|
| 513 |
+
for rank in range(1, self.world_size):
|
| 514 |
+
self.command_queues[rank].put(("shutdown", False))
|
| 515 |
+
torch.distributed.destroy_process_group()
|
| 516 |
+
for rank in range(1, self.world_size):
|
| 517 |
+
self.result_queues[rank].get() # wait for the worker to acknowledge
|
| 518 |
+
logger.info(f"shut down {self.world_size - 1} worker processes")
|
| 519 |
+
self.has_shutdown = True
|
| 520 |
+
|
| 521 |
+
super().shutdown()
|
之前的代码版本/这一版注意力有问题/HuatuoGPT-Vision/MedSAM3/sam3/model/tokenizer_ve.py
ADDED
|
@@ -0,0 +1,253 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
# Copyright (c) Meta Platforms, Inc. and affiliates. All Rights Reserved
|
| 2 |
+
|
| 3 |
+
"""
|
| 4 |
+
Text Tokenizer.
|
| 5 |
+
|
| 6 |
+
Copied and lightly adapted from VE repo, which in turn copied
|
| 7 |
+
from open_clip and openAI CLIP.
|
| 8 |
+
"""
|
| 9 |
+
|
| 10 |
+
import gzip
|
| 11 |
+
import html
|
| 12 |
+
import io
|
| 13 |
+
import os
|
| 14 |
+
import string
|
| 15 |
+
from functools import lru_cache
|
| 16 |
+
from typing import List, Optional, Union
|
| 17 |
+
|
| 18 |
+
import ftfy
|
| 19 |
+
import regex as re
|
| 20 |
+
import torch
|
| 21 |
+
from iopath.common.file_io import g_pathmgr
|
| 22 |
+
|
| 23 |
+
|
| 24 |
+
# https://stackoverflow.com/q/62691279
|
| 25 |
+
os.environ["TOKENIZERS_PARALLELISM"] = "false"
|
| 26 |
+
DEFAULT_CONTEXT_LENGTH = 77
|
| 27 |
+
|
| 28 |
+
|
| 29 |
+
@lru_cache()
|
| 30 |
+
def bytes_to_unicode():
|
| 31 |
+
"""
|
| 32 |
+
Returns list of utf-8 byte and a corresponding list of unicode strings.
|
| 33 |
+
The reversible bpe codes work on unicode strings.
|
| 34 |
+
This means you need a large # of unicode characters in your vocab if you want to avoid UNKs.
|
| 35 |
+
When you're at something like a 10B token dataset you end up needing around 5K for decent coverage.
|
| 36 |
+
This is a significant percentage of your normal, say, 32K bpe vocab.
|
| 37 |
+
To avoid that, we want lookup tables between utf-8 bytes and unicode strings.
|
| 38 |
+
And avoids mapping to whitespace/control characters the bpe code barfs on.
|
| 39 |
+
"""
|
| 40 |
+
bs = (
|
| 41 |
+
list(range(ord("!"), ord("~") + 1))
|
| 42 |
+
+ list(range(ord("¡"), ord("¬") + 1))
|
| 43 |
+
+ list(range(ord("®"), ord("ÿ") + 1))
|
| 44 |
+
)
|
| 45 |
+
cs = bs[:]
|
| 46 |
+
n = 0
|
| 47 |
+
for b in range(2**8):
|
| 48 |
+
if b not in bs:
|
| 49 |
+
bs.append(b)
|
| 50 |
+
cs.append(2**8 + n)
|
| 51 |
+
n += 1
|
| 52 |
+
cs = [chr(n) for n in cs]
|
| 53 |
+
return dict(zip(bs, cs))
|
| 54 |
+
|
| 55 |
+
|
| 56 |
+
def get_pairs(word):
|
| 57 |
+
"""Return set of symbol pairs in a word.
|
| 58 |
+
Word is represented as tuple of symbols (symbols being variable-length strings).
|
| 59 |
+
"""
|
| 60 |
+
pairs = set()
|
| 61 |
+
prev_char = word[0]
|
| 62 |
+
for char in word[1:]:
|
| 63 |
+
pairs.add((prev_char, char))
|
| 64 |
+
prev_char = char
|
| 65 |
+
return pairs
|
| 66 |
+
|
| 67 |
+
|
| 68 |
+
def basic_clean(text):
|
| 69 |
+
text = ftfy.fix_text(text)
|
| 70 |
+
text = html.unescape(html.unescape(text))
|
| 71 |
+
return text.strip()
|
| 72 |
+
|
| 73 |
+
|
| 74 |
+
def whitespace_clean(text):
|
| 75 |
+
text = re.sub(r"\s+", " ", text)
|
| 76 |
+
text = text.strip()
|
| 77 |
+
return text
|
| 78 |
+
|
| 79 |
+
|
| 80 |
+
def _clean_canonicalize(x):
|
| 81 |
+
# basic, remove whitespace, remove punctuation, lower case
|
| 82 |
+
return canonicalize_text(basic_clean(x))
|
| 83 |
+
|
| 84 |
+
|
| 85 |
+
def _clean_lower(x):
|
| 86 |
+
# basic, remove whitespace, lower case
|
| 87 |
+
return whitespace_clean(basic_clean(x)).lower()
|
| 88 |
+
|
| 89 |
+
|
| 90 |
+
def _clean_whitespace(x):
|
| 91 |
+
# basic, remove whitespace
|
| 92 |
+
return whitespace_clean(basic_clean(x))
|
| 93 |
+
|
| 94 |
+
|
| 95 |
+
def get_clean_fn(type: str):
|
| 96 |
+
if type == "canonicalize":
|
| 97 |
+
return _clean_canonicalize
|
| 98 |
+
elif type == "lower":
|
| 99 |
+
return _clean_lower
|
| 100 |
+
elif type == "whitespace":
|
| 101 |
+
return _clean_whitespace
|
| 102 |
+
else:
|
| 103 |
+
assert False, f"Invalid clean function ({type})."
|
| 104 |
+
|
| 105 |
+
|
| 106 |
+
def canonicalize_text(text, *, keep_punctuation_exact_string=None):
|
| 107 |
+
"""Returns canonicalized `text` (lowercase and punctuation removed).
|
| 108 |
+
From: https://github.com/google-research/big_vision/blob/53f18caf27a9419231bbf08d3388b07671616d3d/big_vision/evaluators/proj/image_text/prompt_engineering.py#L94
|
| 109 |
+
Args:
|
| 110 |
+
text: string to be canonicalized.
|
| 111 |
+
keep_punctuation_exact_string: If provided, then this exact string kept.
|
| 112 |
+
For example providing '{}' will keep any occurrences of '{}' (but will
|
| 113 |
+
still remove '{' and '}' that appear separately).
|
| 114 |
+
"""
|
| 115 |
+
text = text.replace("_", " ")
|
| 116 |
+
if keep_punctuation_exact_string:
|
| 117 |
+
text = keep_punctuation_exact_string.join(
|
| 118 |
+
part.translate(str.maketrans("", "", string.punctuation))
|
| 119 |
+
for part in text.split(keep_punctuation_exact_string)
|
| 120 |
+
)
|
| 121 |
+
else:
|
| 122 |
+
text = text.translate(str.maketrans("", "", string.punctuation))
|
| 123 |
+
text = text.lower()
|
| 124 |
+
text = re.sub(r"\s+", " ", text)
|
| 125 |
+
return text.strip()
|
| 126 |
+
|
| 127 |
+
|
| 128 |
+
class SimpleTokenizer(object):
|
| 129 |
+
def __init__(
|
| 130 |
+
self,
|
| 131 |
+
bpe_path: Union[str, os.PathLike],
|
| 132 |
+
additional_special_tokens: Optional[List[str]] = None,
|
| 133 |
+
context_length: Optional[int] = DEFAULT_CONTEXT_LENGTH,
|
| 134 |
+
clean: str = "lower",
|
| 135 |
+
):
|
| 136 |
+
self.byte_encoder = bytes_to_unicode()
|
| 137 |
+
self.byte_decoder = {v: k for k, v in self.byte_encoder.items()}
|
| 138 |
+
with g_pathmgr.open(bpe_path, "rb") as fh:
|
| 139 |
+
bpe_bytes = io.BytesIO(fh.read())
|
| 140 |
+
merges = gzip.open(bpe_bytes).read().decode("utf-8").split("\n")
|
| 141 |
+
# merges = gzip.open(bpe_path).read().decode("utf-8").split("\n")
|
| 142 |
+
merges = merges[1 : 49152 - 256 - 2 + 1]
|
| 143 |
+
merges = [tuple(merge.split()) for merge in merges]
|
| 144 |
+
vocab = list(bytes_to_unicode().values())
|
| 145 |
+
vocab = vocab + [v + "</w>" for v in vocab]
|
| 146 |
+
for merge in merges:
|
| 147 |
+
vocab.append("".join(merge))
|
| 148 |
+
special_tokens = ["<start_of_text>", "<end_of_text>"]
|
| 149 |
+
if additional_special_tokens:
|
| 150 |
+
special_tokens += additional_special_tokens
|
| 151 |
+
vocab.extend(special_tokens)
|
| 152 |
+
self.encoder = dict(zip(vocab, range(len(vocab))))
|
| 153 |
+
self.decoder = {v: k for k, v in self.encoder.items()}
|
| 154 |
+
self.bpe_ranks = dict(zip(merges, range(len(merges))))
|
| 155 |
+
self.cache = {t: t for t in special_tokens}
|
| 156 |
+
special = "|".join(special_tokens)
|
| 157 |
+
self.pat = re.compile(
|
| 158 |
+
special + r"""|'s|'t|'re|'ve|'m|'ll|'d|[\p{L}]+|[\p{N}]|[^\s\p{L}\p{N}]+""",
|
| 159 |
+
re.IGNORECASE,
|
| 160 |
+
)
|
| 161 |
+
self.vocab_size = len(self.encoder)
|
| 162 |
+
self.all_special_ids = [self.encoder[t] for t in special_tokens]
|
| 163 |
+
self.sot_token_id = self.all_special_ids[0]
|
| 164 |
+
self.eot_token_id = self.all_special_ids[1]
|
| 165 |
+
self.context_length = context_length
|
| 166 |
+
self.clean_fn = get_clean_fn(clean)
|
| 167 |
+
|
| 168 |
+
def bpe(self, token):
|
| 169 |
+
if token in self.cache:
|
| 170 |
+
return self.cache[token]
|
| 171 |
+
word = tuple(token[:-1]) + (token[-1] + "</w>",)
|
| 172 |
+
pairs = get_pairs(word)
|
| 173 |
+
if not pairs:
|
| 174 |
+
return token + "</w>"
|
| 175 |
+
while True:
|
| 176 |
+
bigram = min(pairs, key=lambda pair: self.bpe_ranks.get(pair, float("inf")))
|
| 177 |
+
if bigram not in self.bpe_ranks:
|
| 178 |
+
break
|
| 179 |
+
first, second = bigram
|
| 180 |
+
new_word = []
|
| 181 |
+
i = 0
|
| 182 |
+
while i < len(word):
|
| 183 |
+
try:
|
| 184 |
+
j = word.index(first, i)
|
| 185 |
+
new_word.extend(word[i:j])
|
| 186 |
+
i = j
|
| 187 |
+
except:
|
| 188 |
+
new_word.extend(word[i:])
|
| 189 |
+
break
|
| 190 |
+
if word[i] == first and i < len(word) - 1 and word[i + 1] == second:
|
| 191 |
+
new_word.append(first + second)
|
| 192 |
+
i += 2
|
| 193 |
+
else:
|
| 194 |
+
new_word.append(word[i])
|
| 195 |
+
i += 1
|
| 196 |
+
new_word = tuple(new_word)
|
| 197 |
+
word = new_word
|
| 198 |
+
if len(word) == 1:
|
| 199 |
+
break
|
| 200 |
+
else:
|
| 201 |
+
pairs = get_pairs(word)
|
| 202 |
+
word = " ".join(word)
|
| 203 |
+
self.cache[token] = word
|
| 204 |
+
return word
|
| 205 |
+
|
| 206 |
+
def encode(self, text):
|
| 207 |
+
bpe_tokens = []
|
| 208 |
+
text = self.clean_fn(text)
|
| 209 |
+
for token in re.findall(self.pat, text):
|
| 210 |
+
token = "".join(self.byte_encoder[b] for b in token.encode("utf-8"))
|
| 211 |
+
bpe_tokens.extend(
|
| 212 |
+
self.encoder[bpe_token] for bpe_token in self.bpe(token).split(" ")
|
| 213 |
+
)
|
| 214 |
+
return bpe_tokens
|
| 215 |
+
|
| 216 |
+
def decode(self, tokens):
|
| 217 |
+
text = "".join([self.decoder[token] for token in tokens])
|
| 218 |
+
text = (
|
| 219 |
+
bytearray([self.byte_decoder[c] for c in text])
|
| 220 |
+
.decode("utf-8", errors="replace")
|
| 221 |
+
.replace("</w>", " ")
|
| 222 |
+
)
|
| 223 |
+
return text
|
| 224 |
+
|
| 225 |
+
def __call__(
|
| 226 |
+
self, texts: Union[str, List[str]], context_length: Optional[int] = None
|
| 227 |
+
) -> torch.LongTensor:
|
| 228 |
+
"""Returns the tokenized representation of given input string(s)
|
| 229 |
+
Parameters
|
| 230 |
+
----------
|
| 231 |
+
texts : Union[str, List[str]]
|
| 232 |
+
An input string or a list of input strings to tokenize
|
| 233 |
+
context_length : int
|
| 234 |
+
The context length to use; all CLIP models use 77 as the context length
|
| 235 |
+
Returns
|
| 236 |
+
-------
|
| 237 |
+
A two-dimensional tensor containing the resulting tokens, shape = [number of input strings, context_length]
|
| 238 |
+
"""
|
| 239 |
+
if isinstance(texts, str):
|
| 240 |
+
texts = [texts]
|
| 241 |
+
context_length = context_length or self.context_length
|
| 242 |
+
assert context_length, "Please set a valid context length"
|
| 243 |
+
all_tokens = [
|
| 244 |
+
[self.sot_token_id] + self.encode(text) + [self.eot_token_id]
|
| 245 |
+
for text in texts
|
| 246 |
+
]
|
| 247 |
+
result = torch.zeros(len(all_tokens), context_length, dtype=torch.long)
|
| 248 |
+
for i, tokens in enumerate(all_tokens):
|
| 249 |
+
if len(tokens) > context_length:
|
| 250 |
+
tokens = tokens[:context_length] # Truncate
|
| 251 |
+
tokens[-1] = self.eot_token_id
|
| 252 |
+
result[i, : len(tokens)] = torch.tensor(tokens)
|
| 253 |
+
return result
|