IFMedTechdemo commited on
Commit
ef99afc
·
verified ·
1 Parent(s): 1b7162b

Upload folder using huggingface_hub

Browse files
This view is limited to 50 files because it contains too many changes.   See raw diff
Files changed (50) hide show
  1. .gitattributes +2 -0
  2. README.md +31 -12
  3. app.py +264 -7
  4. models/__init__.py +6 -0
  5. models/__pycache__/__init__.cpython-310.pyc +0 -0
  6. models/__pycache__/__init__.cpython-311.pyc +0 -0
  7. models/__pycache__/__init__.cpython-312.pyc +0 -0
  8. models/__pycache__/backbone.cpython-310.pyc +0 -0
  9. models/__pycache__/backbone.cpython-311.pyc +0 -0
  10. models/__pycache__/backbone.cpython-312.pyc +0 -0
  11. models/__pycache__/detr.cpython-310.pyc +0 -0
  12. models/__pycache__/detr.cpython-311.pyc +0 -0
  13. models/__pycache__/detr_seg.cpython-310.pyc +0 -0
  14. models/__pycache__/detr_seg.cpython-312.pyc +0 -0
  15. models/__pycache__/matcher.cpython-310.pyc +0 -0
  16. models/__pycache__/matcher.cpython-311.pyc +0 -0
  17. models/__pycache__/matcher.cpython-312.pyc +0 -0
  18. models/__pycache__/position_encoding.cpython-310.pyc +0 -0
  19. models/__pycache__/position_encoding.cpython-311.pyc +0 -0
  20. models/__pycache__/position_encoding.cpython-312.pyc +0 -0
  21. models/__pycache__/segmentation.cpython-310.pyc +0 -0
  22. models/__pycache__/segmentation.cpython-311.pyc +0 -0
  23. models/__pycache__/segmentation.cpython-312.pyc +0 -0
  24. models/__pycache__/swin_transformer.cpython-310.pyc +0 -0
  25. models/__pycache__/swin_transformer.cpython-312.pyc +0 -0
  26. models/__pycache__/transformer.cpython-310.pyc +0 -0
  27. models/__pycache__/transformer.cpython-311.pyc +0 -0
  28. models/__pycache__/transformer.cpython-312.pyc +0 -0
  29. models/backbone.py +213 -0
  30. models/detr.py +407 -0
  31. models/detr_seg.py +616 -0
  32. models/matcher.py +86 -0
  33. models/position_encoding.py +89 -0
  34. models/sam/CODE_OF_CONDUCT.md +80 -0
  35. models/sam/CONTRIBUTING.md +31 -0
  36. models/sam/LICENSE +201 -0
  37. models/sam/README.md +171 -0
  38. models/sam/linter.sh +32 -0
  39. models/sam/notebooks/automatic_mask_generator_example.ipynb +0 -0
  40. models/sam/notebooks/images/dog.jpg +0 -0
  41. models/sam/notebooks/images/groceries.jpg +3 -0
  42. models/sam/notebooks/images/truck.jpg +3 -0
  43. models/sam/notebooks/onnx_model_example.ipynb +774 -0
  44. models/sam/notebooks/predictor_example.ipynb +0 -0
  45. models/sam/scripts/amg.py +238 -0
  46. models/sam/scripts/export_onnx_model.py +201 -0
  47. models/sam/segment_anything/__init__.py +15 -0
  48. models/sam/segment_anything/__pycache__/__init__.cpython-310.pyc +0 -0
  49. models/sam/segment_anything/__pycache__/__init__.cpython-312.pyc +0 -0
  50. models/sam/segment_anything/__pycache__/automatic_mask_generator.cpython-310.pyc +0 -0
.gitattributes CHANGED
@@ -33,3 +33,5 @@ saved_model/**/* filter=lfs diff=lfs merge=lfs -text
33
  *.zip filter=lfs diff=lfs merge=lfs -text
34
  *.zst filter=lfs diff=lfs merge=lfs -text
35
  *tfevents* filter=lfs diff=lfs merge=lfs -text
 
 
 
33
  *.zip filter=lfs diff=lfs merge=lfs -text
34
  *.zst filter=lfs diff=lfs merge=lfs -text
35
  *tfevents* filter=lfs diff=lfs merge=lfs -text
36
+ models/sam/notebooks/images/groceries.jpg filter=lfs diff=lfs merge=lfs -text
37
+ models/sam/notebooks/images/truck.jpg filter=lfs diff=lfs merge=lfs -text
README.md CHANGED
@@ -1,12 +1,31 @@
1
- ---
2
- title: Video Segmentation
3
- emoji: 👁
4
- colorFrom: blue
5
- colorTo: purple
6
- sdk: gradio
7
- sdk_version: 6.2.0
8
- app_file: app.py
9
- pinned: false
10
- ---
11
-
12
- Check out the configuration reference at https://huggingface.co/docs/hub/spaces-config-reference
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ ---
2
+ title: Surgical-DeSAM
3
+ emoji: 🔬
4
+ colorFrom: blue
5
+ colorTo: green
6
+ sdk: gradio
7
+ sdk_version: 4.44.0
8
+ app_file: app.py
9
+ pinned: false
10
+ license: apache-2.0
11
+ ---
12
+
13
+ # Surgical-DeSAM
14
+
15
+ Surgical instrument segmentation using DeSAM (Decoupled SAM) architecture.
16
+
17
+ Upload a surgical image to get instance segmentation masks for instruments.
18
+
19
+ ## Model
20
+
21
+ Based on [Surgical-DeSAM](https://github.com/YuyangSheng/Surgical-DeSAM) - integrates DETR for detection and SAM for segmentation.
22
+
23
+ ## Classes Detected
24
+ - Bipolar Forceps
25
+ - Prograsp Forceps
26
+ - Large Needle Driver
27
+ - Monopolar Curved Scissors
28
+ - Ultrasound Probe
29
+ - Suction
30
+ - Clip Applier
31
+ - Stapler
app.py CHANGED
@@ -1,7 +1,264 @@
1
- import gradio as gr
2
-
3
- def greet(name):
4
- return "Hello " + name + "!!"
5
-
6
- demo = gr.Interface(fn=greet, inputs="text", outputs="text")
7
- demo.launch()
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ """
2
+ Surgical-DeSAM Gradio App for Hugging Face Spaces
3
+ Uses ZeroGPU for inference
4
+ """
5
+ import os
6
+ import spaces
7
+ import gradio as gr
8
+ import torch
9
+ import numpy as np
10
+ import cv2
11
+ from PIL import Image
12
+ from huggingface_hub import hf_hub_download
13
+
14
+ # Model imports (will be copied to hf_space)
15
+ from models.detr_seg import DETR, SAMModel
16
+ from models.backbone import build_backbone
17
+ from models.transformer import build_transformer
18
+ from util.misc import NestedTensor
19
+
20
+ # Configuration
21
+ MODEL_REPO = os.environ.get("MODEL_REPO", "IFMedTech/surgical-desam-weights")
22
+ HF_TOKEN = os.environ.get("HF_TOKEN")
23
+
24
+ INSTRUMENT_CLASSES = (
25
+ 'bipolar_forceps', 'prograsp_forceps', 'large_needle_driver',
26
+ 'monopolar_curved_scissors', 'ultrasound_probe', 'suction',
27
+ 'clip_applier', 'stapler'
28
+ )
29
+
30
+ COLORS = [
31
+ [0, 114, 189], [217, 83, 25], [237, 177, 32],
32
+ [126, 47, 142], [119, 172, 48], [77, 190, 238],
33
+ [162, 20, 47], [76, 76, 76]
34
+ ]
35
+
36
+ # Global model variables
37
+ model = None
38
+ seg_model = None
39
+ device = None
40
+
41
+
42
+ def download_weights():
43
+ """Download model weights from private HF repo"""
44
+ weights_dir = "weights"
45
+ os.makedirs(weights_dir, exist_ok=True)
46
+
47
+ # Download DeSAM weights
48
+ desam_path = hf_hub_download(
49
+ repo_id=MODEL_REPO,
50
+ filename="surgical_desam_1024.pth",
51
+ token=HF_TOKEN,
52
+ local_dir=weights_dir
53
+ )
54
+
55
+ # Download SAM weights
56
+ sam_path = hf_hub_download(
57
+ repo_id=MODEL_REPO,
58
+ filename="sam_vit_b_01ec64.pth",
59
+ token=HF_TOKEN,
60
+ local_dir=weights_dir
61
+ )
62
+
63
+ # Download Swin backbone
64
+ swin_dir = "swin_backbone"
65
+ os.makedirs(swin_dir, exist_ok=True)
66
+ swin_path = hf_hub_download(
67
+ repo_id=MODEL_REPO,
68
+ filename="swin_base_patch4_window7_224_22kto1k.pth",
69
+ token=HF_TOKEN,
70
+ local_dir=swin_dir
71
+ )
72
+
73
+ return desam_path, sam_path
74
+
75
+
76
+ class Args:
77
+ """Mock args for model building"""
78
+ backbone = 'swin_B_224_22k'
79
+ dilation = False
80
+ position_embedding = 'sine'
81
+ hidden_dim = 256
82
+ dropout = 0.1
83
+ nheads = 8
84
+ dim_feedforward = 2048
85
+ enc_layers = 6
86
+ dec_layers = 6
87
+ pre_norm = False
88
+ num_queries = 100
89
+ aux_loss = False
90
+ lr_backbone = 1e-5
91
+ masks = False
92
+ dataset_file = 'endovis18'
93
+ device = 'cuda'
94
+ backbone_dir = './swin_backbone'
95
+
96
+
97
+ def load_models():
98
+ """Load DETR and SAM models"""
99
+ global model, seg_model, device
100
+
101
+ device = torch.device("cuda" if torch.cuda.is_available() else "cpu")
102
+
103
+ # Download weights
104
+ desam_path, sam_path = download_weights()
105
+
106
+ # Build model
107
+ args = Args()
108
+ args.device = str(device)
109
+
110
+ backbone = build_backbone(args)
111
+ transformer = build_transformer(args)
112
+
113
+ model = DETR(
114
+ backbone,
115
+ transformer,
116
+ num_classes=9, # 8 classes + background
117
+ num_queries=args.num_queries,
118
+ aux_loss=args.aux_loss,
119
+ )
120
+
121
+ # Load weights
122
+ checkpoint = torch.load(desam_path, map_location='cpu')
123
+ model.load_state_dict(checkpoint['model'], strict=False)
124
+ model.to(device)
125
+ model.eval()
126
+
127
+ # Load SAM model
128
+ seg_model = SAMModel(device=device, ckpt_path=sam_path)
129
+ if 'seg_model' in checkpoint:
130
+ seg_model.load_state_dict(checkpoint['seg_model'])
131
+ seg_model.to(device)
132
+ seg_model.eval()
133
+
134
+ print("Models loaded successfully!")
135
+
136
+
137
+ def preprocess_image(image):
138
+ """Preprocess image for model input"""
139
+ # Resize to 1024x1024
140
+ img = cv2.resize(np.array(image), (1024, 1024))
141
+ img = img.astype(np.float32) / 255.0
142
+
143
+ # Normalize
144
+ mean = np.array([0.485, 0.456, 0.406])
145
+ std = np.array([0.229, 0.224, 0.225])
146
+ img = (img - mean) / std
147
+
148
+ # Convert to tensor
149
+ img_tensor = torch.from_numpy(img.transpose(2, 0, 1)).float()
150
+ return img_tensor
151
+
152
+
153
+ def box_cxcywh_to_xyxy(x):
154
+ """Convert boxes from center format to corner format"""
155
+ x_c, y_c, w, h = x.unbind(-1)
156
+ b = [(x_c - 0.5 * w), (y_c - 0.5 * h),
157
+ (x_c + 0.5 * w), (y_c + 0.5 * h)]
158
+ return torch.stack(b, dim=-1)
159
+
160
+
161
+ def create_visualization(image, boxes, labels, masks, scores):
162
+ """Create visualization with boxes and masks"""
163
+ img = np.array(image).copy()
164
+ h, w = img.shape[:2]
165
+
166
+ for i, (box, label, mask, score) in enumerate(zip(boxes, labels, masks, scores)):
167
+ if score < 0.3:
168
+ continue
169
+
170
+ color = COLORS[label % len(COLORS)]
171
+
172
+ # Draw mask
173
+ mask_resized = cv2.resize(mask, (w, h))
174
+ mask_bool = mask_resized > 0.5
175
+ overlay = img.copy()
176
+ overlay[mask_bool] = color
177
+ img = cv2.addWeighted(img, 0.6, overlay, 0.4, 0)
178
+
179
+ # Draw box
180
+ x1, y1, x2, y2 = box.astype(int)
181
+ cv2.rectangle(img, (x1, y1), (x2, y2), color, 2)
182
+
183
+ # Draw label
184
+ label_text = f"{INSTRUMENT_CLASSES[label]}: {score:.2f}"
185
+ cv2.putText(img, label_text, (x1, y1 - 10),
186
+ cv2.FONT_HERSHEY_SIMPLEX, 0.5, color, 2)
187
+
188
+ return Image.fromarray(img)
189
+
190
+
191
+ @spaces.GPU
192
+ def predict(image):
193
+ """Run inference on input image"""
194
+ global model, seg_model, device
195
+
196
+ if model is None:
197
+ load_models()
198
+
199
+ if image is None:
200
+ return None
201
+
202
+ # Preprocess
203
+ img_tensor = preprocess_image(image).unsqueeze(0).to(device)
204
+
205
+ # Create nested tensor
206
+ mask = torch.zeros((1, 1024, 1024), dtype=torch.bool, device=device)
207
+ samples = NestedTensor(img_tensor, mask)
208
+
209
+ # Run detection
210
+ with torch.no_grad():
211
+ outputs, image_embeddings = model(samples)
212
+
213
+ # Get predictions
214
+ probas = outputs['pred_logits'].softmax(-1)[0, :, :-1]
215
+ keep = probas.max(-1).values > 0.3
216
+
217
+ if not keep.any():
218
+ return image # No detections
219
+
220
+ # Get boxes
221
+ boxes = outputs['pred_boxes'][0, keep]
222
+ scores = probas[keep].max(-1).values.cpu().numpy()
223
+ labels = probas[keep].argmax(-1).cpu().numpy()
224
+
225
+ # Scale boxes to image size
226
+ h, w = image.size[1], image.size[0]
227
+ boxes_scaled = box_cxcywh_to_xyxy(boxes) * torch.tensor([w, h, w, h], device=device)
228
+ boxes_np = boxes_scaled.cpu().numpy()
229
+
230
+ # Run segmentation
231
+ low_res_masks, pred_masks, _ = seg_model(
232
+ img_tensor, boxes, image_embeddings,
233
+ sizes=(1024, 1024), add_noise=False
234
+ )
235
+ masks_np = pred_masks.cpu().numpy()
236
+
237
+ # Create visualization
238
+ result = create_visualization(image, boxes_np, labels, masks_np, scores)
239
+
240
+ return result
241
+
242
+
243
+ # Create Gradio interface
244
+ with gr.Blocks(title="Surgical-DeSAM") as demo:
245
+ gr.Markdown("# 🔬 Surgical-DeSAM")
246
+ gr.Markdown("Upload a surgical image to segment instruments.")
247
+
248
+ with gr.Row():
249
+ with gr.Column():
250
+ input_image = gr.Image(type="pil", label="Input Image")
251
+ submit_btn = gr.Button("Segment", variant="primary")
252
+
253
+ with gr.Column():
254
+ output_image = gr.Image(type="pil", label="Segmentation Result")
255
+
256
+ submit_btn.click(fn=predict, inputs=input_image, outputs=output_image)
257
+
258
+ gr.Examples(
259
+ examples=[], # Add example images if available
260
+ inputs=input_image
261
+ )
262
+
263
+ if __name__ == "__main__":
264
+ demo.launch()
models/__init__.py ADDED
@@ -0,0 +1,6 @@
 
 
 
 
 
 
 
1
+ # Copyright (c) Facebook, Inc. and its affiliates. All Rights Reserved
2
+ from .detr_seg import build
3
+
4
+
5
+ def build_model(args):
6
+ return build(args)
models/__pycache__/__init__.cpython-310.pyc ADDED
Binary file (320 Bytes). View file
 
models/__pycache__/__init__.cpython-311.pyc ADDED
Binary file (380 Bytes). View file
 
models/__pycache__/__init__.cpython-312.pyc ADDED
Binary file (358 Bytes). View file
 
models/__pycache__/backbone.cpython-310.pyc ADDED
Binary file (7.15 kB). View file
 
models/__pycache__/backbone.cpython-311.pyc ADDED
Binary file (8.13 kB). View file
 
models/__pycache__/backbone.cpython-312.pyc ADDED
Binary file (10.9 kB). View file
 
models/__pycache__/detr.cpython-310.pyc ADDED
Binary file (15.9 kB). View file
 
models/__pycache__/detr.cpython-311.pyc ADDED
Binary file (25 kB). View file
 
models/__pycache__/detr_seg.cpython-310.pyc ADDED
Binary file (21.4 kB). View file
 
models/__pycache__/detr_seg.cpython-312.pyc ADDED
Binary file (31.3 kB). View file
 
models/__pycache__/matcher.cpython-310.pyc ADDED
Binary file (4.4 kB). View file
 
models/__pycache__/matcher.cpython-311.pyc ADDED
Binary file (6.49 kB). View file
 
models/__pycache__/matcher.cpython-312.pyc ADDED
Binary file (5.47 kB). View file
 
models/__pycache__/position_encoding.cpython-310.pyc ADDED
Binary file (3.55 kB). View file
 
models/__pycache__/position_encoding.cpython-311.pyc ADDED
Binary file (6.69 kB). View file
 
models/__pycache__/position_encoding.cpython-312.pyc ADDED
Binary file (6.17 kB). View file
 
models/__pycache__/segmentation.cpython-310.pyc ADDED
Binary file (14.4 kB). View file
 
models/__pycache__/segmentation.cpython-311.pyc ADDED
Binary file (27.5 kB). View file
 
models/__pycache__/segmentation.cpython-312.pyc ADDED
Binary file (27.2 kB). View file
 
models/__pycache__/swin_transformer.cpython-310.pyc ADDED
Binary file (20.5 kB). View file
 
models/__pycache__/swin_transformer.cpython-312.pyc ADDED
Binary file (33.8 kB). View file
 
models/__pycache__/transformer.cpython-310.pyc ADDED
Binary file (9.28 kB). View file
 
models/__pycache__/transformer.cpython-311.pyc ADDED
Binary file (18.1 kB). View file
 
models/__pycache__/transformer.cpython-312.pyc ADDED
Binary file (15.9 kB). View file
 
models/backbone.py ADDED
@@ -0,0 +1,213 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ # Copyright (c) Facebook, Inc. and its affiliates. All Rights Reserved
2
+ """
3
+ Backbone modules.
4
+ """
5
+ from collections import OrderedDict
6
+
7
+ import os
8
+ import torch
9
+ import torch.nn.functional as F
10
+ import torchvision
11
+ from torch import nn
12
+ from torchvision.models._utils import IntermediateLayerGetter
13
+ from typing import Dict, List
14
+
15
+ from util.misc import NestedTensor, is_main_process, clean_state_dict
16
+
17
+ from .position_encoding import build_position_encoding
18
+ from segment_anything import sam_model_registry, SamAutomaticMaskGenerator, SamPredictor
19
+ from .swin_transformer import build_swin_transformer
20
+
21
+ class FrozenBatchNorm2d(torch.nn.Module):
22
+ """
23
+ BatchNorm2d where the batch statistics and the affine parameters are fixed.
24
+
25
+ Copy-paste from torchvision.misc.ops with added eps before rqsrt,
26
+ without which any other models than torchvision.models.resnet[18,34,50,101]
27
+ produce nans.
28
+ """
29
+
30
+ def __init__(self, n):
31
+ super(FrozenBatchNorm2d, self).__init__()
32
+ self.register_buffer("weight", torch.ones(n))
33
+ self.register_buffer("bias", torch.zeros(n))
34
+ self.register_buffer("running_mean", torch.zeros(n))
35
+ self.register_buffer("running_var", torch.ones(n))
36
+
37
+ def _load_from_state_dict(self, state_dict, prefix, local_metadata, strict,
38
+ missing_keys, unexpected_keys, error_msgs):
39
+ num_batches_tracked_key = prefix + 'num_batches_tracked'
40
+ if num_batches_tracked_key in state_dict:
41
+ del state_dict[num_batches_tracked_key]
42
+
43
+ super(FrozenBatchNorm2d, self)._load_from_state_dict(
44
+ state_dict, prefix, local_metadata, strict,
45
+ missing_keys, unexpected_keys, error_msgs)
46
+
47
+ def forward(self, x):
48
+ # move reshapes to the beginning
49
+ # to make it fuser-friendly
50
+ w = self.weight.reshape(1, -1, 1, 1)
51
+ b = self.bias.reshape(1, -1, 1, 1)
52
+ rv = self.running_var.reshape(1, -1, 1, 1)
53
+ rm = self.running_mean.reshape(1, -1, 1, 1)
54
+ eps = 1e-5
55
+ scale = w * (rv + eps).rsqrt()
56
+ bias = b - rm * scale
57
+ return x * scale + bias
58
+
59
+
60
+ class BackboneBase(nn.Module):
61
+
62
+ def __init__(self, backbone: nn.Module, train_backbone: bool, num_channels: int, return_interm_layers: bool):
63
+ super().__init__()
64
+ for name, parameter in backbone.named_parameters():
65
+ if not train_backbone or 'layer2' not in name and 'layer3' not in name and 'layer4' not in name:
66
+ parameter.requires_grad_(False)
67
+ # if return_interm_layers:
68
+ # return_layers = {"layer1": "0", "layer2": "1", "layer3": "2", "layer4": "3"}
69
+ # else:
70
+ # return_layers = {'layer4': "0"}
71
+
72
+ # swin
73
+ return_interm_indices = [1, 2, 3]
74
+ return_layers = {}
75
+ for idx, layer_index in enumerate(return_interm_indices):
76
+ return_layers.update({"layer{}".format(5 - len(return_interm_indices) + idx): "{}".format(layer_index)})
77
+
78
+ self.body = IntermediateLayerGetter(backbone, return_layers=return_layers)
79
+ self.num_channels = num_channels
80
+
81
+ def forward(self, tensor_list: NestedTensor):
82
+ xs = self.body(tensor_list.tensors)
83
+ # xs = OrderedDict()
84
+ # xs['0'] = self.sam_encoder(tensor_list.tensors)
85
+
86
+ out: Dict[str, NestedTensor] = {}
87
+ for name, x in xs.items():
88
+ m = tensor_list.mask
89
+ assert m is not None
90
+ mask = F.interpolate(m[None].float(), size=x.shape[-2:]).to(torch.bool)[0]
91
+ out[name] = NestedTensor(x, mask)
92
+ return out
93
+
94
+
95
+ class Backbone(BackboneBase):
96
+ """ResNet backbone with frozen BatchNorm."""
97
+ def __init__(self, name: str,
98
+ train_backbone: bool,
99
+ return_interm_layers: bool,
100
+ dilation: bool):
101
+ if name in ['resnet18', 'resnet34', 'resnet50', 'resnet101']:
102
+ backbone = getattr(torchvision.models, name)(
103
+ replace_stride_with_dilation=[False, False, dilation],
104
+ pretrained=is_main_process(), norm_layer=FrozenBatchNorm2d)
105
+ num_channels = 512 if name in ('resnet18', 'resnet34') else 2048
106
+
107
+ super().__init__(backbone, train_backbone, num_channels, return_interm_layers)
108
+
109
+
110
+ class Joiner(nn.Sequential):
111
+ def __init__(self, backbone, position_embedding):
112
+ super().__init__(backbone, position_embedding)
113
+
114
+ def forward(self, tensor_list: NestedTensor):
115
+ xs = self[0](tensor_list)
116
+ out: List[NestedTensor] = []
117
+ pos = []
118
+ for name, x in xs.items():
119
+ out.append(x)
120
+ # position encoding
121
+ pos.append(self[1](x).to(x.tensors.dtype))
122
+
123
+ return out, pos
124
+
125
+
126
+ # def build_backbone(args):
127
+ # position_embedding = build_position_encoding(args)
128
+
129
+ # # sam = sam_model_registry["vit_b"](checkpoint="sam_vit_b_01ec64.pth")
130
+ # # position_embedding = sam.prompt_encoder.get_dense_pe() # (bs, 256, 64, 64)
131
+
132
+ # train_backbone = args.lr_backbone > 0
133
+ # return_interm_layers = args.masks
134
+ # backbone = Backbone(args.backbone, train_backbone, return_interm_layers, args.dilation)
135
+ # model = Joiner(backbone, position_embedding)
136
+ # model.num_channels = backbone.num_channels
137
+ # return model
138
+
139
+ def build_backbone(args):
140
+ """
141
+ Useful args:
142
+ - backbone: backbone name
143
+ - lr_backbone:
144
+ - dilation
145
+ - return_interm_indices: available: [0,1,2,3], [1,2,3], [3]
146
+ - backbone_freeze_keywords:
147
+ - use_checkpoint: for swin only for now
148
+
149
+ """
150
+ backbone_freeze_keywords = None
151
+ use_checkpoint = True
152
+ position_embedding = build_position_encoding(args)
153
+ train_backbone = args.lr_backbone > 0
154
+ if not train_backbone:
155
+ raise ValueError("Please set lr_backbone > 0")
156
+ return_interm_indices = [1, 2, 3]
157
+ assert return_interm_indices in [[0,1,2,3], [1,2,3], [3]]
158
+
159
+
160
+ if args.backbone in ['resnet50', 'resnet101']:
161
+ backbone = Backbone(args.backbone, train_backbone, args.dilation,
162
+ return_interm_indices,
163
+ batch_norm=FrozenBatchNorm2d)
164
+ bb_num_channels = backbone.num_channels
165
+ elif args.backbone in ['swin_T_224_1k', 'swin_B_224_22k', 'swin_B_384_22k', 'swin_L_224_22k', 'swin_L_384_22k']:
166
+ pretrain_img_size = int(args.backbone.split('_')[-2])
167
+ backbone = build_swin_transformer(args.backbone, \
168
+ pretrain_img_size=pretrain_img_size, \
169
+ out_indices=tuple(return_interm_indices), \
170
+ dilation=args.dilation, use_checkpoint=use_checkpoint)
171
+
172
+ # freeze some layers
173
+ if backbone_freeze_keywords is not None:
174
+ for name, parameter in backbone.named_parameters():
175
+ for keyword in backbone_freeze_keywords:
176
+ if keyword in name:
177
+ parameter.requires_grad_(False)
178
+ break
179
+ if "backbone_dir" in args:
180
+ pretrained_dir = args.backbone_dir
181
+ PTDICT = {
182
+ 'swin_T_224_1k': 'swin_tiny_patch4_window7_224.pth',
183
+ 'swin_B_224_22k': 'swin_base_patch4_window7_224_22kto1k.pth',
184
+ 'swin_B_384_22k': 'swin_base_patch4_window12_384.pth',
185
+ 'swin_L_384_22k': 'swin_large_patch4_window12_384_22k.pth',
186
+ }
187
+ pretrainedpath = os.path.join(pretrained_dir, PTDICT[args.backbone])
188
+ checkpoint = torch.load(pretrainedpath, map_location='cpu')['model']
189
+ from collections import OrderedDict
190
+ def key_select_function(keyname):
191
+ if 'head' in keyname:
192
+ return False
193
+ if args.dilation and 'layers.3' in keyname:
194
+ return False
195
+ return True
196
+ _tmp_st = OrderedDict({k:v for k, v in clean_state_dict(checkpoint).items() if key_select_function(k)})
197
+ _tmp_st_output = backbone.load_state_dict(_tmp_st, strict=False)
198
+ print(str(_tmp_st_output))
199
+ bb_num_channels = backbone.num_features[4 - len(return_interm_indices):]
200
+ # elif args.backbone in ['convnext_xlarge_22k']:
201
+ # backbone = build_convnext(modelname=args.backbone, pretrained=True, out_indices=tuple(return_interm_indices),backbone_dir=args.backbone_dir)
202
+ # bb_num_channels = backbone.dims[4 - len(return_interm_indices):]
203
+ else:
204
+ raise NotImplementedError("Unknown backbone {}".format(args.backbone))
205
+
206
+
207
+ assert len(bb_num_channels) == len(return_interm_indices), f"len(bb_num_channels) {len(bb_num_channels)} != len(return_interm_indices) {len(return_interm_indices)}"
208
+
209
+
210
+ model = Joiner(backbone, position_embedding)
211
+ model.num_channels = bb_num_channels
212
+ assert isinstance(bb_num_channels, List), "bb_num_channels is expected to be a List but {}".format(type(bb_num_channels))
213
+ return model
models/detr.py ADDED
@@ -0,0 +1,407 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ # Copyright (c) Facebook, Inc. and its affiliates. All Rights Reserved
2
+ """
3
+ DETR model and criterion classes.
4
+ """
5
+ import torch
6
+ import torch.nn.functional as F
7
+ from torch import nn
8
+
9
+ from util import box_ops
10
+ from util.misc import (NestedTensor, nested_tensor_from_tensor_list,
11
+ accuracy, get_world_size, interpolate,
12
+ is_dist_avail_and_initialized)
13
+
14
+ from .backbone import build_backbone
15
+ from .matcher import build_matcher
16
+ from .segmentation import (DETRsegm, PostProcessPanoptic, PostProcessSegm,
17
+ dice_loss, sigmoid_focal_loss)
18
+ from .transformer import build_transformer
19
+
20
+
21
+ class DETR(nn.Module):
22
+ """ This is the DETR module that performs object detection """
23
+ def __init__(self, backbone, transformer, num_classes, num_queries, aux_loss=False):
24
+ """ Initializes the model.
25
+ Parameters:
26
+ backbone: torch module of the backbone to be used. See backbone.py
27
+ transformer: torch module of the transformer architecture. See transformer.py
28
+ num_classes: number of object classes
29
+ num_queries: number of object queries, ie detection slot. This is the maximal number of objects
30
+ DETR can detect in a single image. For COCO, we recommend 100 queries.
31
+ aux_loss: True if auxiliary decoding losses (loss at each decoder layer) are to be used.
32
+ """
33
+ super().__init__()
34
+ self.num_queries = num_queries
35
+ self.transformer = transformer
36
+ hidden_dim = transformer.d_model # =args.hidden_dim 256
37
+ self.class_embed = nn.Linear(hidden_dim, num_classes + 1)
38
+ self.bbox_embed = MLP(hidden_dim, hidden_dim, 4, 3)
39
+ self.query_embed = nn.Embedding(num_queries, hidden_dim)
40
+ # self.input_proj = nn.ModuleList([
41
+ # nn.Sequential(
42
+ # nn.Conv2d(backbone.num_channels[-1], hidden_dim, kernel_size=1),
43
+ # nn.GroupNorm(32, hidden_dim),
44
+ # )])
45
+ self.input_proj = nn.Conv2d(backbone.num_channels[-1], hidden_dim, kernel_size=1)
46
+ # self.input_proj = nn.Conv2d(256, hidden_dim, kernel_size=1)
47
+ self.backbone = backbone
48
+ self.aux_loss = aux_loss
49
+
50
+ def forward(self, samples: NestedTensor):
51
+ """ The forward expects a NestedTensor, which consists of:
52
+ - samples.tensor: batched images, of shape [batch_size x 3 x H x W]
53
+ - samples.mask: a binary mask of shape [batch_size x H x W], containing 1 on padded pixels
54
+
55
+ It returns a dict with the following elements:
56
+ - "pred_logits": the classification logits (including no-object) for all queries.
57
+ Shape= [batch_size x num_queries x (num_classes + 1)]
58
+ - "pred_boxes": The normalized boxes coordinates for all queries, represented as
59
+ (center_x, center_y, height, width). These values are normalized in [0, 1],
60
+ relative to the size of each individual image (disregarding possible padding).
61
+ See PostProcess for information on how to retrieve the unnormalized bounding box.
62
+ - "aux_outputs": Optional, only returned when auxilary losses are activated. It is a list of
63
+ dictionnaries containing the two above keys for each decoder layer.
64
+ """
65
+ if isinstance(samples, (list, torch.Tensor)):
66
+ samples = nested_tensor_from_tensor_list(samples)
67
+ features, pos = self.backbone(samples)
68
+ # print('features:', features[0].tensors.shape)
69
+ # print('pos:', pos[0].shape)
70
+ src, mask = features[-1].decompose()
71
+ # print('src shape:', src.shape, mask.shape)
72
+ assert mask is not None
73
+
74
+ hs = self.transformer(self.input_proj(src), mask, self.query_embed.weight, pos[-1])[0]
75
+
76
+ outputs_class = self.class_embed(hs)
77
+ outputs_coord = self.bbox_embed(hs).sigmoid()
78
+ out = {'pred_logits': outputs_class[-1], 'pred_boxes': outputs_coord[-1]}
79
+ if self.aux_loss:
80
+ out['aux_outputs'] = self._set_aux_loss(outputs_class, outputs_coord)
81
+ return out
82
+
83
+ @torch.jit.unused
84
+ def _set_aux_loss(self, outputs_class, outputs_coord):
85
+ # this is a workaround to make torchscript happy, as torchscript
86
+ # doesn't support dictionary with non-homogeneous values, such
87
+ # as a dict having both a Tensor and a list.
88
+ return [{'pred_logits': a, 'pred_boxes': b}
89
+ for a, b in zip(outputs_class[:-1], outputs_coord[:-1])]
90
+
91
+
92
+ class SetCriterion(nn.Module):
93
+ """ This class computes the loss for DETR.
94
+ The process happens in two steps:
95
+ 1) we compute hungarian assignment between ground truth boxes and the outputs of the model
96
+ 2) we supervise each pair of matched ground-truth / prediction (supervise class and box)
97
+ """
98
+ def __init__(self, num_classes, matcher, weight_dict, eos_coef, losses):
99
+ """ Create the criterion.
100
+ Parameters:
101
+ num_classes: number of object categories, omitting the special no-object category
102
+ matcher: module able to compute a matching between targets and proposals
103
+ weight_dict: dict containing as key the names of the losses and as values their relative weight.
104
+ eos_coef: relative classification weight applied to the no-object category
105
+ losses: list of all the losses to be applied. See get_loss for list of available losses.
106
+ """
107
+ super().__init__()
108
+ self.num_classes = num_classes
109
+ self.matcher = matcher
110
+ self.weight_dict = weight_dict
111
+ self.eos_coef = eos_coef
112
+ self.losses = losses
113
+ empty_weight = torch.ones(self.num_classes + 1)
114
+ empty_weight[-1] = self.eos_coef
115
+ self.register_buffer('empty_weight', empty_weight)
116
+
117
+ def loss_labels(self, outputs, targets, indices, num_boxes, log=True):
118
+ """Classification loss (NLL)
119
+ targets dicts must contain the key "labels" containing a tensor of dim [nb_target_boxes]
120
+ """
121
+ assert 'pred_logits' in outputs
122
+ src_logits = outputs['pred_logits']
123
+
124
+ idx = self._get_src_permutation_idx(indices)
125
+ target_classes_o = torch.cat([t["labels"][J] for t, (_, J) in zip(targets, indices)])
126
+ target_classes = torch.full(src_logits.shape[:2], self.num_classes,
127
+ dtype=torch.int64, device=src_logits.device)
128
+ target_classes[idx] = target_classes_o
129
+
130
+ target_classes_onehot = torch.zeros([src_logits.shape[0], src_logits.shape[1], src_logits.shape[2]+1],
131
+ dtype=src_logits.dtype, layout=src_logits.layout, device=src_logits.device)
132
+ target_classes_onehot.scatter_(2, target_classes.unsqueeze(-1), 1)
133
+ target_classes_onehot = target_classes_onehot[:,:,:-1]
134
+ loss_ce = sigmoid_focal_loss(src_logits, target_classes_onehot, num_boxes, alpha=0.25, gamma=2) * src_logits.shape[1]
135
+
136
+ # loss_ce = F.cross_entropy(src_logits.transpose(1, 2), target_classes, self.empty_weight)
137
+ losses = {'loss_ce': loss_ce}
138
+
139
+ if log:
140
+ # TODO this should probably be a separate loss, not hacked in this one here
141
+ losses['class_error'] = 100 - accuracy(src_logits[idx], target_classes_o)[0]
142
+ return losses
143
+
144
+ @torch.no_grad()
145
+ def loss_cardinality(self, outputs, targets, indices, num_boxes):
146
+ """ Compute the cardinality error, ie the absolute error in the number of predicted non-empty boxes
147
+ This is not really a loss, it is intended for logging purposes only. It doesn't propagate gradients
148
+ """
149
+ pred_logits = outputs['pred_logits']
150
+ device = pred_logits.device
151
+ tgt_lengths = torch.as_tensor([len(v["labels"]) for v in targets], device=device)
152
+ # Count the number of predictions that are NOT "no-object" (which is the last class)
153
+ card_pred = (pred_logits.argmax(-1) != pred_logits.shape[-1] - 1).sum(1)
154
+ card_err = F.l1_loss(card_pred.float(), tgt_lengths.float())
155
+ losses = {'cardinality_error': card_err}
156
+ return losses
157
+
158
+ def loss_boxes(self, outputs, targets, indices, num_boxes):
159
+ """Compute the losses related to the bounding boxes, the L1 regression loss and the GIoU loss
160
+ targets dicts must contain the key "boxes" containing a tensor of dim [nb_target_boxes, 4]
161
+ The target boxes are expected in format (center_x, center_y, w, h), normalized by the image size.
162
+ """
163
+ assert 'pred_boxes' in outputs
164
+ idx = self._get_src_permutation_idx(indices)
165
+ src_boxes = outputs['pred_boxes'][idx]
166
+ target_boxes = torch.cat([t['boxes'][i] for t, (_, i) in zip(targets, indices)], dim=0)
167
+
168
+ loss_bbox = F.l1_loss(src_boxes, target_boxes, reduction='none')
169
+
170
+ losses = {}
171
+ losses['loss_bbox'] = loss_bbox.sum() / num_boxes
172
+
173
+ loss_giou = 1 - torch.diag(box_ops.generalized_box_iou(
174
+ box_ops.box_cxcywh_to_xyxy(src_boxes),
175
+ box_ops.box_cxcywh_to_xyxy(target_boxes)))
176
+ losses['loss_giou'] = loss_giou.sum() / num_boxes
177
+ return losses
178
+
179
+ def loss_masks(self, outputs, targets, indices, num_boxes):
180
+ """Compute the losses related to the masks: the focal loss and the dice loss.
181
+ targets dicts must contain the key "masks" containing a tensor of dim [nb_target_boxes, h, w]
182
+ """
183
+ assert "pred_masks" in outputs
184
+
185
+ src_idx = self._get_src_permutation_idx(indices)
186
+ tgt_idx = self._get_tgt_permutation_idx(indices)
187
+ src_masks = outputs["pred_masks"]
188
+ src_masks = src_masks[src_idx]
189
+ masks = [t["masks"] for t in targets]
190
+ # TODO use valid to mask invalid areas due to padding in loss
191
+ target_masks, valid = nested_tensor_from_tensor_list(masks).decompose()
192
+ target_masks = target_masks.to(src_masks)
193
+ target_masks = target_masks[tgt_idx]
194
+
195
+ # upsample predictions to the target size
196
+ src_masks = interpolate(src_masks[:, None], size=target_masks.shape[-2:],
197
+ mode="bilinear", align_corners=False)
198
+ src_masks = src_masks[:, 0].flatten(1)
199
+
200
+ target_masks = target_masks.flatten(1)
201
+ target_masks = target_masks.view(src_masks.shape)
202
+ losses = {
203
+ "loss_mask": sigmoid_focal_loss(src_masks, target_masks, num_boxes),
204
+ "loss_dice": dice_loss(src_masks, target_masks, num_boxes),
205
+ }
206
+ return losses
207
+
208
+ def _get_src_permutation_idx(self, indices):
209
+ # permute predictions following indices
210
+ batch_idx = torch.cat([torch.full_like(src, i) for i, (src, _) in enumerate(indices)])
211
+ src_idx = torch.cat([src for (src, _) in indices])
212
+ return batch_idx, src_idx
213
+
214
+ def _get_tgt_permutation_idx(self, indices):
215
+ # permute targets following indices
216
+ batch_idx = torch.cat([torch.full_like(tgt, i) for i, (_, tgt) in enumerate(indices)])
217
+ tgt_idx = torch.cat([tgt for (_, tgt) in indices])
218
+ return batch_idx, tgt_idx
219
+
220
+ def get_loss(self, loss, outputs, targets, indices, num_boxes, **kwargs):
221
+ loss_map = {
222
+ 'labels': self.loss_labels,
223
+ 'cardinality': self.loss_cardinality,
224
+ 'boxes': self.loss_boxes,
225
+ 'masks': self.loss_masks
226
+ }
227
+ assert loss in loss_map, f'do you really want to compute {loss} loss?'
228
+ return loss_map[loss](outputs, targets, indices, num_boxes, **kwargs)
229
+
230
+ def forward(self, outputs, targets):
231
+ """ This performs the loss computation.
232
+ Parameters:
233
+ outputs: dict of tensors, see the output specification of the model for the format
234
+ targets: list of dicts, such that len(targets) == batch_size.
235
+ The expected keys in each dict depends on the losses applied, see each loss' doc
236
+ """
237
+ outputs_without_aux = {k: v for k, v in outputs.items() if k != 'aux_outputs'}
238
+
239
+ # Retrieve the matching between the outputs of the last layer and the targets
240
+ indices = self.matcher(outputs_without_aux, targets)
241
+
242
+ # Compute the average number of target boxes accross all nodes, for normalization purposes
243
+ num_boxes = sum(len(t["labels"]) for t in targets)
244
+ num_boxes = torch.as_tensor([num_boxes], dtype=torch.float, device=next(iter(outputs.values())).device)
245
+ if is_dist_avail_and_initialized():
246
+ torch.distributed.all_reduce(num_boxes)
247
+ num_boxes = torch.clamp(num_boxes / get_world_size(), min=1).item()
248
+
249
+ # Compute all the requested losses
250
+ losses = {}
251
+ for loss in self.losses:
252
+ losses.update(self.get_loss(loss, outputs, targets, indices, num_boxes))
253
+
254
+ # In case of auxiliary losses, we repeat this process with the output of each intermediate layer.
255
+ if 'aux_outputs' in outputs:
256
+ for i, aux_outputs in enumerate(outputs['aux_outputs']):
257
+ indices = self.matcher(aux_outputs, targets)
258
+ for loss in self.losses:
259
+ if loss == 'masks':
260
+ # Intermediate masks losses are too costly to compute, we ignore them.
261
+ continue
262
+ kwargs = {}
263
+ if loss == 'labels':
264
+ # Logging is enabled only for the last layer
265
+ kwargs = {'log': False}
266
+ l_dict = self.get_loss(loss, aux_outputs, targets, indices, num_boxes, **kwargs)
267
+ l_dict = {k + f'_{i}': v for k, v in l_dict.items()}
268
+ losses.update(l_dict)
269
+
270
+ return losses
271
+
272
+
273
+ class PostProcess(nn.Module):
274
+ """ This module converts the model's output into the format expected by the coco api"""
275
+ @torch.no_grad()
276
+ def forward(self, outputs, target_sizes):
277
+ """ Perform the computation
278
+ Parameters:
279
+ outputs: raw outputs of the model
280
+ target_sizes: tensor of dimension [batch_size x 2] containing the size of each images of the batch
281
+ For evaluation, this must be the original image size (before any data augmentation)
282
+ For visualization, this should be the image size after data augment, but before padding
283
+ """
284
+ out_logits, out_bbox = outputs['pred_logits'], outputs['pred_boxes']
285
+
286
+ assert len(out_logits) == len(target_sizes)
287
+ assert target_sizes.shape[1] == 2
288
+
289
+ prob = F.softmax(out_logits, -1)
290
+ scores, labels = prob[..., :-1].max(-1)
291
+
292
+ # convert to [x0, y0, x1, y1] format
293
+ boxes = box_ops.box_cxcywh_to_xyxy(out_bbox)
294
+ # and from relative [0, 1] to absolute [0, height] coordinates
295
+ img_h, img_w = target_sizes.unbind(1)
296
+ scale_fct = torch.stack([img_w, img_h, img_w, img_h], dim=1)
297
+ boxes = boxes * scale_fct[:, None, :]
298
+
299
+ # print('Originial output:')
300
+ # print('Labels:', labels, 'bbox:', boxes)
301
+
302
+ results = [{'scores': s, 'labels': l, 'boxes': b} for s, l, b in zip(scores, labels, boxes)]
303
+
304
+ return results
305
+
306
+
307
+ class MLP(nn.Module):
308
+ """ Very simple multi-layer perceptron (also called FFN)"""
309
+
310
+ def __init__(self, input_dim, hidden_dim, output_dim, num_layers):
311
+ super().__init__()
312
+ self.num_layers = num_layers
313
+ h = [hidden_dim] * (num_layers - 1)
314
+ self.layers = nn.ModuleList(nn.Linear(n, k) for n, k in zip([input_dim] + h, h + [output_dim]))
315
+
316
+ def forward(self, x):
317
+ for i, layer in enumerate(self.layers):
318
+ x = F.relu(layer(x)) if i < self.num_layers - 1 else layer(x)
319
+ return x
320
+
321
+
322
+ def build(args):
323
+ # the `num_classes` naming here is somewhat misleading.
324
+ # it indeed corresponds to `max_obj_id + 1`, where max_obj_id
325
+ # is the maximum id for a class in your dataset. For example,
326
+ # COCO has a max_obj_id of 90, so we pass `num_classes` to be 91.
327
+ # As another example, for a dataset that has a single class with id 1,
328
+ # you should pass `num_classes` to be 2 (max_obj_id + 1).
329
+ # For more details on this, check the following discussion
330
+ # https://github.com/facebookresearch/detr/issues/108#issuecomment-650269223
331
+ num_classes = 8 if args.dataset_file == 'endovis17' else 91
332
+ if args.dataset_file == "coco_panoptic":
333
+ # for panoptic, we just add a num_classes that is large enough to hold
334
+ # max_obj_id + 1, but the exact value doesn't really matter
335
+ num_classes = 250
336
+ device = torch.device(args.device)
337
+
338
+ backbone = build_backbone(args)
339
+
340
+ transformer = build_transformer(args)
341
+ transformer.eval()
342
+ for param in transformer.parameters():
343
+ param.requires_grad = False
344
+
345
+ if args.model:
346
+ # pretrained_model = torch.hub.load('facebookresearch/detr', 'detr_resnet50', pretrained=True)
347
+ # # save model weights
348
+ # torch.save(pretrained_model.state_dict(), 'detr_weights.pth')
349
+
350
+ # initialize model weights
351
+ model = DETR(
352
+ backbone,
353
+ transformer,
354
+ num_classes=num_classes,
355
+ num_queries=args.num_queries,
356
+ aux_loss=args.aux_loss,
357
+ )
358
+
359
+ weights = torch.load('detr_weights.pth')
360
+ # checkpoint = torch.load('checkpoint0040.pth', map_location='cpu')
361
+ # weights = checkpoint['model']
362
+ # delete specific layers in weights
363
+ exclude_keys = ['class_embed.weight', 'class_embed.bias', 'input_proj.weight']
364
+ for key in exclude_keys:
365
+ del weights[key]
366
+
367
+ model.load_state_dict(weights, strict=False)
368
+
369
+ else:
370
+ model = DETR(
371
+ backbone,
372
+ transformer,
373
+ num_classes=num_classes,
374
+ num_queries=args.num_queries,
375
+ aux_loss=args.aux_loss,
376
+ )
377
+
378
+
379
+ if args.masks:
380
+ model = DETRsegm(model, freeze_detr=(args.frozen_weights is not None))
381
+ matcher = build_matcher(args)
382
+ weight_dict = {'loss_ce': 1, 'loss_bbox': args.bbox_loss_coef}
383
+ weight_dict['loss_giou'] = args.giou_loss_coef
384
+ if args.masks:
385
+ weight_dict["loss_mask"] = args.mask_loss_coef
386
+ weight_dict["loss_dice"] = args.dice_loss_coef
387
+ # TODO this is a hack
388
+ if args.aux_loss:
389
+ aux_weight_dict = {}
390
+ for i in range(args.dec_layers - 1):
391
+ aux_weight_dict.update({k + f'_{i}': v for k, v in weight_dict.items()})
392
+ weight_dict.update(aux_weight_dict)
393
+
394
+ losses = ['labels', 'boxes', 'cardinality']
395
+ if args.masks:
396
+ losses += ["masks"]
397
+ criterion = SetCriterion(num_classes, matcher=matcher, weight_dict=weight_dict,
398
+ eos_coef=args.eos_coef, losses=losses)
399
+ criterion.to(device)
400
+ postprocessors = {'bbox': PostProcess()}
401
+ if args.masks:
402
+ postprocessors['segm'] = PostProcessSegm()
403
+ if args.dataset_file == "coco_panoptic":
404
+ is_thing_map = {i: i <= 90 for i in range(201)}
405
+ postprocessors["panoptic"] = PostProcessPanoptic(is_thing_map, threshold=0.85)
406
+
407
+ return model, criterion, postprocessors
models/detr_seg.py ADDED
@@ -0,0 +1,616 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ # Copyright (c) Facebook, Inc. and its affiliates. All Rights Reserved
2
+ """
3
+ DETR model and criterion classes.
4
+ """
5
+ import torch
6
+ import torch.nn.functional as F
7
+ from torch import nn
8
+
9
+ from util import box_ops
10
+ from util.misc import (NestedTensor, nested_tensor_from_tensor_list,
11
+ accuracy, get_world_size, interpolate,
12
+ is_dist_avail_and_initialized)
13
+
14
+ from .backbone import build_backbone
15
+ from .matcher import build_matcher
16
+ from .segmentation import (DETRsegm, PostProcessPanoptic, PostProcessSegm,
17
+ dice_loss, sigmoid_focal_loss, dice_coefficient, focal_loss_masks)
18
+ from .transformer import build_transformer
19
+ from models.sam.segment_anything.modeling import ImageEncoderViT, PromptEncoder, MaskDecoder, TwoWayTransformer
20
+ from segment_anything import sam_model_registry, SamPredictor
21
+
22
+ from torch.nn import functional as FN
23
+ from torch import nn
24
+
25
+ import torch.distributions as dist
26
+ import numpy as np
27
+ import monai
28
+
29
+ def add_noise_to_bbox(bbox, max_noise=20):
30
+ '''
31
+ args: bbox (N, 4)
32
+ '''
33
+ # Calculate standard deviation as 10% of the box sidelength
34
+ box_width = bbox[:, 2] - bbox[:, 0]
35
+ box_height = bbox[:, 3] - bbox[:, 1]
36
+ std_dev = 0.1 * torch.max(box_width, box_height)
37
+
38
+ # Create normal distribution for generating noise
39
+ noise_dist = dist.Normal(0, std_dev) # (num_boxes, )
40
+ num_boxes = bbox.shape[0]
41
+
42
+ # Generate random noise for each coordinate
43
+ x1_noise = noise_dist.sample()
44
+ y1_noise = noise_dist.sample()
45
+ x2_noise = noise_dist.sample()
46
+ y2_noise = noise_dist.sample()
47
+
48
+ # Clip noise to a maximum of 20 pixels
49
+ x1_noise = torch.clamp(x1_noise, -max_noise, max_noise)
50
+ y1_noise = torch.clamp(y1_noise, -max_noise, max_noise)
51
+ x2_noise = torch.clamp(x2_noise, -max_noise, max_noise)
52
+ y2_noise = torch.clamp(y2_noise, -max_noise, max_noise)
53
+ noise = torch.stack([x1_noise, y1_noise, x2_noise, y2_noise], dim=1)
54
+
55
+ # Add noise to the original coordinates
56
+ noisy_bbox = bbox + noise
57
+
58
+ return noisy_bbox
59
+
60
+ def box_cxcywh_to_xyxy(x):
61
+ x_c, y_c, w, h = x.unbind(1)
62
+ b = [(x_c - 0.5 * w), (y_c - 0.5 * h),
63
+ (x_c + 0.5 * w), (y_c + 0.5 * h)]
64
+ return torch.stack(b, dim=1)
65
+
66
+ def rescale_bboxes(out_bbox, size):
67
+ img_w, img_h = size
68
+ b = box_cxcywh_to_xyxy(out_bbox.cpu())
69
+ b = b * torch.tensor([img_w, img_h, img_w, img_h], dtype=torch.float32)
70
+ return b
71
+
72
+ def postprocess_masks(masks, input_size, original_size,) -> torch.Tensor:
73
+ masks = FN.interpolate(
74
+ masks,
75
+ input_size,
76
+ mode="bilinear",
77
+ align_corners=False,
78
+ )
79
+ masks = masks[..., :input_size[0], :input_size[1]]
80
+ masks = FN.interpolate(masks, original_size, mode="bilinear", align_corners=False)
81
+ return masks
82
+
83
+ class SAMModel(nn.Module):
84
+ def __init__(self, device, model_type='vit_b', ckpt_path='sam_vit_b_01ec64.pth'):
85
+ super().__init__()
86
+
87
+ sam = sam_model_registry[model_type](checkpoint=ckpt_path).to(device)
88
+ self.predictor = SamPredictor(sam)
89
+
90
+ self.sam_image_encoder = sam.image_encoder
91
+ self.sam_prompt_encoder = sam.prompt_encoder
92
+ self.sam_mask_decoder = sam.mask_decoder
93
+ self.device = device
94
+ self.upsample_layer = nn.ConvTranspose2d(
95
+ in_channels=256, # Number of input channels (should match your input image)
96
+ out_channels=256, # Number of output channels (same as input channels for no change)
97
+ kernel_size=4, # Kernel size for the convolution
98
+ stride=2, # Upsampling factor (doubles the spatial dimensions)
99
+ padding=1, # Padding to maintain spatial dimensions
100
+ output_padding=0, # Additional padding to adjust the output size
101
+ )
102
+
103
+ def forward(self, batched_img, boxes, image_embeddings=None, sizes=(1024, 1024), add_noise=True):
104
+ if image_embeddings is None:
105
+ image_embeddings = self.sam_image_encoder(batched_img)[0].unsqueeze(0)
106
+ else:
107
+ image_embeddings = self.upsample_layer(image_embeddings) # (3, 32, 32)-> (3, 64, 64)
108
+ # print(image_embeddings.shape)
109
+
110
+ gt_boxes = rescale_bboxes(boxes, sizes) # xyxy-format with shape (N, 4)
111
+ if add_noise:
112
+ noisy_boxes = add_noise_to_bbox(gt_boxes)
113
+ else:
114
+ noisy_boxes = gt_boxes
115
+
116
+ transformed_boxes = self.predictor.transform.apply_boxes_torch(noisy_boxes, sizes).to(self.device)
117
+ if gt_boxes.shape[0] == 0:
118
+ transformed_boxes = None
119
+ sparse_embeddings, dense_embeddings = self.sam_prompt_encoder(points=None,
120
+ boxes=transformed_boxes,
121
+ masks=None)
122
+ # print(gt_boxes.shape, transformed_boxes)
123
+ # print(image_embeddings.shape, self.sam_prompt_encoder.get_dense_pe().shape)
124
+ # print(sparse_embeddings.shape, dense_embeddings.shape)
125
+ low_res_masks, iou_predictions = self.sam_mask_decoder(
126
+ image_embeddings=image_embeddings,
127
+ image_pe=self.sam_prompt_encoder.get_dense_pe(),
128
+ sparse_prompt_embeddings=sparse_embeddings,
129
+ dense_prompt_embeddings=dense_embeddings,
130
+ multimask_output=False,
131
+ # hq_token_only=False,
132
+ # interm_embeddings=False
133
+ )
134
+ pred_masks = postprocess_masks(low_res_masks, input_size=sizes, original_size=sizes)
135
+ return low_res_masks.reshape(-1, 256, 256), pred_masks.reshape(-1, sizes[0], sizes[1]), iou_predictions
136
+
137
+ class CustomSAMModel(nn.Module):
138
+ def __init__(self, device, img_size=224, prompt_embed_dim=256, image_embedding_size=(14, 14), input_image_size=(224, 224)):
139
+ super().__init__()
140
+ self.device = device
141
+ self.sam_image_encoder = ImageEncoderViT(img_size=img_size)
142
+ self.sam_prompt_encoder = PromptEncoder(embed_dim=prompt_embed_dim,
143
+ image_embedding_size=image_embedding_size,
144
+ input_image_size=input_image_size,
145
+ mask_in_chans=16
146
+ )
147
+ self.sam_mask_decoder = MaskDecoder(transformer_dim=256,
148
+ transformer=TwoWayTransformer(depth=2,
149
+ embedding_dim=prompt_embed_dim,
150
+ mlp_dim=2048,
151
+ num_heads=8))
152
+
153
+ def forward(self, batched_img, image_embeddings, boxes, sizes, predictor, add_noise=True):
154
+ image_embeddings = self.sam_image_encoder(batched_img)
155
+
156
+ gt_boxes = rescale_bboxes(boxes, sizes) # xyxy-format
157
+ if add_noise:
158
+ noisy_boxes = add_noise_to_bbox(gt_boxes)
159
+ else:
160
+ noisy_boxes = gt_boxes
161
+
162
+ transformed_boxes = predictor.transform.apply_boxes_torch(noisy_boxes, (224, 224)).to(self.device)
163
+ if gt_boxes.shape[0] == 0:
164
+ transformed_boxes = None
165
+ sparse_embeddings, dense_embeddings = self.sam_prompt_encoder(points=None,
166
+ boxes=transformed_boxes,
167
+ masks=None)
168
+ # print(gt_boxes.shape, transformed_boxes)
169
+ # print(image_embeddings.shape, self.sam_prompt_encoder.get_dense_pe().shape)
170
+ # print(sparse_embeddings.shape, dense_embeddings.shape)
171
+ low_res_masks, iou_predictions = self.sam_mask_decoder(
172
+ image_embeddings=image_embeddings,
173
+ image_pe=self.sam_prompt_encoder.get_dense_pe(),
174
+ sparse_prompt_embeddings=sparse_embeddings,
175
+ dense_prompt_embeddings=dense_embeddings,
176
+ multimask_output=False,
177
+ )
178
+ pred_masks = postprocess_masks(low_res_masks, input_size=(224, 224), original_size=(224, 224))
179
+ return low_res_masks.reshape(-1, 56, 56), pred_masks.reshape(-1, 224, 224), iou_predictions
180
+
181
+ class DETR(nn.Module):
182
+ """ This is the DETR module that performs object detection """
183
+ def __init__(self, backbone, transformer, num_classes, num_queries, aux_loss=False):
184
+ """ Initializes the model.
185
+ Parameters:
186
+ backbone: torch module of the backbone to be used. See backbone.py
187
+ transformer: torch module of the transformer architecture. See transformer.py
188
+ num_classes: number of object classes
189
+ num_queries: number of object queries, ie detection slot. This is the maximal number of objects
190
+ DETR can detect in a single image. For COCO, we recommend 100 queries.
191
+ aux_loss: True if auxiliary decoding losses (loss at each decoder layer) are to be used.
192
+ """
193
+ super().__init__()
194
+ self.num_queries = num_queries
195
+ self.transformer = transformer
196
+ hidden_dim = transformer.d_model # =args.hidden_dim 256
197
+ self.class_embed = nn.Linear(hidden_dim, num_classes + 1)
198
+ self.bbox_embed = MLP(hidden_dim, hidden_dim, 4, 3)
199
+ self.query_embed = nn.Embedding(num_queries, hidden_dim)
200
+ # self.input_proj = nn.ModuleList([
201
+ # nn.Sequential(
202
+ # nn.Conv2d(backbone.num_channels[-1], hidden_dim, kernel_size=1),
203
+ # nn.GroupNorm(32, hidden_dim),
204
+ # )])
205
+ self.input_proj = nn.Conv2d(backbone.num_channels[-1], hidden_dim, kernel_size=1)
206
+ # self.input_proj = nn.Conv2d(256, hidden_dim, kernel_size=1)
207
+ self.backbone = backbone
208
+ self.aux_loss = aux_loss
209
+
210
+ def forward(self, samples: NestedTensor):
211
+ """ The forward expects a NestedTensor, which consists of:
212
+ - samples.tensor: batched images, of shape [batch_size x 3 x H x W]
213
+ - samples.mask: a binary mask of shape [batch_size x H x W], containing 1 on padded pixels
214
+
215
+ It returns a dict with the following elements:
216
+ - "pred_logits": the classification logits (including no-object) for all queries.
217
+ Shape= [batch_size x num_queries x (num_classes + 1)]
218
+ - "pred_boxes": The normalized boxes coordinates for all queries, represented as
219
+ (center_x, center_y, height, width). These values are normalized in [0, 1],
220
+ relative to the size of each individual image (disregarding possible padding).
221
+ See PostProcess for information on how to retrieve the unnormalized bounding box.
222
+ - "aux_outputs": Optional, only returned when auxilary losses are activated. It is a list of
223
+ dictionnaries containing the two above keys for each decoder layer.
224
+ """
225
+ if isinstance(samples, (list, torch.Tensor)):
226
+ samples = nested_tensor_from_tensor_list(samples)
227
+ features, pos = self.backbone(samples)
228
+ # print('features:', features[0].tensors.shape)
229
+ # print('pos:', pos[0].shape)
230
+ src, mask = features[-1].decompose()
231
+ # print('src shape:', src.shape, mask.shape)
232
+ assert mask is not None
233
+
234
+ hs, image_embeddings = self.transformer(self.input_proj(src), mask, self.query_embed.weight, pos[-1])
235
+
236
+ outputs_class = self.class_embed(hs)
237
+ outputs_coord = self.bbox_embed(hs).sigmoid()
238
+ out = {'pred_logits': outputs_class[-1], 'pred_boxes': outputs_coord[-1]}
239
+ if self.aux_loss:
240
+ out['aux_outputs'] = self._set_aux_loss(outputs_class, outputs_coord)
241
+ return out, image_embeddings
242
+
243
+ @torch.jit.unused
244
+ def _set_aux_loss(self, outputs_class, outputs_coord):
245
+ # this is a workaround to make torchscript happy, as torchscript
246
+ # doesn't support dictionary with non-homogeneous values, such
247
+ # as a dict having both a Tensor and a list.
248
+ return [{'pred_logits': a, 'pred_boxes': b}
249
+ for a, b in zip(outputs_class[:-1], outputs_coord[:-1])]
250
+
251
+ def sigmoid_focal_loss(inputs, targets, num_boxes, alpha: float = 0.25, gamma: float = 2):
252
+ """
253
+ Loss used in RetinaNet for dense detection: https://arxiv.org/abs/1708.02002.
254
+ Args:
255
+ inputs: A float tensor of arbitrary shape.
256
+ The predictions for each example.
257
+ targets: A float tensor with the same shape as inputs. Stores the binary
258
+ classification label for each element in inputs
259
+ (0 for the negative class and 1 for the positive class).
260
+ alpha: (optional) Weighting factor in range (0,1) to balance
261
+ positive vs negative examples. Default = -1 (no weighting).
262
+ gamma: Exponent of the modulating factor (1 - p_t) to
263
+ balance easy vs hard examples.
264
+ Returns:
265
+ Loss tensor
266
+ """
267
+ prob = inputs.sigmoid()
268
+ ce_loss = F.binary_cross_entropy_with_logits(inputs, targets, reduction="none")
269
+ p_t = prob * targets + (1 - prob) * (1 - targets)
270
+ loss = ce_loss * ((1 - p_t) ** gamma)
271
+
272
+ if alpha >= 0:
273
+ alpha_t = alpha * targets + (1 - alpha) * (1 - targets)
274
+ loss = alpha_t * loss
275
+
276
+ return loss.mean(1).sum() / num_boxes
277
+
278
+ class SetCriterion(nn.Module):
279
+ """ This class computes the loss for DETR.
280
+ The process happens in two steps:
281
+ 1) we compute hungarian assignment between ground truth boxes and the outputs of the model
282
+ 2) we supervise each pair of matched ground-truth / prediction (supervise class and box)
283
+ """
284
+ def __init__(self, num_classes, matcher, weight_dict, eos_coef, losses, use_matcher=True):
285
+ """ Create the criterion.
286
+ Parameters:
287
+ num_classes: number of object categories, omitting the special no-object category
288
+ matcher: module able to compute a matching between targets and proposals
289
+ weight_dict: dict containing as key the names of the losses and as values their relative weight.
290
+ eos_coef: relative classification weight applied to the no-object category
291
+ losses: list of all the losses to be applied. See get_loss for list of available losses.
292
+ """
293
+ super().__init__()
294
+ self.num_classes = num_classes
295
+ self.matcher = matcher
296
+ self.weight_dict = weight_dict
297
+ self.eos_coef = eos_coef
298
+ self.losses = losses
299
+ empty_weight = torch.ones(self.num_classes + 1)
300
+ empty_weight[-1] = self.eos_coef
301
+ self.register_buffer('empty_weight', empty_weight)
302
+ self.use_matcher = use_matcher
303
+
304
+ def loss_labels(self, outputs, targets, indices, num_boxes, log=True):
305
+ """Classification loss (NLL)
306
+ targets dicts must contain the key "labels" containing a tensor of dim [nb_target_boxes]
307
+ """
308
+ assert 'pred_logits' in outputs
309
+ src_logits = outputs['pred_logits']
310
+
311
+ idx = self._get_src_permutation_idx(indices)
312
+ target_classes_o = torch.cat([t["labels"][J] for t, (_, J) in zip(targets, indices)])
313
+ target_classes = torch.full(src_logits.shape[:2], self.num_classes,
314
+ dtype=torch.int64, device=src_logits.device)
315
+ target_classes[idx] = target_classes_o
316
+
317
+ target_classes_onehot = torch.zeros([src_logits.shape[0], src_logits.shape[1], src_logits.shape[2]+1],
318
+ dtype=src_logits.dtype, layout=src_logits.layout, device=src_logits.device)
319
+ target_classes_onehot.scatter_(2, target_classes.unsqueeze(-1), 1)
320
+ target_classes_onehot = target_classes_onehot[:,:,:-1]
321
+ loss_ce = sigmoid_focal_loss(src_logits, target_classes_onehot, num_boxes, alpha=0.25, gamma=2) * src_logits.shape[1]
322
+
323
+ # loss_ce = F.cross_entropy(src_logits.transpose(1, 2), target_classes, self.empty_weight)
324
+ losses = {'loss_ce': loss_ce}
325
+
326
+ if log:
327
+ # TODO this should probably be a separate loss, not hacked in this one here
328
+ losses['class_error'] = 100 - accuracy(src_logits[idx], target_classes_o)[0]
329
+ return losses
330
+
331
+ @torch.no_grad()
332
+ def loss_cardinality(self, outputs, targets, indices, num_boxes):
333
+ """ Compute the cardinality error, ie the absolute error in the number of predicted non-empty boxes
334
+ This is not really a loss, it is intended for logging purposes only. It doesn't propagate gradients
335
+ """
336
+ pred_logits = outputs['pred_logits']
337
+ device = pred_logits.device
338
+ tgt_lengths = torch.as_tensor([len(v["labels"]) for v in targets], device=device)
339
+ # Count the number of predictions that are NOT "no-object" (which is the last class)
340
+ card_pred = (pred_logits.argmax(-1) != pred_logits.shape[-1] - 1).sum(1)
341
+ card_err = F.l1_loss(card_pred.float(), tgt_lengths.float())
342
+ losses = {'cardinality_error': card_err}
343
+ return losses
344
+
345
+ def loss_boxes(self, outputs, targets, indices, num_boxes):
346
+ """Compute the losses related to the bounding boxes, the L1 regression loss and the GIoU loss
347
+ targets dicts must contain the key "boxes" containing a tensor of dim [nb_target_boxes, 4]
348
+ The target boxes are expected in format (center_x, center_y, w, h), normalized by the image size.
349
+ """
350
+ assert 'pred_boxes' in outputs
351
+ idx = self._get_src_permutation_idx(indices)
352
+ src_boxes = outputs['pred_boxes'][idx] # (N, 4)
353
+ target_boxes = torch.cat([t['boxes'][i] for t, (_, i) in zip(targets, indices)], dim=0)
354
+
355
+ loss_bbox = F.l1_loss(src_boxes, target_boxes, reduction='none')
356
+
357
+ losses = {}
358
+ losses['loss_bbox'] = loss_bbox.sum() / num_boxes
359
+
360
+ loss_giou = 1 - torch.diag(box_ops.generalized_box_iou(
361
+ box_ops.box_cxcywh_to_xyxy(src_boxes),
362
+ box_ops.box_cxcywh_to_xyxy(target_boxes)))
363
+ losses['loss_giou'] = loss_giou.sum() / num_boxes
364
+ return losses
365
+
366
+ def loss_masks(self, outputs, targets, indices, num_boxes):
367
+ """Compute the losses related to the masks: the focal loss and the dice loss.
368
+ targets dicts must contain the key "masks" containing a tensor of dim [nb_target_boxes, h, w]
369
+ """
370
+ assert "pred_masks" in outputs
371
+
372
+ # src_idx = self._get_src_permutation_idx(indices)
373
+ # tgt_idx = self._get_tgt_permutation_idx(indices)
374
+
375
+ src_masks = outputs["pred_masks"].unsqueeze(0) # (bs, N, H, W)
376
+ # src_masks = src_masks[src_idx]
377
+ # masks = [t["masks"] for t in targets]
378
+ # # TODO use valid to mask invalid areas due to padding in loss
379
+ # target_masks, valid = nested_tensor_from_tensor_list(masks).decompose()
380
+ # target_masks = target_masks.to(src_masks)
381
+ target_masks = targets[0]['masks'].unsqueeze(0)
382
+
383
+ # target_masks = target_masks[tgt_idx]
384
+
385
+ # # upsample predictions to the target size
386
+ # src_masks = interpolate(src_masks[:, None], size=target_masks.shape[-2:],
387
+ # mode="bilinear", align_corners=False)
388
+ # src_masks = src_masks[:, 0].flatten(1)
389
+
390
+ # target_masks = target_masks.flatten(1)
391
+ # target_masks = target_masks.view(src_masks.shape)
392
+
393
+ # ---------sam--------
394
+ # src_masks = outputs['pred_masks']
395
+ # target_masks = targets[0]['masks']
396
+ dice_loss = monai.losses.DiceCELoss(sigmoid=True, squared_pred=True, reduction='mean')
397
+ losses = {
398
+ "loss_mask": focal_loss_masks(src_masks.cpu(), target_masks.cpu(), num_boxes),
399
+ # "loss_dice": dice_loss(src_masks, target_masks.cpu(), num_boxes),
400
+ "loss_dice": dice_loss(src_masks.cpu(), target_masks.cpu()),
401
+ }
402
+ return losses
403
+
404
+ def _get_src_permutation_idx(self, indices):
405
+ # permute predictions following indices
406
+ batch_idx = torch.cat([torch.full_like(src, i) for i, (src, _) in enumerate(indices)])
407
+ src_idx = torch.cat([src for (src, _) in indices])
408
+ return batch_idx, src_idx
409
+
410
+ def _get_tgt_permutation_idx(self, indices):
411
+ # permute targets following indices
412
+ batch_idx = torch.cat([torch.full_like(tgt, i) for i, (_, tgt) in enumerate(indices)])
413
+ tgt_idx = torch.cat([tgt for (_, tgt) in indices])
414
+ return batch_idx, tgt_idx
415
+
416
+ def get_loss(self, loss, outputs, targets, indices, num_boxes, **kwargs):
417
+ loss_map = {
418
+ 'labels': self.loss_labels,
419
+ 'cardinality': self.loss_cardinality,
420
+ 'boxes': self.loss_boxes,
421
+ 'masks': self.loss_masks
422
+ }
423
+ assert loss in loss_map, f'do you really want to compute {loss} loss?'
424
+ return loss_map[loss](outputs, targets, indices, num_boxes, **kwargs)
425
+
426
+ def forward(self, outputs, targets):
427
+ """ This performs the loss computation.
428
+ Parameters:
429
+ outputs: dict of tensors, see the output specification of the model for the format
430
+ targets: list of dicts, such that len(targets) == batch_size.
431
+ The expected keys in each dict depends on the losses applied, see each loss' doc
432
+ """
433
+ outputs_without_aux = {k: v for k, v in outputs.items() if k != 'aux_outputs'}
434
+
435
+ # Retrieve the matching between the outputs of the last layer and the targets
436
+ if self.use_matcher:
437
+ indices = self.matcher(outputs_without_aux, targets)
438
+ else:
439
+ indices = None
440
+
441
+ # Compute the average number of target boxes accross all nodes, for normalization purposes
442
+ num_boxes = sum(len(t["labels"]) for t in targets)
443
+ num_boxes = torch.as_tensor([num_boxes], dtype=torch.float, device=next(iter(outputs.values())).device)
444
+ if is_dist_avail_and_initialized():
445
+ torch.distributed.all_reduce(num_boxes)
446
+ num_boxes = torch.clamp(num_boxes / get_world_size(), min=1).item()
447
+
448
+ # Compute all the requested losses
449
+ losses = {}
450
+ for loss in self.losses:
451
+ losses.update(self.get_loss(loss, outputs, targets, indices, num_boxes))
452
+
453
+ # In case of auxiliary losses, we repeat this process with the output of each intermediate layer.
454
+ if 'aux_outputs' in outputs:
455
+ for i, aux_outputs in enumerate(outputs['aux_outputs']):
456
+ indices = self.matcher(aux_outputs, targets)
457
+ for loss in self.losses:
458
+ if loss == 'masks':
459
+ # Intermediate masks losses are too costly to compute, we ignore them.
460
+ continue
461
+ kwargs = {}
462
+ if loss == 'labels':
463
+ # Logging is enabled only for the last layer
464
+ kwargs = {'log': False}
465
+ l_dict = self.get_loss(loss, aux_outputs, targets, indices, num_boxes, **kwargs)
466
+ l_dict = {k + f'_{i}': v for k, v in l_dict.items()}
467
+ losses.update(l_dict)
468
+
469
+ return losses
470
+
471
+
472
+ class PostProcess(nn.Module):
473
+ """ This module converts the model's output into the format expected by the coco api"""
474
+ @torch.no_grad()
475
+ def forward(self, outputs, target_sizes):
476
+ """ Perform the computation
477
+ Parameters:
478
+ outputs: raw outputs of the model
479
+ target_sizes: tensor of dimension [batch_size x 2] containing the size of each images of the batch
480
+ For evaluation, this must be the original image size (before any data augmentation)
481
+ For visualization, this should be the image size after data augment, but before padding
482
+ """
483
+ out_logits, out_bbox = outputs['pred_logits'], outputs['pred_boxes']
484
+
485
+ assert len(out_logits) == len(target_sizes)
486
+ assert target_sizes.shape[1] == 2
487
+
488
+ prob = F.softmax(out_logits, -1)
489
+ scores, labels = prob[..., :-1].max(-1)
490
+
491
+ # convert to [x0, y0, x1, y1] format
492
+ boxes = box_ops.box_cxcywh_to_xyxy(out_bbox)
493
+ # and from relative [0, 1] to absolute [0, height] coordinates
494
+ img_h, img_w = target_sizes.unbind(1)
495
+ scale_fct = torch.stack([img_w, img_h, img_w, img_h], dim=1)
496
+ boxes = boxes * scale_fct[:, None, :]
497
+
498
+ # print('Originial output:')
499
+ # print('Labels:', labels, 'bbox:', boxes)
500
+
501
+ results = [{'scores': s, 'labels': l, 'boxes': b} for s, l, b in zip(scores, labels, boxes)]
502
+
503
+ return results
504
+
505
+
506
+ class MLP(nn.Module):
507
+ """ Very simple multi-layer perceptron (also called FFN)"""
508
+
509
+ def __init__(self, input_dim, hidden_dim, output_dim, num_layers):
510
+ super().__init__()
511
+ self.num_layers = num_layers
512
+ h = [hidden_dim] * (num_layers - 1)
513
+ self.layers = nn.ModuleList(nn.Linear(n, k) for n, k in zip([input_dim] + h, h + [output_dim]))
514
+
515
+ def forward(self, x):
516
+ for i, layer in enumerate(self.layers):
517
+ x = F.relu(layer(x)) if i < self.num_layers - 1 else layer(x)
518
+ return x
519
+
520
+
521
+ def build(args):
522
+ # the `num_classes` naming here is somewhat misleading.
523
+ # it indeed corresponds to `max_obj_id + 1`, where max_obj_id
524
+ # is the maximum id for a class in your dataset. For example,
525
+ # COCO has a max_obj_id of 90, so we pass `num_classes` to be 91.
526
+ # As another example, for a dataset that has a single class with id 1,
527
+ # you should pass `num_classes` to be 2 (max_obj_id + 1).
528
+ # For more details on this, check the following discussion
529
+ # https://github.com/facebookresearch/detr/issues/108#issuecomment-650269223
530
+ num_classes = 8 if args.dataset_file == 'endovis17' else 91
531
+ if args.dataset_file == 'endovis18':
532
+ num_classes = 9
533
+ if args.dataset_file == "coco_panoptic":
534
+ # for panoptic, we just add a num_classes that is large enough to hold
535
+ # max_obj_id + 1, but the exact value doesn't really matter
536
+ num_classes = 250
537
+ device = torch.device(args.device)
538
+
539
+ backbone = build_backbone(args)
540
+
541
+ transformer = build_transformer(args)
542
+
543
+ if args.model:
544
+ # pretrained_model = torch.hub.load('facebookresearch/detr', 'detr_resnet50', pretrained=True)
545
+ # # save model weights
546
+ # torch.save(pretrained_model.state_dict(), 'detr_weights.pth')
547
+
548
+ # initialize model weights
549
+ model = DETR(
550
+ backbone,
551
+ transformer,
552
+ num_classes=num_classes,
553
+ num_queries=args.num_queries,
554
+ aux_loss=args.aux_loss,
555
+ )
556
+
557
+ # weights = torch.load('detr_weights.pth')
558
+ # # checkpoint = torch.load('outputs/ckpt_best.pth')
559
+ # # weights = checkpoint['model']
560
+ # # delete specific layers in weights
561
+ # exclude_keys = ['class_embed.weight', 'class_embed.bias', 'input_proj.weight']
562
+ # # for key in exclude_keys:
563
+ # # del weights[key]
564
+
565
+ # # model.load_state_dict(weights, strict=False)
566
+
567
+ else:
568
+ model = DETR(
569
+ backbone,
570
+ transformer,
571
+ num_classes=num_classes,
572
+ num_queries=args.num_queries,
573
+ aux_loss=args.aux_loss,
574
+ )
575
+
576
+
577
+ if args.masks:
578
+ model = DETRsegm(model, freeze_detr=(args.frozen_weights is not None))
579
+ matcher = build_matcher(args)
580
+ weight_dict = {'loss_ce': 1, 'loss_bbox': args.bbox_loss_coef}
581
+ weight_dict['loss_giou'] = args.giou_loss_coef
582
+ if args.masks:
583
+ weight_dict["loss_mask"] = args.mask_loss_coef
584
+ weight_dict["loss_dice"] = args.dice_loss_coef
585
+ # TODO this is a hack
586
+ if args.aux_loss:
587
+ aux_weight_dict = {}
588
+ for i in range(args.dec_layers - 1):
589
+ aux_weight_dict.update({k + f'_{i}': v for k, v in weight_dict.items()})
590
+ weight_dict.update(aux_weight_dict)
591
+
592
+ losses = ['labels', 'boxes', 'cardinality']
593
+ if args.masks:
594
+ losses += ["masks"]
595
+ criterion = SetCriterion(num_classes, matcher=matcher, weight_dict=weight_dict,
596
+ eos_coef=args.eos_coef, losses=losses)
597
+
598
+ seg_losses = ['masks']
599
+ seg_losses += losses
600
+ seg_weight_dict = {'loss_mask': args.mask_loss_coef, 'loss_dice': args.dice_loss_coef, 'loss_ce': 1, 'loss_bbox': args.bbox_loss_coef,
601
+ 'loss_giou': args.giou_loss_coef}
602
+ #TODO if use_matcher == True: use Hungarian matching for predicted boxes and GT boxes
603
+ seg_criterion = SetCriterion(num_classes, matcher=matcher, weight_dict=seg_weight_dict,
604
+ eos_coef=args.eos_coef, losses=seg_losses, use_matcher=True)
605
+ seg_criterion.to(device)
606
+
607
+ criterion.to(device)
608
+ postprocessors = {'bbox': PostProcess()}
609
+ if args.masks:
610
+ postprocessors['segm'] = PostProcessSegm()
611
+ if args.dataset_file == "coco_panoptic":
612
+ is_thing_map = {i: i <= 90 for i in range(201)}
613
+ postprocessors["panoptic"] = PostProcessPanoptic(is_thing_map, threshold=0.85)
614
+
615
+ return model, criterion, seg_criterion, postprocessors
616
+
models/matcher.py ADDED
@@ -0,0 +1,86 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ # Copyright (c) Facebook, Inc. and its affiliates. All Rights Reserved
2
+ """
3
+ Modules to compute the matching cost and solve the corresponding LSAP.
4
+ """
5
+ import torch
6
+ from scipy.optimize import linear_sum_assignment
7
+ from torch import nn
8
+
9
+ from util.box_ops import box_cxcywh_to_xyxy, generalized_box_iou
10
+
11
+
12
+ class HungarianMatcher(nn.Module):
13
+ """This class computes an assignment between the targets and the predictions of the network
14
+
15
+ For efficiency reasons, the targets don't include the no_object. Because of this, in general,
16
+ there are more predictions than targets. In this case, we do a 1-to-1 matching of the best predictions,
17
+ while the others are un-matched (and thus treated as non-objects).
18
+ """
19
+
20
+ def __init__(self, cost_class: float = 1, cost_bbox: float = 1, cost_giou: float = 1):
21
+ """Creates the matcher
22
+
23
+ Params:
24
+ cost_class: This is the relative weight of the classification error in the matching cost
25
+ cost_bbox: This is the relative weight of the L1 error of the bounding box coordinates in the matching cost
26
+ cost_giou: This is the relative weight of the giou loss of the bounding box in the matching cost
27
+ """
28
+ super().__init__()
29
+ self.cost_class = cost_class
30
+ self.cost_bbox = cost_bbox
31
+ self.cost_giou = cost_giou
32
+ assert cost_class != 0 or cost_bbox != 0 or cost_giou != 0, "all costs cant be 0"
33
+
34
+ @torch.no_grad()
35
+ def forward(self, outputs, targets):
36
+ """ Performs the matching
37
+
38
+ Params:
39
+ outputs: This is a dict that contains at least these entries:
40
+ "pred_logits": Tensor of dim [batch_size, num_queries, num_classes] with the classification logits
41
+ "pred_boxes": Tensor of dim [batch_size, num_queries, 4] with the predicted box coordinates
42
+
43
+ targets: This is a list of targets (len(targets) = batch_size), where each target is a dict containing:
44
+ "labels": Tensor of dim [num_target_boxes] (where num_target_boxes is the number of ground-truth
45
+ objects in the target) containing the class labels
46
+ "boxes": Tensor of dim [num_target_boxes, 4] containing the target box coordinates
47
+
48
+ Returns:
49
+ A list of size batch_size, containing tuples of (index_i, index_j) where:
50
+ - index_i is the indices of the selected predictions (in order)
51
+ - index_j is the indices of the corresponding selected targets (in order)
52
+ For each batch element, it holds:
53
+ len(index_i) = len(index_j) = min(num_queries, num_target_boxes)
54
+ """
55
+ bs, num_queries = outputs["pred_logits"].shape[:2]
56
+
57
+ # We flatten to compute the cost matrices in a batch
58
+ out_prob = outputs["pred_logits"].flatten(0, 1).softmax(-1) # [batch_size * num_queries, num_classes]
59
+ out_bbox = outputs["pred_boxes"].flatten(0, 1) # [batch_size * num_queries, 4]
60
+
61
+ # Also concat the target labels and boxes
62
+ tgt_ids = torch.cat([v["labels"] for v in targets])
63
+ tgt_bbox = torch.cat([v["boxes"] for v in targets])
64
+
65
+ # Compute the classification cost. Contrary to the loss, we don't use the NLL,
66
+ # but approximate it in 1 - proba[target class].
67
+ # The 1 is a constant that doesn't change the matching, it can be ommitted.
68
+ cost_class = -out_prob[:, tgt_ids]
69
+
70
+ # Compute the L1 cost between boxes
71
+ cost_bbox = torch.cdist(out_bbox, tgt_bbox, p=1)
72
+
73
+ # Compute the giou cost betwen boxes
74
+ cost_giou = -generalized_box_iou(box_cxcywh_to_xyxy(out_bbox), box_cxcywh_to_xyxy(tgt_bbox))
75
+
76
+ # Final cost matrix
77
+ C = self.cost_bbox * cost_bbox + self.cost_class * cost_class + self.cost_giou * cost_giou
78
+ C = C.view(bs, num_queries, -1).cpu()
79
+
80
+ sizes = [len(v["boxes"]) for v in targets]
81
+ indices = [linear_sum_assignment(c[i]) for i, c in enumerate(C.split(sizes, -1))]
82
+ return [(torch.as_tensor(i, dtype=torch.int64), torch.as_tensor(j, dtype=torch.int64)) for i, j in indices]
83
+
84
+
85
+ def build_matcher(args):
86
+ return HungarianMatcher(cost_class=args.set_cost_class, cost_bbox=args.set_cost_bbox, cost_giou=args.set_cost_giou)
models/position_encoding.py ADDED
@@ -0,0 +1,89 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ # Copyright (c) Facebook, Inc. and its affiliates. All Rights Reserved
2
+ """
3
+ Various positional encodings for the transformer.
4
+ """
5
+ import math
6
+ import torch
7
+ from torch import nn
8
+
9
+ from util.misc import NestedTensor
10
+
11
+
12
+ class PositionEmbeddingSine(nn.Module):
13
+ """
14
+ This is a more standard version of the position embedding, very similar to the one
15
+ used by the Attention is all you need paper, generalized to work on images.
16
+ """
17
+ def __init__(self, num_pos_feats=64, temperature=10000, normalize=False, scale=None):
18
+ super().__init__()
19
+ self.num_pos_feats = num_pos_feats
20
+ self.temperature = temperature
21
+ self.normalize = normalize
22
+ if scale is not None and normalize is False:
23
+ raise ValueError("normalize should be True if scale is passed")
24
+ if scale is None:
25
+ scale = 2 * math.pi
26
+ self.scale = scale
27
+
28
+ def forward(self, tensor_list: NestedTensor):
29
+ x = tensor_list.tensors
30
+ mask = tensor_list.mask
31
+ assert mask is not None
32
+ not_mask = ~mask
33
+ y_embed = not_mask.cumsum(1, dtype=torch.float32)
34
+ x_embed = not_mask.cumsum(2, dtype=torch.float32)
35
+ if self.normalize:
36
+ eps = 1e-6
37
+ y_embed = y_embed / (y_embed[:, -1:, :] + eps) * self.scale
38
+ x_embed = x_embed / (x_embed[:, :, -1:] + eps) * self.scale
39
+
40
+ dim_t = torch.arange(self.num_pos_feats, dtype=torch.float32, device=x.device)
41
+ dim_t = self.temperature ** (2 * (dim_t // 2) / self.num_pos_feats)
42
+
43
+ pos_x = x_embed[:, :, :, None] / dim_t
44
+ pos_y = y_embed[:, :, :, None] / dim_t
45
+ pos_x = torch.stack((pos_x[:, :, :, 0::2].sin(), pos_x[:, :, :, 1::2].cos()), dim=4).flatten(3)
46
+ pos_y = torch.stack((pos_y[:, :, :, 0::2].sin(), pos_y[:, :, :, 1::2].cos()), dim=4).flatten(3)
47
+ pos = torch.cat((pos_y, pos_x), dim=3).permute(0, 3, 1, 2)
48
+ return pos
49
+
50
+
51
+ class PositionEmbeddingLearned(nn.Module):
52
+ """
53
+ Absolute pos embedding, learned.
54
+ """
55
+ def __init__(self, num_pos_feats=256):
56
+ super().__init__()
57
+ self.row_embed = nn.Embedding(50, num_pos_feats)
58
+ self.col_embed = nn.Embedding(50, num_pos_feats)
59
+ self.reset_parameters()
60
+
61
+ def reset_parameters(self):
62
+ nn.init.uniform_(self.row_embed.weight)
63
+ nn.init.uniform_(self.col_embed.weight)
64
+
65
+ def forward(self, tensor_list: NestedTensor):
66
+ x = tensor_list.tensors
67
+ h, w = x.shape[-2:]
68
+ i = torch.arange(w, device=x.device)
69
+ j = torch.arange(h, device=x.device)
70
+ x_emb = self.col_embed(i)
71
+ y_emb = self.row_embed(j)
72
+ pos = torch.cat([
73
+ x_emb.unsqueeze(0).repeat(h, 1, 1),
74
+ y_emb.unsqueeze(1).repeat(1, w, 1),
75
+ ], dim=-1).permute(2, 0, 1).unsqueeze(0).repeat(x.shape[0], 1, 1, 1)
76
+ return pos
77
+
78
+
79
+ def build_position_encoding(args):
80
+ N_steps = args.hidden_dim // 2 # 256 // 2 = 128
81
+ if args.position_embedding in ('v2', 'sine'):
82
+ # TODO find a better way of exposing other arguments
83
+ position_embedding = PositionEmbeddingSine(N_steps, normalize=True)
84
+ elif args.position_embedding in ('v3', 'learned'):
85
+ position_embedding = PositionEmbeddingLearned(N_steps)
86
+ else:
87
+ raise ValueError(f"not supported {args.position_embedding}")
88
+
89
+ return position_embedding
models/sam/CODE_OF_CONDUCT.md ADDED
@@ -0,0 +1,80 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ # Code of Conduct
2
+
3
+ ## Our Pledge
4
+
5
+ In the interest of fostering an open and welcoming environment, we as
6
+ contributors and maintainers pledge to make participation in our project and
7
+ our community a harassment-free experience for everyone, regardless of age, body
8
+ size, disability, ethnicity, sex characteristics, gender identity and expression,
9
+ level of experience, education, socio-economic status, nationality, personal
10
+ appearance, race, religion, or sexual identity and orientation.
11
+
12
+ ## Our Standards
13
+
14
+ Examples of behavior that contributes to creating a positive environment
15
+ include:
16
+
17
+ * Using welcoming and inclusive language
18
+ * Being respectful of differing viewpoints and experiences
19
+ * Gracefully accepting constructive criticism
20
+ * Focusing on what is best for the community
21
+ * Showing empathy towards other community members
22
+
23
+ Examples of unacceptable behavior by participants include:
24
+
25
+ * The use of sexualized language or imagery and unwelcome sexual attention or
26
+ advances
27
+ * Trolling, insulting/derogatory comments, and personal or political attacks
28
+ * Public or private harassment
29
+ * Publishing others' private information, such as a physical or electronic
30
+ address, without explicit permission
31
+ * Other conduct which could reasonably be considered inappropriate in a
32
+ professional setting
33
+
34
+ ## Our Responsibilities
35
+
36
+ Project maintainers are responsible for clarifying the standards of acceptable
37
+ behavior and are expected to take appropriate and fair corrective action in
38
+ response to any instances of unacceptable behavior.
39
+
40
+ Project maintainers have the right and responsibility to remove, edit, or
41
+ reject comments, commits, code, wiki edits, issues, and other contributions
42
+ that are not aligned to this Code of Conduct, or to ban temporarily or
43
+ permanently any contributor for other behaviors that they deem inappropriate,
44
+ threatening, offensive, or harmful.
45
+
46
+ ## Scope
47
+
48
+ This Code of Conduct applies within all project spaces, and it also applies when
49
+ an individual is representing the project or its community in public spaces.
50
+ Examples of representing a project or community include using an official
51
+ project e-mail address, posting via an official social media account, or acting
52
+ as an appointed representative at an online or offline event. Representation of
53
+ a project may be further defined and clarified by project maintainers.
54
+
55
+ This Code of Conduct also applies outside the project spaces when there is a
56
+ reasonable belief that an individual's behavior may have a negative impact on
57
+ the project or its community.
58
+
59
+ ## Enforcement
60
+
61
+ Instances of abusive, harassing, or otherwise unacceptable behavior may be
62
+ reported by contacting the project team at <opensource-conduct@fb.com>. All
63
+ complaints will be reviewed and investigated and will result in a response that
64
+ is deemed necessary and appropriate to the circumstances. The project team is
65
+ obligated to maintain confidentiality with regard to the reporter of an incident.
66
+ Further details of specific enforcement policies may be posted separately.
67
+
68
+ Project maintainers who do not follow or enforce the Code of Conduct in good
69
+ faith may face temporary or permanent repercussions as determined by other
70
+ members of the project's leadership.
71
+
72
+ ## Attribution
73
+
74
+ This Code of Conduct is adapted from the [Contributor Covenant][homepage], version 1.4,
75
+ available at https://www.contributor-covenant.org/version/1/4/code-of-conduct.html
76
+
77
+ [homepage]: https://www.contributor-covenant.org
78
+
79
+ For answers to common questions about this code of conduct, see
80
+ https://www.contributor-covenant.org/faq
models/sam/CONTRIBUTING.md ADDED
@@ -0,0 +1,31 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ # Contributing to segment-anything
2
+ We want to make contributing to this project as easy and transparent as
3
+ possible.
4
+
5
+ ## Pull Requests
6
+ We actively welcome your pull requests.
7
+
8
+ 1. Fork the repo and create your branch from `main`.
9
+ 2. If you've added code that should be tested, add tests.
10
+ 3. If you've changed APIs, update the documentation.
11
+ 4. Ensure the test suite passes.
12
+ 5. Make sure your code lints, using the `linter.sh` script in the project's root directory. Linting requires `black==23.*`, `isort==5.12.0`, `flake8`, and `mypy`.
13
+ 6. If you haven't already, complete the Contributor License Agreement ("CLA").
14
+
15
+ ## Contributor License Agreement ("CLA")
16
+ In order to accept your pull request, we need you to submit a CLA. You only need
17
+ to do this once to work on any of Facebook's open source projects.
18
+
19
+ Complete your CLA here: <https://code.facebook.com/cla>
20
+
21
+ ## Issues
22
+ We use GitHub issues to track public bugs. Please ensure your description is
23
+ clear and has sufficient instructions to be able to reproduce the issue.
24
+
25
+ Facebook has a [bounty program](https://www.facebook.com/whitehat/) for the safe
26
+ disclosure of security bugs. In those cases, please go through the process
27
+ outlined on that page and do not file a public issue.
28
+
29
+ ## License
30
+ By contributing to segment-anything, you agree that your contributions will be licensed
31
+ under the LICENSE file in the root directory of this source tree.
models/sam/LICENSE ADDED
@@ -0,0 +1,201 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ Apache License
2
+ Version 2.0, January 2004
3
+ http://www.apache.org/licenses/
4
+
5
+ TERMS AND CONDITIONS FOR USE, REPRODUCTION, AND DISTRIBUTION
6
+
7
+ 1. Definitions.
8
+
9
+ "License" shall mean the terms and conditions for use, reproduction,
10
+ and distribution as defined by Sections 1 through 9 of this document.
11
+
12
+ "Licensor" shall mean the copyright owner or entity authorized by
13
+ the copyright owner that is granting the License.
14
+
15
+ "Legal Entity" shall mean the union of the acting entity and all
16
+ other entities that control, are controlled by, or are under common
17
+ control with that entity. For the purposes of this definition,
18
+ "control" means (i) the power, direct or indirect, to cause the
19
+ direction or management of such entity, whether by contract or
20
+ otherwise, or (ii) ownership of fifty percent (50%) or more of the
21
+ outstanding shares, or (iii) beneficial ownership of such entity.
22
+
23
+ "You" (or "Your") shall mean an individual or Legal Entity
24
+ exercising permissions granted by this License.
25
+
26
+ "Source" form shall mean the preferred form for making modifications,
27
+ including but not limited to software source code, documentation
28
+ source, and configuration files.
29
+
30
+ "Object" form shall mean any form resulting from mechanical
31
+ transformation or translation of a Source form, including but
32
+ not limited to compiled object code, generated documentation,
33
+ and conversions to other media types.
34
+
35
+ "Work" shall mean the work of authorship, whether in Source or
36
+ Object form, made available under the License, as indicated by a
37
+ copyright notice that is included in or attached to the work
38
+ (an example is provided in the Appendix below).
39
+
40
+ "Derivative Works" shall mean any work, whether in Source or Object
41
+ form, that is based on (or derived from) the Work and for which the
42
+ editorial revisions, annotations, elaborations, or other modifications
43
+ represent, as a whole, an original work of authorship. For the purposes
44
+ of this License, Derivative Works shall not include works that remain
45
+ separable from, or merely link (or bind by name) to the interfaces of,
46
+ the Work and Derivative Works thereof.
47
+
48
+ "Contribution" shall mean any work of authorship, including
49
+ the original version of the Work and any modifications or additions
50
+ to that Work or Derivative Works thereof, that is intentionally
51
+ submitted to Licensor for inclusion in the Work by the copyright owner
52
+ or by an individual or Legal Entity authorized to submit on behalf of
53
+ the copyright owner. For the purposes of this definition, "submitted"
54
+ means any form of electronic, verbal, or written communication sent
55
+ to the Licensor or its representatives, including but not limited to
56
+ communication on electronic mailing lists, source code control systems,
57
+ and issue tracking systems that are managed by, or on behalf of, the
58
+ Licensor for the purpose of discussing and improving the Work, but
59
+ excluding communication that is conspicuously marked or otherwise
60
+ designated in writing by the copyright owner as "Not a Contribution."
61
+
62
+ "Contributor" shall mean Licensor and any individual or Legal Entity
63
+ on behalf of whom a Contribution has been received by Licensor and
64
+ subsequently incorporated within the Work.
65
+
66
+ 2. Grant of Copyright License. Subject to the terms and conditions of
67
+ this License, each Contributor hereby grants to You a perpetual,
68
+ worldwide, non-exclusive, no-charge, royalty-free, irrevocable
69
+ copyright license to reproduce, prepare Derivative Works of,
70
+ publicly display, publicly perform, sublicense, and distribute the
71
+ Work and such Derivative Works in Source or Object form.
72
+
73
+ 3. Grant of Patent License. Subject to the terms and conditions of
74
+ this License, each Contributor hereby grants to You a perpetual,
75
+ worldwide, non-exclusive, no-charge, royalty-free, irrevocable
76
+ (except as stated in this section) patent license to make, have made,
77
+ use, offer to sell, sell, import, and otherwise transfer the Work,
78
+ where such license applies only to those patent claims licensable
79
+ by such Contributor that are necessarily infringed by their
80
+ Contribution(s) alone or by combination of their Contribution(s)
81
+ with the Work to which such Contribution(s) was submitted. If You
82
+ institute patent litigation against any entity (including a
83
+ cross-claim or counterclaim in a lawsuit) alleging that the Work
84
+ or a Contribution incorporated within the Work constitutes direct
85
+ or contributory patent infringement, then any patent licenses
86
+ granted to You under this License for that Work shall terminate
87
+ as of the date such litigation is filed.
88
+
89
+ 4. Redistribution. You may reproduce and distribute copies of the
90
+ Work or Derivative Works thereof in any medium, with or without
91
+ modifications, and in Source or Object form, provided that You
92
+ meet the following conditions:
93
+
94
+ (a) You must give any other recipients of the Work or
95
+ Derivative Works a copy of this License; and
96
+
97
+ (b) You must cause any modified files to carry prominent notices
98
+ stating that You changed the files; and
99
+
100
+ (c) You must retain, in the Source form of any Derivative Works
101
+ that You distribute, all copyright, patent, trademark, and
102
+ attribution notices from the Source form of the Work,
103
+ excluding those notices that do not pertain to any part of
104
+ the Derivative Works; and
105
+
106
+ (d) If the Work includes a "NOTICE" text file as part of its
107
+ distribution, then any Derivative Works that You distribute must
108
+ include a readable copy of the attribution notices contained
109
+ within such NOTICE file, excluding those notices that do not
110
+ pertain to any part of the Derivative Works, in at least one
111
+ of the following places: within a NOTICE text file distributed
112
+ as part of the Derivative Works; within the Source form or
113
+ documentation, if provided along with the Derivative Works; or,
114
+ within a display generated by the Derivative Works, if and
115
+ wherever such third-party notices normally appear. The contents
116
+ of the NOTICE file are for informational purposes only and
117
+ do not modify the License. You may add Your own attribution
118
+ notices within Derivative Works that You distribute, alongside
119
+ or as an addendum to the NOTICE text from the Work, provided
120
+ that such additional attribution notices cannot be construed
121
+ as modifying the License.
122
+
123
+ You may add Your own copyright statement to Your modifications and
124
+ may provide additional or different license terms and conditions
125
+ for use, reproduction, or distribution of Your modifications, or
126
+ for any such Derivative Works as a whole, provided Your use,
127
+ reproduction, and distribution of the Work otherwise complies with
128
+ the conditions stated in this License.
129
+
130
+ 5. Submission of Contributions. Unless You explicitly state otherwise,
131
+ any Contribution intentionally submitted for inclusion in the Work
132
+ by You to the Licensor shall be under the terms and conditions of
133
+ this License, without any additional terms or conditions.
134
+ Notwithstanding the above, nothing herein shall supersede or modify
135
+ the terms of any separate license agreement you may have executed
136
+ with Licensor regarding such Contributions.
137
+
138
+ 6. Trademarks. This License does not grant permission to use the trade
139
+ names, trademarks, service marks, or product names of the Licensor,
140
+ except as required for reasonable and customary use in describing the
141
+ origin of the Work and reproducing the content of the NOTICE file.
142
+
143
+ 7. Disclaimer of Warranty. Unless required by applicable law or
144
+ agreed to in writing, Licensor provides the Work (and each
145
+ Contributor provides its Contributions) on an "AS IS" BASIS,
146
+ WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or
147
+ implied, including, without limitation, any warranties or conditions
148
+ of TITLE, NON-INFRINGEMENT, MERCHANTABILITY, or FITNESS FOR A
149
+ PARTICULAR PURPOSE. You are solely responsible for determining the
150
+ appropriateness of using or redistributing the Work and assume any
151
+ risks associated with Your exercise of permissions under this License.
152
+
153
+ 8. Limitation of Liability. In no event and under no legal theory,
154
+ whether in tort (including negligence), contract, or otherwise,
155
+ unless required by applicable law (such as deliberate and grossly
156
+ negligent acts) or agreed to in writing, shall any Contributor be
157
+ liable to You for damages, including any direct, indirect, special,
158
+ incidental, or consequential damages of any character arising as a
159
+ result of this License or out of the use or inability to use the
160
+ Work (including but not limited to damages for loss of goodwill,
161
+ work stoppage, computer failure or malfunction, or any and all
162
+ other commercial damages or losses), even if such Contributor
163
+ has been advised of the possibility of such damages.
164
+
165
+ 9. Accepting Warranty or Additional Liability. While redistributing
166
+ the Work or Derivative Works thereof, You may choose to offer,
167
+ and charge a fee for, acceptance of support, warranty, indemnity,
168
+ or other liability obligations and/or rights consistent with this
169
+ License. However, in accepting such obligations, You may act only
170
+ on Your own behalf and on Your sole responsibility, not on behalf
171
+ of any other Contributor, and only if You agree to indemnify,
172
+ defend, and hold each Contributor harmless for any liability
173
+ incurred by, or claims asserted against, such Contributor by reason
174
+ of your accepting any such warranty or additional liability.
175
+
176
+ END OF TERMS AND CONDITIONS
177
+
178
+ APPENDIX: How to apply the Apache License to your work.
179
+
180
+ To apply the Apache License to your work, attach the following
181
+ boilerplate notice, with the fields enclosed by brackets "[]"
182
+ replaced with your own identifying information. (Don't include
183
+ the brackets!) The text should be enclosed in the appropriate
184
+ comment syntax for the file format. We also recommend that a
185
+ file or class name and description of purpose be included on the
186
+ same "printed page" as the copyright notice for easier
187
+ identification within third-party archives.
188
+
189
+ Copyright [yyyy] [name of copyright owner]
190
+
191
+ Licensed under the Apache License, Version 2.0 (the "License");
192
+ you may not use this file except in compliance with the License.
193
+ You may obtain a copy of the License at
194
+
195
+ http://www.apache.org/licenses/LICENSE-2.0
196
+
197
+ Unless required by applicable law or agreed to in writing, software
198
+ distributed under the License is distributed on an "AS IS" BASIS,
199
+ WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
200
+ See the License for the specific language governing permissions and
201
+ limitations under the License.
models/sam/README.md ADDED
@@ -0,0 +1,171 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ # Segment Anything
2
+
3
+ **[Meta AI Research, FAIR](https://ai.facebook.com/research/)**
4
+
5
+ [Alexander Kirillov](https://alexander-kirillov.github.io/), [Eric Mintun](https://ericmintun.github.io/), [Nikhila Ravi](https://nikhilaravi.com/), [Hanzi Mao](https://hanzimao.me/), Chloe Rolland, Laura Gustafson, [Tete Xiao](https://tetexiao.com), [Spencer Whitehead](https://www.spencerwhitehead.com/), Alex Berg, Wan-Yen Lo, [Piotr Dollar](https://pdollar.github.io/), [Ross Girshick](https://www.rossgirshick.info/)
6
+
7
+ [[`Paper`](https://ai.facebook.com/research/publications/segment-anything/)] [[`Project`](https://segment-anything.com/)] [[`Demo`](https://segment-anything.com/demo)] [[`Dataset`](https://segment-anything.com/dataset/index.html)] [[`Blog`](https://ai.facebook.com/blog/segment-anything-foundation-model-image-segmentation/)] [[`BibTeX`](#citing-segment-anything)]
8
+
9
+ ![SAM design](assets/model_diagram.png?raw=true)
10
+
11
+ The **Segment Anything Model (SAM)** produces high quality object masks from input prompts such as points or boxes, and it can be used to generate masks for all objects in an image. It has been trained on a [dataset](https://segment-anything.com/dataset/index.html) of 11 million images and 1.1 billion masks, and has strong zero-shot performance on a variety of segmentation tasks.
12
+
13
+ <p float="left">
14
+ <img src="assets/masks1.png?raw=true" width="37.25%" />
15
+ <img src="assets/masks2.jpg?raw=true" width="61.5%" />
16
+ </p>
17
+
18
+ ## Installation
19
+
20
+ The code requires `python>=3.8`, as well as `pytorch>=1.7` and `torchvision>=0.8`. Please follow the instructions [here](https://pytorch.org/get-started/locally/) to install both PyTorch and TorchVision dependencies. Installing both PyTorch and TorchVision with CUDA support is strongly recommended.
21
+
22
+ Install Segment Anything:
23
+
24
+ ```
25
+ pip install git+https://github.com/facebookresearch/segment-anything.git
26
+ ```
27
+
28
+ or clone the repository locally and install with
29
+
30
+ ```
31
+ git clone git@github.com:facebookresearch/segment-anything.git
32
+ cd segment-anything; pip install -e .
33
+ ```
34
+
35
+ The following optional dependencies are necessary for mask post-processing, saving masks in COCO format, the example notebooks, and exporting the model in ONNX format. `jupyter` is also required to run the example notebooks.
36
+
37
+ ```
38
+ pip install opencv-python pycocotools matplotlib onnxruntime onnx
39
+ ```
40
+
41
+ ## <a name="GettingStarted"></a>Getting Started
42
+
43
+ First download a [model checkpoint](#model-checkpoints). Then the model can be used in just a few lines to get masks from a given prompt:
44
+
45
+ ```
46
+ from segment_anything import SamPredictor, sam_model_registry
47
+ sam = sam_model_registry["<model_type>"](checkpoint="<path/to/checkpoint>")
48
+ predictor = SamPredictor(sam)
49
+ predictor.set_image(<your_image>)
50
+ masks, _, _ = predictor.predict(<input_prompts>)
51
+ ```
52
+
53
+ or generate masks for an entire image:
54
+
55
+ ```
56
+ from segment_anything import SamAutomaticMaskGenerator, sam_model_registry
57
+ sam = sam_model_registry["<model_type>"](checkpoint="<path/to/checkpoint>")
58
+ mask_generator = SamAutomaticMaskGenerator(sam)
59
+ masks = mask_generator.generate(<your_image>)
60
+ ```
61
+
62
+ Additionally, masks can be generated for images from the command line:
63
+
64
+ ```
65
+ python scripts/amg.py --checkpoint <path/to/checkpoint> --model-type <model_type> --input <image_or_folder> --output <path/to/output>
66
+ ```
67
+
68
+ See the examples notebooks on [using SAM with prompts](/notebooks/predictor_example.ipynb) and [automatically generating masks](/notebooks/automatic_mask_generator_example.ipynb) for more details.
69
+
70
+ <p float="left">
71
+ <img src="assets/notebook1.png?raw=true" width="49.1%" />
72
+ <img src="assets/notebook2.png?raw=true" width="48.9%" />
73
+ </p>
74
+
75
+ ## ONNX Export
76
+
77
+ SAM's lightweight mask decoder can be exported to ONNX format so that it can be run in any environment that supports ONNX runtime, such as in-browser as showcased in the [demo](https://segment-anything.com/demo). Export the model with
78
+
79
+ ```
80
+ python scripts/export_onnx_model.py --checkpoint <path/to/checkpoint> --model-type <model_type> --output <path/to/output>
81
+ ```
82
+
83
+ See the [example notebook](https://github.com/facebookresearch/segment-anything/blob/main/notebooks/onnx_model_example.ipynb) for details on how to combine image preprocessing via SAM's backbone with mask prediction using the ONNX model. It is recommended to use the latest stable version of PyTorch for ONNX export.
84
+
85
+ ### Web demo
86
+
87
+ The `demo/` folder has a simple one page React app which shows how to run mask prediction with the exported ONNX model in a web browser with multithreading. Please see [`demo/README.md`](https://github.com/facebookresearch/segment-anything/blob/main/demo/README.md) for more details.
88
+
89
+ ## <a name="Models"></a>Model Checkpoints
90
+
91
+ Three model versions of the model are available with different backbone sizes. These models can be instantiated by running
92
+
93
+ ```
94
+ from segment_anything import sam_model_registry
95
+ sam = sam_model_registry["<model_type>"](checkpoint="<path/to/checkpoint>")
96
+ ```
97
+
98
+ Click the links below to download the checkpoint for the corresponding model type.
99
+
100
+ - **`default` or `vit_h`: [ViT-H SAM model.](https://dl.fbaipublicfiles.com/segment_anything/sam_vit_h_4b8939.pth)**
101
+ - `vit_l`: [ViT-L SAM model.](https://dl.fbaipublicfiles.com/segment_anything/sam_vit_l_0b3195.pth)
102
+ - `vit_b`: [ViT-B SAM model.](https://dl.fbaipublicfiles.com/segment_anything/sam_vit_b_01ec64.pth)
103
+
104
+ ## Dataset
105
+
106
+ See [here](https://ai.facebook.com/datasets/segment-anything/) for an overview of the datastet. The dataset can be downloaded [here](https://ai.facebook.com/datasets/segment-anything-downloads/). By downloading the datasets you agree that you have read and accepted the terms of the SA-1B Dataset Research License.
107
+
108
+ We save masks per image as a json file. It can be loaded as a dictionary in python in the below format.
109
+
110
+ ```python
111
+ {
112
+ "image" : image_info,
113
+ "annotations" : [annotation],
114
+ }
115
+
116
+ image_info {
117
+ "image_id" : int, # Image id
118
+ "width" : int, # Image width
119
+ "height" : int, # Image height
120
+ "file_name" : str, # Image filename
121
+ }
122
+
123
+ annotation {
124
+ "id" : int, # Annotation id
125
+ "segmentation" : dict, # Mask saved in COCO RLE format.
126
+ "bbox" : [x, y, w, h], # The box around the mask, in XYWH format
127
+ "area" : int, # The area in pixels of the mask
128
+ "predicted_iou" : float, # The model's own prediction of the mask's quality
129
+ "stability_score" : float, # A measure of the mask's quality
130
+ "crop_box" : [x, y, w, h], # The crop of the image used to generate the mask, in XYWH format
131
+ "point_coords" : [[x, y]], # The point coordinates input to the model to generate the mask
132
+ }
133
+ ```
134
+
135
+ Image ids can be found in sa_images_ids.txt which can be downloaded using the above [link](https://ai.facebook.com/datasets/segment-anything-downloads/) as well.
136
+
137
+ To decode a mask in COCO RLE format into binary:
138
+
139
+ ```
140
+ from pycocotools import mask as mask_utils
141
+ mask = mask_utils.decode(annotation["segmentation"])
142
+ ```
143
+
144
+ See [here](https://github.com/cocodataset/cocoapi/blob/master/PythonAPI/pycocotools/mask.py) for more instructions to manipulate masks stored in RLE format.
145
+
146
+ ## License
147
+
148
+ The model is licensed under the [Apache 2.0 license](LICENSE).
149
+
150
+ ## Contributing
151
+
152
+ See [contributing](CONTRIBUTING.md) and the [code of conduct](CODE_OF_CONDUCT.md).
153
+
154
+ ## Contributors
155
+
156
+ The Segment Anything project was made possible with the help of many contributors (alphabetical):
157
+
158
+ Aaron Adcock, Vaibhav Aggarwal, Morteza Behrooz, Cheng-Yang Fu, Ashley Gabriel, Ahuva Goldstand, Allen Goodman, Sumanth Gurram, Jiabo Hu, Somya Jain, Devansh Kukreja, Robert Kuo, Joshua Lane, Yanghao Li, Lilian Luong, Jitendra Malik, Mallika Malhotra, William Ngan, Omkar Parkhi, Nikhil Raina, Dirk Rowe, Neil Sejoor, Vanessa Stark, Bala Varadarajan, Bram Wasti, Zachary Winstrom
159
+
160
+ ## Citing Segment Anything
161
+
162
+ If you use SAM or SA-1B in your research, please use the following BibTeX entry.
163
+
164
+ ```
165
+ @article{kirillov2023segany,
166
+ title={Segment Anything},
167
+ author={Kirillov, Alexander and Mintun, Eric and Ravi, Nikhila and Mao, Hanzi and Rolland, Chloe and Gustafson, Laura and Xiao, Tete and Whitehead, Spencer and Berg, Alexander C. and Lo, Wan-Yen and Doll{\'a}r, Piotr and Girshick, Ross},
168
+ journal={arXiv:2304.02643},
169
+ year={2023}
170
+ }
171
+ ```
models/sam/linter.sh ADDED
@@ -0,0 +1,32 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ #!/bin/bash -e
2
+ # Copyright (c) Facebook, Inc. and its affiliates.
3
+
4
+ {
5
+ black --version | grep -E "23\." > /dev/null
6
+ } || {
7
+ echo "Linter requires 'black==23.*' !"
8
+ exit 1
9
+ }
10
+
11
+ ISORT_VERSION=$(isort --version-number)
12
+ if [[ "$ISORT_VERSION" != 5.12* ]]; then
13
+ echo "Linter requires isort==5.12.0 !"
14
+ exit 1
15
+ fi
16
+
17
+ echo "Running isort ..."
18
+ isort . --atomic
19
+
20
+ echo "Running black ..."
21
+ black -l 100 .
22
+
23
+ echo "Running flake8 ..."
24
+ if [ -x "$(command -v flake8)" ]; then
25
+ flake8 .
26
+ else
27
+ python3 -m flake8 .
28
+ fi
29
+
30
+ echo "Running mypy..."
31
+
32
+ mypy --exclude 'setup.py|notebooks' .
models/sam/notebooks/automatic_mask_generator_example.ipynb ADDED
The diff for this file is too large to render. See raw diff
 
models/sam/notebooks/images/dog.jpg ADDED
models/sam/notebooks/images/groceries.jpg ADDED

Git LFS Details

  • SHA256: 7073dfecb5a3ecafb6152124113163a0ea1c1c70f92999ec892b519eca63e3d3
  • Pointer size: 131 Bytes
  • Size of remote file: 168 kB
models/sam/notebooks/images/truck.jpg ADDED

Git LFS Details

  • SHA256: 941715e721c8864324a1425b445ea4dde0498b995c45ddce0141a58971c6ff99
  • Pointer size: 131 Bytes
  • Size of remote file: 271 kB
models/sam/notebooks/onnx_model_example.ipynb ADDED
@@ -0,0 +1,774 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ {
2
+ "cells": [
3
+ {
4
+ "cell_type": "code",
5
+ "execution_count": null,
6
+ "id": "901c8ef3",
7
+ "metadata": {},
8
+ "outputs": [],
9
+ "source": [
10
+ "# Copyright (c) Meta Platforms, Inc. and affiliates."
11
+ ]
12
+ },
13
+ {
14
+ "cell_type": "markdown",
15
+ "id": "1662bb7c",
16
+ "metadata": {},
17
+ "source": [
18
+ "# Produces masks from prompts using an ONNX model"
19
+ ]
20
+ },
21
+ {
22
+ "cell_type": "markdown",
23
+ "id": "7fcc21a0",
24
+ "metadata": {},
25
+ "source": [
26
+ "SAM's prompt encoder and mask decoder are very lightweight, which allows for efficient computation of a mask given user input. This notebook shows an example of how to export and use this lightweight component of the model in ONNX format, allowing it to run on a variety of platforms that support an ONNX runtime."
27
+ ]
28
+ },
29
+ {
30
+ "cell_type": "code",
31
+ "execution_count": 4,
32
+ "id": "86daff77",
33
+ "metadata": {},
34
+ "outputs": [
35
+ {
36
+ "data": {
37
+ "text/html": [
38
+ "\n",
39
+ "<a target=\"_blank\" href=\"https://colab.research.google.com/github/facebookresearch/segment-anything/blob/main/notebooks/onnx_model_example.ipynb\">\n",
40
+ " <img src=\"https://colab.research.google.com/assets/colab-badge.svg\" alt=\"Open In Colab\"/>\n",
41
+ "</a>\n"
42
+ ],
43
+ "text/plain": [
44
+ "<IPython.core.display.HTML object>"
45
+ ]
46
+ },
47
+ "metadata": {},
48
+ "output_type": "display_data"
49
+ }
50
+ ],
51
+ "source": [
52
+ "from IPython.display import display, HTML\n",
53
+ "display(HTML(\n",
54
+ "\"\"\"\n",
55
+ "<a target=\"_blank\" href=\"https://colab.research.google.com/github/facebookresearch/segment-anything/blob/main/notebooks/onnx_model_example.ipynb\">\n",
56
+ " <img src=\"https://colab.research.google.com/assets/colab-badge.svg\" alt=\"Open In Colab\"/>\n",
57
+ "</a>\n",
58
+ "\"\"\"\n",
59
+ "))"
60
+ ]
61
+ },
62
+ {
63
+ "cell_type": "markdown",
64
+ "id": "55ae4e00",
65
+ "metadata": {},
66
+ "source": [
67
+ "## Environment Set-up"
68
+ ]
69
+ },
70
+ {
71
+ "cell_type": "markdown",
72
+ "id": "109a5cc2",
73
+ "metadata": {},
74
+ "source": [
75
+ "If running locally using jupyter, first install `segment_anything` in your environment using the [installation instructions](https://github.com/facebookresearch/segment-anything#installation) in the repository. The latest stable versions of PyTorch and ONNX are recommended for this notebook. If running from Google Colab, set `using_colab=True` below and run the cell. In Colab, be sure to select 'GPU' under 'Edit'->'Notebook Settings'->'Hardware accelerator'."
76
+ ]
77
+ },
78
+ {
79
+ "cell_type": "code",
80
+ "execution_count": 5,
81
+ "id": "39b99fc4",
82
+ "metadata": {},
83
+ "outputs": [],
84
+ "source": [
85
+ "using_colab = False"
86
+ ]
87
+ },
88
+ {
89
+ "cell_type": "code",
90
+ "execution_count": 6,
91
+ "id": "296a69be",
92
+ "metadata": {},
93
+ "outputs": [],
94
+ "source": [
95
+ "if using_colab:\n",
96
+ " import torch\n",
97
+ " import torchvision\n",
98
+ " print(\"PyTorch version:\", torch.__version__)\n",
99
+ " print(\"Torchvision version:\", torchvision.__version__)\n",
100
+ " print(\"CUDA is available:\", torch.cuda.is_available())\n",
101
+ " import sys\n",
102
+ " !{sys.executable} -m pip install opencv-python matplotlib onnx onnxruntime\n",
103
+ " !{sys.executable} -m pip install 'git+https://github.com/facebookresearch/segment-anything.git'\n",
104
+ " \n",
105
+ " !mkdir images\n",
106
+ " !wget -P images https://raw.githubusercontent.com/facebookresearch/segment-anything/main/notebooks/images/truck.jpg\n",
107
+ " \n",
108
+ " !wget https://dl.fbaipublicfiles.com/segment_anything/sam_vit_h_4b8939.pth"
109
+ ]
110
+ },
111
+ {
112
+ "cell_type": "markdown",
113
+ "id": "dc4a58be",
114
+ "metadata": {},
115
+ "source": [
116
+ "## Set-up"
117
+ ]
118
+ },
119
+ {
120
+ "cell_type": "markdown",
121
+ "id": "42396e8d",
122
+ "metadata": {},
123
+ "source": [
124
+ "Note that this notebook requires both the `onnx` and `onnxruntime` optional dependencies, in addition to `opencv-python` and `matplotlib` for visualization."
125
+ ]
126
+ },
127
+ {
128
+ "cell_type": "code",
129
+ "execution_count": null,
130
+ "id": "2c712610",
131
+ "metadata": {},
132
+ "outputs": [],
133
+ "source": [
134
+ "import torch\n",
135
+ "import numpy as np\n",
136
+ "import cv2\n",
137
+ "import matplotlib.pyplot as plt\n",
138
+ "from segment_anything import sam_model_registry, SamPredictor\n",
139
+ "from segment_anything.utils.onnx import SamOnnxModel\n",
140
+ "\n",
141
+ "import onnxruntime\n",
142
+ "from onnxruntime.quantization import QuantType\n",
143
+ "from onnxruntime.quantization.quantize import quantize_dynamic"
144
+ ]
145
+ },
146
+ {
147
+ "cell_type": "code",
148
+ "execution_count": null,
149
+ "id": "f29441b9",
150
+ "metadata": {},
151
+ "outputs": [],
152
+ "source": [
153
+ "def show_mask(mask, ax):\n",
154
+ " color = np.array([30/255, 144/255, 255/255, 0.6])\n",
155
+ " h, w = mask.shape[-2:]\n",
156
+ " mask_image = mask.reshape(h, w, 1) * color.reshape(1, 1, -1)\n",
157
+ " ax.imshow(mask_image)\n",
158
+ " \n",
159
+ "def show_points(coords, labels, ax, marker_size=375):\n",
160
+ " pos_points = coords[labels==1]\n",
161
+ " neg_points = coords[labels==0]\n",
162
+ " ax.scatter(pos_points[:, 0], pos_points[:, 1], color='green', marker='*', s=marker_size, edgecolor='white', linewidth=1.25)\n",
163
+ " ax.scatter(neg_points[:, 0], neg_points[:, 1], color='red', marker='*', s=marker_size, edgecolor='white', linewidth=1.25) \n",
164
+ " \n",
165
+ "def show_box(box, ax):\n",
166
+ " x0, y0 = box[0], box[1]\n",
167
+ " w, h = box[2] - box[0], box[3] - box[1]\n",
168
+ " ax.add_patch(plt.Rectangle((x0, y0), w, h, edgecolor='green', facecolor=(0,0,0,0), lw=2)) "
169
+ ]
170
+ },
171
+ {
172
+ "cell_type": "markdown",
173
+ "id": "bd0f6b2b",
174
+ "metadata": {},
175
+ "source": [
176
+ "## Export an ONNX model"
177
+ ]
178
+ },
179
+ {
180
+ "cell_type": "markdown",
181
+ "id": "1540f719",
182
+ "metadata": {},
183
+ "source": [
184
+ "Set the path below to a SAM model checkpoint, then load the model. This will be needed to both export the model and to calculate embeddings for the model."
185
+ ]
186
+ },
187
+ {
188
+ "cell_type": "code",
189
+ "execution_count": null,
190
+ "id": "76fc53f4",
191
+ "metadata": {},
192
+ "outputs": [],
193
+ "source": [
194
+ "checkpoint = \"sam_vit_h_4b8939.pth\"\n",
195
+ "model_type = \"vit_h\""
196
+ ]
197
+ },
198
+ {
199
+ "cell_type": "code",
200
+ "execution_count": null,
201
+ "id": "11bfc8aa",
202
+ "metadata": {},
203
+ "outputs": [],
204
+ "source": [
205
+ "sam = sam_model_registry[model_type](checkpoint=checkpoint)"
206
+ ]
207
+ },
208
+ {
209
+ "cell_type": "markdown",
210
+ "id": "450c089c",
211
+ "metadata": {},
212
+ "source": [
213
+ "The script `segment-anything/scripts/export_onnx_model.py` can be used to export the necessary portion of SAM. Alternatively, run the following code to export an ONNX model. If you have already exported a model, set the path below and skip to the next section. Assure that the exported ONNX model aligns with the checkpoint and model type set above. This notebook expects the model was exported with the parameter `return_single_mask=True`."
214
+ ]
215
+ },
216
+ {
217
+ "cell_type": "code",
218
+ "execution_count": null,
219
+ "id": "38a8add8",
220
+ "metadata": {},
221
+ "outputs": [],
222
+ "source": [
223
+ "onnx_model_path = None # Set to use an already exported model, then skip to the next section."
224
+ ]
225
+ },
226
+ {
227
+ "cell_type": "code",
228
+ "execution_count": null,
229
+ "id": "7da638ba",
230
+ "metadata": {
231
+ "scrolled": false
232
+ },
233
+ "outputs": [],
234
+ "source": [
235
+ "import warnings\n",
236
+ "\n",
237
+ "onnx_model_path = \"sam_onnx_example.onnx\"\n",
238
+ "\n",
239
+ "onnx_model = SamOnnxModel(sam, return_single_mask=True)\n",
240
+ "\n",
241
+ "dynamic_axes = {\n",
242
+ " \"point_coords\": {1: \"num_points\"},\n",
243
+ " \"point_labels\": {1: \"num_points\"},\n",
244
+ "}\n",
245
+ "\n",
246
+ "embed_dim = sam.prompt_encoder.embed_dim\n",
247
+ "embed_size = sam.prompt_encoder.image_embedding_size\n",
248
+ "mask_input_size = [4 * x for x in embed_size]\n",
249
+ "dummy_inputs = {\n",
250
+ " \"image_embeddings\": torch.randn(1, embed_dim, *embed_size, dtype=torch.float),\n",
251
+ " \"point_coords\": torch.randint(low=0, high=1024, size=(1, 5, 2), dtype=torch.float),\n",
252
+ " \"point_labels\": torch.randint(low=0, high=4, size=(1, 5), dtype=torch.float),\n",
253
+ " \"mask_input\": torch.randn(1, 1, *mask_input_size, dtype=torch.float),\n",
254
+ " \"has_mask_input\": torch.tensor([1], dtype=torch.float),\n",
255
+ " \"orig_im_size\": torch.tensor([1500, 2250], dtype=torch.float),\n",
256
+ "}\n",
257
+ "output_names = [\"masks\", \"iou_predictions\", \"low_res_masks\"]\n",
258
+ "\n",
259
+ "with warnings.catch_warnings():\n",
260
+ " warnings.filterwarnings(\"ignore\", category=torch.jit.TracerWarning)\n",
261
+ " warnings.filterwarnings(\"ignore\", category=UserWarning)\n",
262
+ " with open(onnx_model_path, \"wb\") as f:\n",
263
+ " torch.onnx.export(\n",
264
+ " onnx_model,\n",
265
+ " tuple(dummy_inputs.values()),\n",
266
+ " f,\n",
267
+ " export_params=True,\n",
268
+ " verbose=False,\n",
269
+ " opset_version=17,\n",
270
+ " do_constant_folding=True,\n",
271
+ " input_names=list(dummy_inputs.keys()),\n",
272
+ " output_names=output_names,\n",
273
+ " dynamic_axes=dynamic_axes,\n",
274
+ " ) "
275
+ ]
276
+ },
277
+ {
278
+ "cell_type": "markdown",
279
+ "id": "c450cf1a",
280
+ "metadata": {},
281
+ "source": [
282
+ "If desired, the model can additionally be quantized and optimized. We find this improves web runtime significantly for negligible change in qualitative performance. Run the next cell to quantize the model, or skip to the next section otherwise."
283
+ ]
284
+ },
285
+ {
286
+ "cell_type": "code",
287
+ "execution_count": null,
288
+ "id": "235d39fe",
289
+ "metadata": {},
290
+ "outputs": [],
291
+ "source": [
292
+ "onnx_model_quantized_path = \"sam_onnx_quantized_example.onnx\"\n",
293
+ "quantize_dynamic(\n",
294
+ " model_input=onnx_model_path,\n",
295
+ " model_output=onnx_model_quantized_path,\n",
296
+ " optimize_model=True,\n",
297
+ " per_channel=False,\n",
298
+ " reduce_range=False,\n",
299
+ " weight_type=QuantType.QUInt8,\n",
300
+ ")\n",
301
+ "onnx_model_path = onnx_model_quantized_path"
302
+ ]
303
+ },
304
+ {
305
+ "cell_type": "markdown",
306
+ "id": "927a928b",
307
+ "metadata": {},
308
+ "source": [
309
+ "## Example Image"
310
+ ]
311
+ },
312
+ {
313
+ "cell_type": "code",
314
+ "execution_count": null,
315
+ "id": "6be6eb55",
316
+ "metadata": {},
317
+ "outputs": [],
318
+ "source": [
319
+ "image = cv2.imread('images/truck.jpg')\n",
320
+ "image = cv2.cvtColor(image, cv2.COLOR_BGR2RGB)"
321
+ ]
322
+ },
323
+ {
324
+ "cell_type": "code",
325
+ "execution_count": null,
326
+ "id": "b7e9a27a",
327
+ "metadata": {},
328
+ "outputs": [],
329
+ "source": [
330
+ "plt.figure(figsize=(10,10))\n",
331
+ "plt.imshow(image)\n",
332
+ "plt.axis('on')\n",
333
+ "plt.show()"
334
+ ]
335
+ },
336
+ {
337
+ "cell_type": "markdown",
338
+ "id": "027b177b",
339
+ "metadata": {},
340
+ "source": [
341
+ "## Using an ONNX model"
342
+ ]
343
+ },
344
+ {
345
+ "cell_type": "markdown",
346
+ "id": "778d4593",
347
+ "metadata": {},
348
+ "source": [
349
+ "Here as an example, we use `onnxruntime` in python on CPU to execute the ONNX model. However, any platform that supports an ONNX runtime could be used in principle. Launch the runtime session below:"
350
+ ]
351
+ },
352
+ {
353
+ "cell_type": "code",
354
+ "execution_count": null,
355
+ "id": "9689b1bf",
356
+ "metadata": {},
357
+ "outputs": [],
358
+ "source": [
359
+ "ort_session = onnxruntime.InferenceSession(onnx_model_path)"
360
+ ]
361
+ },
362
+ {
363
+ "cell_type": "markdown",
364
+ "id": "7708ead6",
365
+ "metadata": {},
366
+ "source": [
367
+ "To use the ONNX model, the image must first be pre-processed using the SAM image encoder. This is a heavier weight process best performed on GPU. SamPredictor can be used as normal, then `.get_image_embedding()` will retreive the intermediate features."
368
+ ]
369
+ },
370
+ {
371
+ "cell_type": "code",
372
+ "execution_count": null,
373
+ "id": "26e067b4",
374
+ "metadata": {},
375
+ "outputs": [],
376
+ "source": [
377
+ "sam.to(device='cuda')\n",
378
+ "predictor = SamPredictor(sam)"
379
+ ]
380
+ },
381
+ {
382
+ "cell_type": "code",
383
+ "execution_count": null,
384
+ "id": "7ad3f0d6",
385
+ "metadata": {},
386
+ "outputs": [],
387
+ "source": [
388
+ "predictor.set_image(image)"
389
+ ]
390
+ },
391
+ {
392
+ "cell_type": "code",
393
+ "execution_count": null,
394
+ "id": "8a6f0f07",
395
+ "metadata": {},
396
+ "outputs": [],
397
+ "source": [
398
+ "image_embedding = predictor.get_image_embedding().cpu().numpy()"
399
+ ]
400
+ },
401
+ {
402
+ "cell_type": "code",
403
+ "execution_count": null,
404
+ "id": "5e112f33",
405
+ "metadata": {},
406
+ "outputs": [],
407
+ "source": [
408
+ "image_embedding.shape"
409
+ ]
410
+ },
411
+ {
412
+ "cell_type": "markdown",
413
+ "id": "6337b654",
414
+ "metadata": {},
415
+ "source": [
416
+ "The ONNX model has a different input signature than `SamPredictor.predict`. The following inputs must all be supplied. Note the special cases for both point and mask inputs. All inputs are `np.float32`.\n",
417
+ "* `image_embeddings`: The image embedding from `predictor.get_image_embedding()`. Has a batch index of length 1.\n",
418
+ "* `point_coords`: Coordinates of sparse input prompts, corresponding to both point inputs and box inputs. Boxes are encoded using two points, one for the top-left corner and one for the bottom-right corner. *Coordinates must already be transformed to long-side 1024.* Has a batch index of length 1.\n",
419
+ "* `point_labels`: Labels for the sparse input prompts. 0 is a negative input point, 1 is a positive input point, 2 is a top-left box corner, 3 is a bottom-right box corner, and -1 is a padding point. *If there is no box input, a single padding point with label -1 and coordinates (0.0, 0.0) should be concatenated.*\n",
420
+ "* `mask_input`: A mask input to the model with shape 1x1x256x256. This must be supplied even if there is no mask input. In this case, it can just be zeros.\n",
421
+ "* `has_mask_input`: An indicator for the mask input. 1 indicates a mask input, 0 indicates no mask input.\n",
422
+ "* `orig_im_size`: The size of the input image in (H,W) format, before any transformation. \n",
423
+ "\n",
424
+ "Additionally, the ONNX model does not threshold the output mask logits. To obtain a binary mask, threshold at `sam.mask_threshold` (equal to 0.0)."
425
+ ]
426
+ },
427
+ {
428
+ "cell_type": "markdown",
429
+ "id": "bf5a9f55",
430
+ "metadata": {},
431
+ "source": [
432
+ "### Example point input"
433
+ ]
434
+ },
435
+ {
436
+ "cell_type": "code",
437
+ "execution_count": null,
438
+ "id": "1c0deef0",
439
+ "metadata": {},
440
+ "outputs": [],
441
+ "source": [
442
+ "input_point = np.array([[500, 375]])\n",
443
+ "input_label = np.array([1])"
444
+ ]
445
+ },
446
+ {
447
+ "cell_type": "markdown",
448
+ "id": "7256394c",
449
+ "metadata": {},
450
+ "source": [
451
+ "Add a batch index, concatenate a padding point, and transform."
452
+ ]
453
+ },
454
+ {
455
+ "cell_type": "code",
456
+ "execution_count": null,
457
+ "id": "4f69903e",
458
+ "metadata": {},
459
+ "outputs": [],
460
+ "source": [
461
+ "onnx_coord = np.concatenate([input_point, np.array([[0.0, 0.0]])], axis=0)[None, :, :]\n",
462
+ "onnx_label = np.concatenate([input_label, np.array([-1])], axis=0)[None, :].astype(np.float32)\n",
463
+ "\n",
464
+ "onnx_coord = predictor.transform.apply_coords(onnx_coord, image.shape[:2]).astype(np.float32)\n"
465
+ ]
466
+ },
467
+ {
468
+ "cell_type": "markdown",
469
+ "id": "b188dc53",
470
+ "metadata": {},
471
+ "source": [
472
+ "Create an empty mask input and an indicator for no mask."
473
+ ]
474
+ },
475
+ {
476
+ "cell_type": "code",
477
+ "execution_count": null,
478
+ "id": "5cb52bcf",
479
+ "metadata": {},
480
+ "outputs": [],
481
+ "source": [
482
+ "onnx_mask_input = np.zeros((1, 1, 256, 256), dtype=np.float32)\n",
483
+ "onnx_has_mask_input = np.zeros(1, dtype=np.float32)"
484
+ ]
485
+ },
486
+ {
487
+ "cell_type": "markdown",
488
+ "id": "a99c2cc5",
489
+ "metadata": {},
490
+ "source": [
491
+ "Package the inputs to run in the onnx model"
492
+ ]
493
+ },
494
+ {
495
+ "cell_type": "code",
496
+ "execution_count": null,
497
+ "id": "b1d7ea11",
498
+ "metadata": {},
499
+ "outputs": [],
500
+ "source": [
501
+ "ort_inputs = {\n",
502
+ " \"image_embeddings\": image_embedding,\n",
503
+ " \"point_coords\": onnx_coord,\n",
504
+ " \"point_labels\": onnx_label,\n",
505
+ " \"mask_input\": onnx_mask_input,\n",
506
+ " \"has_mask_input\": onnx_has_mask_input,\n",
507
+ " \"orig_im_size\": np.array(image.shape[:2], dtype=np.float32)\n",
508
+ "}"
509
+ ]
510
+ },
511
+ {
512
+ "cell_type": "markdown",
513
+ "id": "4b6409c9",
514
+ "metadata": {},
515
+ "source": [
516
+ "Predict a mask and threshold it."
517
+ ]
518
+ },
519
+ {
520
+ "cell_type": "code",
521
+ "execution_count": null,
522
+ "id": "dc4cc082",
523
+ "metadata": {
524
+ "scrolled": false
525
+ },
526
+ "outputs": [],
527
+ "source": [
528
+ "masks, _, low_res_logits = ort_session.run(None, ort_inputs)\n",
529
+ "masks = masks > predictor.model.mask_threshold"
530
+ ]
531
+ },
532
+ {
533
+ "cell_type": "code",
534
+ "execution_count": null,
535
+ "id": "d778a8fb",
536
+ "metadata": {},
537
+ "outputs": [],
538
+ "source": [
539
+ "masks.shape"
540
+ ]
541
+ },
542
+ {
543
+ "cell_type": "code",
544
+ "execution_count": null,
545
+ "id": "badb1175",
546
+ "metadata": {},
547
+ "outputs": [],
548
+ "source": [
549
+ "plt.figure(figsize=(10,10))\n",
550
+ "plt.imshow(image)\n",
551
+ "show_mask(masks, plt.gca())\n",
552
+ "show_points(input_point, input_label, plt.gca())\n",
553
+ "plt.axis('off')\n",
554
+ "plt.show() "
555
+ ]
556
+ },
557
+ {
558
+ "cell_type": "markdown",
559
+ "id": "1f1d4d15",
560
+ "metadata": {},
561
+ "source": [
562
+ "### Example mask input"
563
+ ]
564
+ },
565
+ {
566
+ "cell_type": "code",
567
+ "execution_count": null,
568
+ "id": "b319da82",
569
+ "metadata": {},
570
+ "outputs": [],
571
+ "source": [
572
+ "input_point = np.array([[500, 375], [1125, 625]])\n",
573
+ "input_label = np.array([1, 1])\n",
574
+ "\n",
575
+ "# Use the mask output from the previous run. It is already in the correct form for input to the ONNX model.\n",
576
+ "onnx_mask_input = low_res_logits"
577
+ ]
578
+ },
579
+ {
580
+ "cell_type": "markdown",
581
+ "id": "b1823b37",
582
+ "metadata": {},
583
+ "source": [
584
+ "Transform the points as in the previous example."
585
+ ]
586
+ },
587
+ {
588
+ "cell_type": "code",
589
+ "execution_count": null,
590
+ "id": "8885130f",
591
+ "metadata": {},
592
+ "outputs": [],
593
+ "source": [
594
+ "onnx_coord = np.concatenate([input_point, np.array([[0.0, 0.0]])], axis=0)[None, :, :]\n",
595
+ "onnx_label = np.concatenate([input_label, np.array([-1])], axis=0)[None, :].astype(np.float32)\n",
596
+ "\n",
597
+ "onnx_coord = predictor.transform.apply_coords(onnx_coord, image.shape[:2]).astype(np.float32)"
598
+ ]
599
+ },
600
+ {
601
+ "cell_type": "markdown",
602
+ "id": "28e47b69",
603
+ "metadata": {},
604
+ "source": [
605
+ "The `has_mask_input` indicator is now 1."
606
+ ]
607
+ },
608
+ {
609
+ "cell_type": "code",
610
+ "execution_count": null,
611
+ "id": "3ab4483a",
612
+ "metadata": {},
613
+ "outputs": [],
614
+ "source": [
615
+ "onnx_has_mask_input = np.ones(1, dtype=np.float32)"
616
+ ]
617
+ },
618
+ {
619
+ "cell_type": "markdown",
620
+ "id": "d3781955",
621
+ "metadata": {},
622
+ "source": [
623
+ "Package inputs, then predict and threshold the mask."
624
+ ]
625
+ },
626
+ {
627
+ "cell_type": "code",
628
+ "execution_count": null,
629
+ "id": "0c1ec096",
630
+ "metadata": {},
631
+ "outputs": [],
632
+ "source": [
633
+ "ort_inputs = {\n",
634
+ " \"image_embeddings\": image_embedding,\n",
635
+ " \"point_coords\": onnx_coord,\n",
636
+ " \"point_labels\": onnx_label,\n",
637
+ " \"mask_input\": onnx_mask_input,\n",
638
+ " \"has_mask_input\": onnx_has_mask_input,\n",
639
+ " \"orig_im_size\": np.array(image.shape[:2], dtype=np.float32)\n",
640
+ "}\n",
641
+ "\n",
642
+ "masks, _, _ = ort_session.run(None, ort_inputs)\n",
643
+ "masks = masks > predictor.model.mask_threshold"
644
+ ]
645
+ },
646
+ {
647
+ "cell_type": "code",
648
+ "execution_count": null,
649
+ "id": "1e36554b",
650
+ "metadata": {},
651
+ "outputs": [],
652
+ "source": [
653
+ "plt.figure(figsize=(10,10))\n",
654
+ "plt.imshow(image)\n",
655
+ "show_mask(masks, plt.gca())\n",
656
+ "show_points(input_point, input_label, plt.gca())\n",
657
+ "plt.axis('off')\n",
658
+ "plt.show() "
659
+ ]
660
+ },
661
+ {
662
+ "cell_type": "markdown",
663
+ "id": "2ef211d0",
664
+ "metadata": {},
665
+ "source": [
666
+ "### Example box and point input"
667
+ ]
668
+ },
669
+ {
670
+ "cell_type": "code",
671
+ "execution_count": null,
672
+ "id": "51e58d2e",
673
+ "metadata": {},
674
+ "outputs": [],
675
+ "source": [
676
+ "input_box = np.array([425, 600, 700, 875])\n",
677
+ "input_point = np.array([[575, 750]])\n",
678
+ "input_label = np.array([0])"
679
+ ]
680
+ },
681
+ {
682
+ "cell_type": "markdown",
683
+ "id": "6e119dcb",
684
+ "metadata": {},
685
+ "source": [
686
+ "Add a batch index, concatenate a box and point inputs, add the appropriate labels for the box corners, and transform. There is no padding point since the input includes a box input."
687
+ ]
688
+ },
689
+ {
690
+ "cell_type": "code",
691
+ "execution_count": null,
692
+ "id": "bfbe4911",
693
+ "metadata": {},
694
+ "outputs": [],
695
+ "source": [
696
+ "onnx_box_coords = input_box.reshape(2, 2)\n",
697
+ "onnx_box_labels = np.array([2,3])\n",
698
+ "\n",
699
+ "onnx_coord = np.concatenate([input_point, onnx_box_coords], axis=0)[None, :, :]\n",
700
+ "onnx_label = np.concatenate([input_label, onnx_box_labels], axis=0)[None, :].astype(np.float32)\n",
701
+ "\n",
702
+ "onnx_coord = predictor.transform.apply_coords(onnx_coord, image.shape[:2]).astype(np.float32)"
703
+ ]
704
+ },
705
+ {
706
+ "cell_type": "markdown",
707
+ "id": "65edabd2",
708
+ "metadata": {},
709
+ "source": [
710
+ "Package inputs, then predict and threshold the mask."
711
+ ]
712
+ },
713
+ {
714
+ "cell_type": "code",
715
+ "execution_count": null,
716
+ "id": "2abfba56",
717
+ "metadata": {},
718
+ "outputs": [],
719
+ "source": [
720
+ "onnx_mask_input = np.zeros((1, 1, 256, 256), dtype=np.float32)\n",
721
+ "onnx_has_mask_input = np.zeros(1, dtype=np.float32)\n",
722
+ "\n",
723
+ "ort_inputs = {\n",
724
+ " \"image_embeddings\": image_embedding,\n",
725
+ " \"point_coords\": onnx_coord,\n",
726
+ " \"point_labels\": onnx_label,\n",
727
+ " \"mask_input\": onnx_mask_input,\n",
728
+ " \"has_mask_input\": onnx_has_mask_input,\n",
729
+ " \"orig_im_size\": np.array(image.shape[:2], dtype=np.float32)\n",
730
+ "}\n",
731
+ "\n",
732
+ "masks, _, _ = ort_session.run(None, ort_inputs)\n",
733
+ "masks = masks > predictor.model.mask_threshold"
734
+ ]
735
+ },
736
+ {
737
+ "cell_type": "code",
738
+ "execution_count": null,
739
+ "id": "8301bf33",
740
+ "metadata": {},
741
+ "outputs": [],
742
+ "source": [
743
+ "plt.figure(figsize=(10, 10))\n",
744
+ "plt.imshow(image)\n",
745
+ "show_mask(masks[0], plt.gca())\n",
746
+ "show_box(input_box, plt.gca())\n",
747
+ "show_points(input_point, input_label, plt.gca())\n",
748
+ "plt.axis('off')\n",
749
+ "plt.show()"
750
+ ]
751
+ }
752
+ ],
753
+ "metadata": {
754
+ "kernelspec": {
755
+ "display_name": "Python 3 (ipykernel)",
756
+ "language": "python",
757
+ "name": "python3"
758
+ },
759
+ "language_info": {
760
+ "codemirror_mode": {
761
+ "name": "ipython",
762
+ "version": 3
763
+ },
764
+ "file_extension": ".py",
765
+ "mimetype": "text/x-python",
766
+ "name": "python",
767
+ "nbconvert_exporter": "python",
768
+ "pygments_lexer": "ipython3",
769
+ "version": "3.8.0"
770
+ }
771
+ },
772
+ "nbformat": 4,
773
+ "nbformat_minor": 5
774
+ }
models/sam/notebooks/predictor_example.ipynb ADDED
The diff for this file is too large to render. See raw diff
 
models/sam/scripts/amg.py ADDED
@@ -0,0 +1,238 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ # Copyright (c) Meta Platforms, Inc. and affiliates.
2
+ # All rights reserved.
3
+
4
+ # This source code is licensed under the license found in the
5
+ # LICENSE file in the root directory of this source tree.
6
+
7
+ import cv2 # type: ignore
8
+
9
+ from segment_anything import SamAutomaticMaskGenerator, sam_model_registry
10
+
11
+ import argparse
12
+ import json
13
+ import os
14
+ from typing import Any, Dict, List
15
+
16
+ parser = argparse.ArgumentParser(
17
+ description=(
18
+ "Runs automatic mask generation on an input image or directory of images, "
19
+ "and outputs masks as either PNGs or COCO-style RLEs. Requires open-cv, "
20
+ "as well as pycocotools if saving in RLE format."
21
+ )
22
+ )
23
+
24
+ parser.add_argument(
25
+ "--input",
26
+ type=str,
27
+ required=True,
28
+ help="Path to either a single input image or folder of images.",
29
+ )
30
+
31
+ parser.add_argument(
32
+ "--output",
33
+ type=str,
34
+ required=True,
35
+ help=(
36
+ "Path to the directory where masks will be output. Output will be either a folder "
37
+ "of PNGs per image or a single json with COCO-style masks."
38
+ ),
39
+ )
40
+
41
+ parser.add_argument(
42
+ "--model-type",
43
+ type=str,
44
+ required=True,
45
+ help="The type of model to load, in ['default', 'vit_h', 'vit_l', 'vit_b']",
46
+ )
47
+
48
+ parser.add_argument(
49
+ "--checkpoint",
50
+ type=str,
51
+ required=True,
52
+ help="The path to the SAM checkpoint to use for mask generation.",
53
+ )
54
+
55
+ parser.add_argument("--device", type=str, default="cuda", help="The device to run generation on.")
56
+
57
+ parser.add_argument(
58
+ "--convert-to-rle",
59
+ action="store_true",
60
+ help=(
61
+ "Save masks as COCO RLEs in a single json instead of as a folder of PNGs. "
62
+ "Requires pycocotools."
63
+ ),
64
+ )
65
+
66
+ amg_settings = parser.add_argument_group("AMG Settings")
67
+
68
+ amg_settings.add_argument(
69
+ "--points-per-side",
70
+ type=int,
71
+ default=None,
72
+ help="Generate masks by sampling a grid over the image with this many points to a side.",
73
+ )
74
+
75
+ amg_settings.add_argument(
76
+ "--points-per-batch",
77
+ type=int,
78
+ default=None,
79
+ help="How many input points to process simultaneously in one batch.",
80
+ )
81
+
82
+ amg_settings.add_argument(
83
+ "--pred-iou-thresh",
84
+ type=float,
85
+ default=None,
86
+ help="Exclude masks with a predicted score from the model that is lower than this threshold.",
87
+ )
88
+
89
+ amg_settings.add_argument(
90
+ "--stability-score-thresh",
91
+ type=float,
92
+ default=None,
93
+ help="Exclude masks with a stability score lower than this threshold.",
94
+ )
95
+
96
+ amg_settings.add_argument(
97
+ "--stability-score-offset",
98
+ type=float,
99
+ default=None,
100
+ help="Larger values perturb the mask more when measuring stability score.",
101
+ )
102
+
103
+ amg_settings.add_argument(
104
+ "--box-nms-thresh",
105
+ type=float,
106
+ default=None,
107
+ help="The overlap threshold for excluding a duplicate mask.",
108
+ )
109
+
110
+ amg_settings.add_argument(
111
+ "--crop-n-layers",
112
+ type=int,
113
+ default=None,
114
+ help=(
115
+ "If >0, mask generation is run on smaller crops of the image to generate more masks. "
116
+ "The value sets how many different scales to crop at."
117
+ ),
118
+ )
119
+
120
+ amg_settings.add_argument(
121
+ "--crop-nms-thresh",
122
+ type=float,
123
+ default=None,
124
+ help="The overlap threshold for excluding duplicate masks across different crops.",
125
+ )
126
+
127
+ amg_settings.add_argument(
128
+ "--crop-overlap-ratio",
129
+ type=int,
130
+ default=None,
131
+ help="Larger numbers mean image crops will overlap more.",
132
+ )
133
+
134
+ amg_settings.add_argument(
135
+ "--crop-n-points-downscale-factor",
136
+ type=int,
137
+ default=None,
138
+ help="The number of points-per-side in each layer of crop is reduced by this factor.",
139
+ )
140
+
141
+ amg_settings.add_argument(
142
+ "--min-mask-region-area",
143
+ type=int,
144
+ default=None,
145
+ help=(
146
+ "Disconnected mask regions or holes with area smaller than this value "
147
+ "in pixels are removed by postprocessing."
148
+ ),
149
+ )
150
+
151
+
152
+ def write_masks_to_folder(masks: List[Dict[str, Any]], path: str) -> None:
153
+ header = "id,area,bbox_x0,bbox_y0,bbox_w,bbox_h,point_input_x,point_input_y,predicted_iou,stability_score,crop_box_x0,crop_box_y0,crop_box_w,crop_box_h" # noqa
154
+ metadata = [header]
155
+ for i, mask_data in enumerate(masks):
156
+ mask = mask_data["segmentation"]
157
+ filename = f"{i}.png"
158
+ cv2.imwrite(os.path.join(path, filename), mask * 255)
159
+ mask_metadata = [
160
+ str(i),
161
+ str(mask_data["area"]),
162
+ *[str(x) for x in mask_data["bbox"]],
163
+ *[str(x) for x in mask_data["point_coords"][0]],
164
+ str(mask_data["predicted_iou"]),
165
+ str(mask_data["stability_score"]),
166
+ *[str(x) for x in mask_data["crop_box"]],
167
+ ]
168
+ row = ",".join(mask_metadata)
169
+ metadata.append(row)
170
+ metadata_path = os.path.join(path, "metadata.csv")
171
+ with open(metadata_path, "w") as f:
172
+ f.write("\n".join(metadata))
173
+
174
+ return
175
+
176
+
177
+ def get_amg_kwargs(args):
178
+ amg_kwargs = {
179
+ "points_per_side": args.points_per_side,
180
+ "points_per_batch": args.points_per_batch,
181
+ "pred_iou_thresh": args.pred_iou_thresh,
182
+ "stability_score_thresh": args.stability_score_thresh,
183
+ "stability_score_offset": args.stability_score_offset,
184
+ "box_nms_thresh": args.box_nms_thresh,
185
+ "crop_n_layers": args.crop_n_layers,
186
+ "crop_nms_thresh": args.crop_nms_thresh,
187
+ "crop_overlap_ratio": args.crop_overlap_ratio,
188
+ "crop_n_points_downscale_factor": args.crop_n_points_downscale_factor,
189
+ "min_mask_region_area": args.min_mask_region_area,
190
+ }
191
+ amg_kwargs = {k: v for k, v in amg_kwargs.items() if v is not None}
192
+ return amg_kwargs
193
+
194
+
195
+ def main(args: argparse.Namespace) -> None:
196
+ print("Loading model...")
197
+ sam = sam_model_registry[args.model_type](checkpoint=args.checkpoint)
198
+ _ = sam.to(device=args.device)
199
+ output_mode = "coco_rle" if args.convert_to_rle else "binary_mask"
200
+ amg_kwargs = get_amg_kwargs(args)
201
+ generator = SamAutomaticMaskGenerator(sam, output_mode=output_mode, **amg_kwargs)
202
+
203
+ if not os.path.isdir(args.input):
204
+ targets = [args.input]
205
+ else:
206
+ targets = [
207
+ f for f in os.listdir(args.input) if not os.path.isdir(os.path.join(args.input, f))
208
+ ]
209
+ targets = [os.path.join(args.input, f) for f in targets]
210
+
211
+ os.makedirs(args.output, exist_ok=True)
212
+
213
+ for t in targets:
214
+ print(f"Processing '{t}'...")
215
+ image = cv2.imread(t)
216
+ if image is None:
217
+ print(f"Could not load '{t}' as an image, skipping...")
218
+ continue
219
+ image = cv2.cvtColor(image, cv2.COLOR_BGR2RGB)
220
+
221
+ masks = generator.generate(image)
222
+
223
+ base = os.path.basename(t)
224
+ base = os.path.splitext(base)[0]
225
+ save_base = os.path.join(args.output, base)
226
+ if output_mode == "binary_mask":
227
+ os.makedirs(save_base, exist_ok=False)
228
+ write_masks_to_folder(masks, save_base)
229
+ else:
230
+ save_file = save_base + ".json"
231
+ with open(save_file, "w") as f:
232
+ json.dump(masks, f)
233
+ print("Done!")
234
+
235
+
236
+ if __name__ == "__main__":
237
+ args = parser.parse_args()
238
+ main(args)
models/sam/scripts/export_onnx_model.py ADDED
@@ -0,0 +1,201 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ # Copyright (c) Meta Platforms, Inc. and affiliates.
2
+ # All rights reserved.
3
+
4
+ # This source code is licensed under the license found in the
5
+ # LICENSE file in the root directory of this source tree.
6
+
7
+ import torch
8
+
9
+ from segment_anything import sam_model_registry
10
+ from segment_anything.utils.onnx import SamOnnxModel
11
+
12
+ import argparse
13
+ import warnings
14
+
15
+ try:
16
+ import onnxruntime # type: ignore
17
+
18
+ onnxruntime_exists = True
19
+ except ImportError:
20
+ onnxruntime_exists = False
21
+
22
+ parser = argparse.ArgumentParser(
23
+ description="Export the SAM prompt encoder and mask decoder to an ONNX model."
24
+ )
25
+
26
+ parser.add_argument(
27
+ "--checkpoint", type=str, required=True, help="The path to the SAM model checkpoint."
28
+ )
29
+
30
+ parser.add_argument(
31
+ "--output", type=str, required=True, help="The filename to save the ONNX model to."
32
+ )
33
+
34
+ parser.add_argument(
35
+ "--model-type",
36
+ type=str,
37
+ required=True,
38
+ help="In ['default', 'vit_h', 'vit_l', 'vit_b']. Which type of SAM model to export.",
39
+ )
40
+
41
+ parser.add_argument(
42
+ "--return-single-mask",
43
+ action="store_true",
44
+ help=(
45
+ "If true, the exported ONNX model will only return the best mask, "
46
+ "instead of returning multiple masks. For high resolution images "
47
+ "this can improve runtime when upscaling masks is expensive."
48
+ ),
49
+ )
50
+
51
+ parser.add_argument(
52
+ "--opset",
53
+ type=int,
54
+ default=17,
55
+ help="The ONNX opset version to use. Must be >=11",
56
+ )
57
+
58
+ parser.add_argument(
59
+ "--quantize-out",
60
+ type=str,
61
+ default=None,
62
+ help=(
63
+ "If set, will quantize the model and save it with this name. "
64
+ "Quantization is performed with quantize_dynamic from onnxruntime.quantization.quantize."
65
+ ),
66
+ )
67
+
68
+ parser.add_argument(
69
+ "--gelu-approximate",
70
+ action="store_true",
71
+ help=(
72
+ "Replace GELU operations with approximations using tanh. Useful "
73
+ "for some runtimes that have slow or unimplemented erf ops, used in GELU."
74
+ ),
75
+ )
76
+
77
+ parser.add_argument(
78
+ "--use-stability-score",
79
+ action="store_true",
80
+ help=(
81
+ "Replaces the model's predicted mask quality score with the stability "
82
+ "score calculated on the low resolution masks using an offset of 1.0. "
83
+ ),
84
+ )
85
+
86
+ parser.add_argument(
87
+ "--return-extra-metrics",
88
+ action="store_true",
89
+ help=(
90
+ "The model will return five results: (masks, scores, stability_scores, "
91
+ "areas, low_res_logits) instead of the usual three. This can be "
92
+ "significantly slower for high resolution outputs."
93
+ ),
94
+ )
95
+
96
+
97
+ def run_export(
98
+ model_type: str,
99
+ checkpoint: str,
100
+ output: str,
101
+ opset: int,
102
+ return_single_mask: bool,
103
+ gelu_approximate: bool = False,
104
+ use_stability_score: bool = False,
105
+ return_extra_metrics=False,
106
+ ):
107
+ print("Loading model...")
108
+ sam = sam_model_registry[model_type](checkpoint=checkpoint)
109
+
110
+ onnx_model = SamOnnxModel(
111
+ model=sam,
112
+ return_single_mask=return_single_mask,
113
+ use_stability_score=use_stability_score,
114
+ return_extra_metrics=return_extra_metrics,
115
+ )
116
+
117
+ if gelu_approximate:
118
+ for n, m in onnx_model.named_modules():
119
+ if isinstance(m, torch.nn.GELU):
120
+ m.approximate = "tanh"
121
+
122
+ dynamic_axes = {
123
+ "point_coords": {1: "num_points"},
124
+ "point_labels": {1: "num_points"},
125
+ }
126
+
127
+ embed_dim = sam.prompt_encoder.embed_dim
128
+ embed_size = sam.prompt_encoder.image_embedding_size
129
+ mask_input_size = [4 * x for x in embed_size]
130
+ dummy_inputs = {
131
+ "image_embeddings": torch.randn(1, embed_dim, *embed_size, dtype=torch.float),
132
+ "point_coords": torch.randint(low=0, high=1024, size=(1, 5, 2), dtype=torch.float),
133
+ "point_labels": torch.randint(low=0, high=4, size=(1, 5), dtype=torch.float),
134
+ "mask_input": torch.randn(1, 1, *mask_input_size, dtype=torch.float),
135
+ "has_mask_input": torch.tensor([1], dtype=torch.float),
136
+ "orig_im_size": torch.tensor([1500, 2250], dtype=torch.float),
137
+ }
138
+
139
+ _ = onnx_model(**dummy_inputs)
140
+
141
+ output_names = ["masks", "iou_predictions", "low_res_masks"]
142
+
143
+ with warnings.catch_warnings():
144
+ warnings.filterwarnings("ignore", category=torch.jit.TracerWarning)
145
+ warnings.filterwarnings("ignore", category=UserWarning)
146
+ with open(output, "wb") as f:
147
+ print(f"Exporting onnx model to {output}...")
148
+ torch.onnx.export(
149
+ onnx_model,
150
+ tuple(dummy_inputs.values()),
151
+ f,
152
+ export_params=True,
153
+ verbose=False,
154
+ opset_version=opset,
155
+ do_constant_folding=True,
156
+ input_names=list(dummy_inputs.keys()),
157
+ output_names=output_names,
158
+ dynamic_axes=dynamic_axes,
159
+ )
160
+
161
+ if onnxruntime_exists:
162
+ ort_inputs = {k: to_numpy(v) for k, v in dummy_inputs.items()}
163
+ # set cpu provider default
164
+ providers = ["CPUExecutionProvider"]
165
+ ort_session = onnxruntime.InferenceSession(output, providers=providers)
166
+ _ = ort_session.run(None, ort_inputs)
167
+ print("Model has successfully been run with ONNXRuntime.")
168
+
169
+
170
+ def to_numpy(tensor):
171
+ return tensor.cpu().numpy()
172
+
173
+
174
+ if __name__ == "__main__":
175
+ args = parser.parse_args()
176
+ run_export(
177
+ model_type=args.model_type,
178
+ checkpoint=args.checkpoint,
179
+ output=args.output,
180
+ opset=args.opset,
181
+ return_single_mask=args.return_single_mask,
182
+ gelu_approximate=args.gelu_approximate,
183
+ use_stability_score=args.use_stability_score,
184
+ return_extra_metrics=args.return_extra_metrics,
185
+ )
186
+
187
+ if args.quantize_out is not None:
188
+ assert onnxruntime_exists, "onnxruntime is required to quantize the model."
189
+ from onnxruntime.quantization import QuantType # type: ignore
190
+ from onnxruntime.quantization.quantize import quantize_dynamic # type: ignore
191
+
192
+ print(f"Quantizing model and writing to {args.quantize_out}...")
193
+ quantize_dynamic(
194
+ model_input=args.output,
195
+ model_output=args.quantize_out,
196
+ optimize_model=True,
197
+ per_channel=False,
198
+ reduce_range=False,
199
+ weight_type=QuantType.QUInt8,
200
+ )
201
+ print("Done!")
models/sam/segment_anything/__init__.py ADDED
@@ -0,0 +1,15 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ # Copyright (c) Meta Platforms, Inc. and affiliates.
2
+ # All rights reserved.
3
+
4
+ # This source code is licensed under the license found in the
5
+ # LICENSE file in the root directory of this source tree.
6
+
7
+ from .build_sam import (
8
+ build_sam,
9
+ build_sam_vit_h,
10
+ build_sam_vit_l,
11
+ build_sam_vit_b,
12
+ sam_model_registry,
13
+ )
14
+ from .predictor import SamPredictor
15
+ from .automatic_mask_generator import SamAutomaticMaskGenerator
models/sam/segment_anything/__pycache__/__init__.cpython-310.pyc ADDED
Binary file (449 Bytes). View file
 
models/sam/segment_anything/__pycache__/__init__.cpython-312.pyc ADDED
Binary file (474 Bytes). View file
 
models/sam/segment_anything/__pycache__/automatic_mask_generator.cpython-310.pyc ADDED
Binary file (11.5 kB). View file