yuhangzang commited on
Commit
a059c46
1 Parent(s): ea800cd
.gitignore ADDED
@@ -0,0 +1,169 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ # Initially taken from Github's Python gitignore file
2
+
3
+ # Byte-compiled / optimized / DLL files
4
+ __pycache__/
5
+ *.py[cod]
6
+ *$py.class
7
+
8
+ # C extensions
9
+ *.so
10
+
11
+ # tests and logs
12
+ tests/fixtures/cached_*_text.txt
13
+ logs/
14
+ lightning_logs/
15
+ lang_code_data/
16
+
17
+ # Distribution / packaging
18
+ .Python
19
+ build/
20
+ develop-eggs/
21
+ dist/
22
+ downloads/
23
+ eggs/
24
+ .eggs/
25
+ lib/
26
+ lib64/
27
+ parts/
28
+ sdist/
29
+ var/
30
+ wheels/
31
+ *.egg-info/
32
+ .installed.cfg
33
+ *.egg
34
+ MANIFEST
35
+
36
+ # PyInstaller
37
+ # Usually these files are written by a python script from a template
38
+ # before PyInstaller builds the exe, so as to inject date/other infos into it.
39
+ *.manifest
40
+ *.spec
41
+
42
+ # Installer logs
43
+ pip-log.txt
44
+ pip-delete-this-directory.txt
45
+
46
+ # Unit test / coverage reports
47
+ htmlcov/
48
+ .tox/
49
+ .nox/
50
+ .coverage
51
+ .coverage.*
52
+ .cache
53
+ nosetests.xml
54
+ coverage.xml
55
+ *.cover
56
+ .hypothesis/
57
+ .pytest_cache/
58
+
59
+ # Translations
60
+ *.mo
61
+ *.pot
62
+
63
+ # Django stuff:
64
+ *.log
65
+ local_settings.py
66
+ db.sqlite3
67
+
68
+ # Flask stuff:
69
+ instance/
70
+ .webassets-cache
71
+
72
+ # Scrapy stuff:
73
+ .scrapy
74
+
75
+ # Sphinx documentation
76
+ docs/_build/
77
+
78
+ # PyBuilder
79
+ target/
80
+
81
+ # Jupyter Notebook
82
+ .ipynb_checkpoints
83
+
84
+ # IPython
85
+ profile_default/
86
+ ipython_config.py
87
+
88
+ # pyenv
89
+ .python-version
90
+
91
+ # celery beat schedule file
92
+ celerybeat-schedule
93
+
94
+ # SageMath parsed files
95
+ *.sage.py
96
+
97
+ # Environments
98
+ .env
99
+ .venv
100
+ env/
101
+ venv/
102
+ ENV/
103
+ env.bak/
104
+ venv.bak/
105
+
106
+ # Spyder project settings
107
+ .spyderproject
108
+ .spyproject
109
+
110
+ # Rope project settings
111
+ .ropeproject
112
+
113
+ # mkdocs documentation
114
+ /site
115
+
116
+ # mypy
117
+ .mypy_cache/
118
+ .dmypy.json
119
+ dmypy.json
120
+
121
+ # Pyre type checker
122
+ .pyre/
123
+
124
+ # vscode
125
+ .vs
126
+ .vscode
127
+
128
+ # Pycharm
129
+ .idea
130
+
131
+ # TF code
132
+ tensorflow_code
133
+
134
+ # Models
135
+ proc_data
136
+
137
+ # examples
138
+ runs
139
+ /runs_old
140
+ /wandb
141
+ /examples/runs
142
+ /examples/**/*.args
143
+ /examples/rag/sweep
144
+
145
+ # data
146
+ /data
147
+ serialization_dir
148
+
149
+ # emacs
150
+ *.*~
151
+ debug.env
152
+
153
+ # vim
154
+ .*.swp
155
+
156
+ #ctags
157
+ tags
158
+
159
+ # pre-commit
160
+ .pre-commit*
161
+
162
+ # .lock
163
+ *.lock
164
+
165
+ # DS_Store (MacOS)
166
+ .DS_Store
167
+
168
+ # ruff
169
+ .ruff_cache
README.md CHANGED
@@ -1,8 +1,8 @@
1
  ---
2
  title: ContextDet Demo
3
- emoji: 📊
4
  colorFrom: gray
5
- colorTo: indigo
6
  sdk: gradio
7
  sdk_version: 3.32.0
8
  app_file: app.py
 
1
  ---
2
  title: ContextDet Demo
3
+ emoji: 📉
4
  colorFrom: gray
5
+ colorTo: red
6
  sdk: gradio
7
  sdk_version: 3.32.0
8
  app_file: app.py
app.py ADDED
@@ -0,0 +1,172 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ import os
2
+ os.system("python setup.py build develop --user")
3
+
4
+ import gradio as gr
5
+
6
+ from app_util import ContextDetDemo
7
+
8
+ header = '''
9
+ <div align=center>
10
+ <h1 style="font-weight: 900; margin-bottom: 7px;">
11
+ Contextual Object Detection with Multimodal Large Language Models
12
+ </h1>
13
+ </div>
14
+ '''
15
+
16
+ abstract = '''
17
+ 🤗 This is the official Gradio demo for <b>Contextual Object Detection with Multimodal Large Language Models</b>.
18
+
19
+ 🆒 Our goal is to promote object detection with better `context understanding` and enable `interactive feedback`
20
+ through `human language vocabulary`, all made possible by using multimodal large language models!
21
+
22
+ 🤝 This demo is still under construction. Your comments or suggestions are welcome!
23
+
24
+ ⚡ For faster inference without waiting in queue, you may duplicate the space and use the GPU setting:
25
+ <a href="https://huggingface.co/spaces/yuhangzang/ContextDet-Demo?duplicate=true">
26
+ <img style="margin-top: 0em; margin-bottom: 0em" src="https://bit.ly/3gLdBN6" alt="Duplicate Space"></a>
27
+ <p/>
28
+ '''
29
+
30
+ footer = r'''
31
+ 🦁 **Github Repo**
32
+ We would be grateful if you consider star our <a href="https://github.com/yuhangzang/ContextDET">github repo</a>
33
+
34
+ 📝 **Citation**
35
+ We would be grateful if you consider citing our work if you find it useful:
36
+ ```bibtex
37
+ @article{
38
+ }
39
+ ```
40
+
41
+ 📋 **License**
42
+ This project is licensed under
43
+ <a rel="license" href="https://github.com/sczhou/CodeFormer/blob/master/LICENSE">S-Lab License 1.0</a>.
44
+ Redistribution and use for non-commercial purposes should follow this license.
45
+
46
+ 📧 **Contact**
47
+ If you have any questions, please feel free to contact Yuhang Zang <b>(zang0012@ntu.edu.sg)</b>.
48
+ '''
49
+
50
+ css = '''
51
+ h1#title {
52
+ text-align: center;
53
+ }
54
+ '''
55
+
56
+ cloze_samples = [
57
+ ["main_4.jpg", "A teacher is helping a <mask> with her homework at desk."],
58
+ ["main_5.jpg", "A man crossing a busy <mask> with his <mask> up."],
59
+ ]
60
+
61
+
62
+ captioning_samples = [
63
+ ["main_1.jpg"],
64
+ ["main_2.jpg"],
65
+ ["main_4.jpg"],
66
+ ["main_6.jpeg"],
67
+ ]
68
+
69
+ qa_samples = [
70
+ ["main_5.jpg", "What is his career?"],
71
+ ["main_6.jpeg", "What are they doing?"],
72
+ ]
73
+
74
+ contextdet_model = ContextDetDemo('./ckpt.pth')
75
+
76
+
77
+ def inference_fn_select(image_input, text_input, task_button, history=[]):
78
+ return contextdet_model.forward(image_input, text_input, task_button, history)
79
+
80
+
81
+ def set_cloze_samples(example: list) -> dict:
82
+ return gr.Image.update(example[0]), gr.Textbox.update(example[1]), 'Cloze Test'
83
+
84
+
85
+ def set_captioning_samples(example: list) -> dict:
86
+ return gr.Image.update(example[0]), gr.Textbox.update(''), 'Captioning'
87
+
88
+
89
+ def set_qa_samples(example: list) -> dict:
90
+ return gr.Image.update(example[0]), gr.Textbox.update(example[1]), 'Question Answering'
91
+
92
+
93
+ with gr.Blocks(css=css, theme=gr.themes.Soft()) as demo:
94
+ gr.Markdown(header)
95
+ gr.Markdown(abstract)
96
+ state = gr.State([])
97
+
98
+ with gr.Row():
99
+ with gr.Column(scale=0.5, min_width=500):
100
+ image_input = gr.Image(type="pil", interactive=True, label="Upload an image 📁").style(height=250)
101
+ with gr.Column(scale=0.5, min_width=500):
102
+ chat_input = gr.Textbox(label="Type your text prompt ⤵️")
103
+ task_button = gr.Radio(label="Contextual Task type", interactive=True,
104
+ choices=['Cloze Test', 'Captioning', 'Question Answering'],
105
+ value='Cloze Test')
106
+ with gr.Row():
107
+ submit_button = gr.Button(value="🏃 Run", interactive=True, variant="primary")
108
+ clear_button = gr.Button(value="🔄 Clear", interactive=True)
109
+
110
+ with gr.Row():
111
+ with gr.Column(scale=0.5, min_width=500):
112
+ image_output = gr.Image(type='pil', interactive=False, label="Detection output")
113
+ with gr.Column(scale=0.5, min_width=500):
114
+ chat_output = gr.Chatbot(label="Text output").style(height=300)
115
+
116
+ with gr.Row():
117
+ with gr.Column(scale=0.33, min_width=330):
118
+ cloze_examples = gr.Dataset(
119
+ label='Contextual Cloze Test Examples',
120
+ components=[image_input, chat_input],
121
+ samples=cloze_samples,
122
+ )
123
+ with gr.Column(scale=0.33, min_width=330):
124
+ qa_examples = gr.Dataset(
125
+ label='Contextual Question Answering Examples',
126
+ components=[image_input, chat_input],
127
+ samples=qa_samples,
128
+ )
129
+ with gr.Column(scale=0.33, min_width=330):
130
+ captioning_examples = gr.Dataset(
131
+ label='Contextual Captioning Examples',
132
+ components=[image_input, ],
133
+ samples=captioning_samples,
134
+ )
135
+
136
+ submit_button.click(
137
+ inference_fn_select,
138
+ [image_input, chat_input, task_button, state],
139
+ [image_output, chat_output, state],
140
+ )
141
+ clear_button.click(
142
+ lambda: (None, None, "", [], [], 'Question Answering'),
143
+ [],
144
+ [image_input, image_output, chat_input, chat_output, state, task_button],
145
+ queue=False,
146
+ )
147
+ image_input.change(
148
+ lambda: (None, "", []),
149
+ [],
150
+ [image_output, chat_output, state],
151
+ queue=False,
152
+ )
153
+ cloze_examples.click(
154
+ fn=set_cloze_samples,
155
+ inputs=[cloze_examples],
156
+ outputs=[image_input, chat_input, task_button],
157
+ )
158
+ captioning_examples.click(
159
+ fn=set_captioning_samples,
160
+ inputs=[captioning_examples],
161
+ outputs=[image_input, chat_input, task_button],
162
+ )
163
+ qa_examples.click(
164
+ fn=set_qa_samples,
165
+ inputs=[qa_examples],
166
+ outputs=[image_input, chat_input, task_button],
167
+ )
168
+
169
+ gr.Markdown(footer)
170
+
171
+ demo.launch(enable_queue=True, share=False)
172
+ # demo.launch(enable_queue=True, share=True)
app_util.py ADDED
@@ -0,0 +1,201 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ import argparse
2
+ import io
3
+
4
+ import matplotlib.pyplot as plt
5
+ import numpy as np
6
+ import torch
7
+ import torchvision.transforms as T
8
+ from PIL import Image
9
+
10
+ from models.blip2_decoder import BLIP2Decoder
11
+ from models.deformable_detr.backbone import build_backbone
12
+ from models.contextdet_blip2 import ContextDET
13
+ from models.post_process import CondNMSPostProcess
14
+ from models.transformer import build_ov_transformer
15
+ from util.misc import nested_tensor_from_tensor_list
16
+
17
+
18
+ def parse_args() -> argparse.Namespace:
19
+ parser = argparse.ArgumentParser()
20
+ parser.add_argument('--device', type=str, default='cpu')
21
+
22
+ parser.add_argument('--lr_backbone_names', default=["backbone.0"], type=str, nargs='+')
23
+ parser.add_argument('--lr_backbone', default=2e-5, type=float)
24
+
25
+ parser.add_argument('--with_box_refine', default=True, action='store_false')
26
+ parser.add_argument('--two_stage', default=True, action='store_false')
27
+
28
+ # * Backbone
29
+ parser.add_argument('--backbone', default='resnet50', type=str,
30
+ help="Name of the convolutional backbone to use")
31
+ parser.add_argument('--dilation', action='store_true',
32
+ help="If true, we replace stride with dilation in the last convolutional block (DC5)")
33
+ parser.add_argument('--position_embedding', default='sine', type=str, choices=('sine', 'learned'),
34
+ help="Type of positional embedding to use on top of the image features")
35
+ parser.add_argument('--position_embedding_scale', default=2 * np.pi, type=float,
36
+ help="position / size * scale")
37
+ parser.add_argument('--num_feature_levels', default=5, type=int, help='number of feature levels')
38
+
39
+ # * Transformer
40
+ parser.add_argument('--enc_layers', default=6, type=int,
41
+ help="Number of encoding layers in the transformer")
42
+ parser.add_argument('--dec_layers', default=6, type=int,
43
+ help="Number of decoding layers in the transformer")
44
+ parser.add_argument('--dim_feedforward', default=2048, type=int,
45
+ help="Intermediate size of the feedforward layers in the transformer blocks")
46
+ parser.add_argument('--hidden_dim', default=256, type=int,
47
+ help="Size of the embeddings (dimension of the transformer)")
48
+ parser.add_argument('--dropout', default=0.0, type=float,
49
+ help="Dropout applied in the transformer")
50
+ parser.add_argument('--nheads', default=8, type=int,
51
+ help="Number of attention heads inside the transformer's attentions")
52
+ parser.add_argument('--num_queries', default=900, type=int,
53
+ help="Number of query slots")
54
+ parser.add_argument('--dec_n_points', default=4, type=int)
55
+ parser.add_argument('--enc_n_points', default=4, type=int)
56
+
57
+ # * Segmentation
58
+ parser.add_argument('--masks', action='store_true',
59
+ help="Train segmentation head if the flag is provided")
60
+
61
+ parser.add_argument('--assign_first_stage', default=True, action='store_false')
62
+ parser.add_argument('--assign_second_stage', default=True, action='store_false')
63
+
64
+ parser.add_argument('--name', default='ov')
65
+ parser.add_argument('--llm_name', default='bert-base-cased')
66
+
67
+ parser.add_argument('--resume', default='', type=str)
68
+ return parser.parse_args()
69
+
70
+
71
+ COLORS = [
72
+ [0.000, 0.447, 0.741],
73
+ [0.850, 0.325, 0.098],
74
+ [0.929, 0.694, 0.125],
75
+ [0.494, 0.184, 0.556],
76
+ [0.466, 0.674, 0.188],
77
+ [0.301, 0.745, 0.933]
78
+ ]
79
+
80
+
81
+ def fig2img(fig):
82
+ buf = io.BytesIO()
83
+ fig.savefig(buf)
84
+ buf.seek(0)
85
+ img = Image.open(buf)
86
+ return img
87
+
88
+
89
+ def visualize_prediction(pil_img, output_dict, threshold=0.7):
90
+ keep = output_dict["scores"] > threshold
91
+ boxes = output_dict["boxes"][keep].tolist()
92
+ scores = output_dict["scores"][keep].tolist()
93
+ keep_list = keep.nonzero().squeeze(1).numpy().tolist()
94
+ labels = [output_dict["names"][i] for i in keep_list]
95
+
96
+ plt.figure(figsize=(12.8, 8))
97
+ plt.imshow(pil_img)
98
+ ax = plt.gca()
99
+ colors = COLORS * 100
100
+ for score, (xmin, ymin, xmax, ymax), label, color in zip(scores, boxes, labels, colors):
101
+ ax.add_patch(plt.Rectangle((xmin, ymin), xmax - xmin, ymax - ymin, fill=False, color=color, linewidth=3))
102
+ ax.text(xmin, ymin, f"{label}: {score:0.2f}", fontsize=15, bbox=dict(facecolor="yellow", alpha=0.5))
103
+ plt.axis("off")
104
+ return fig2img(plt.gcf())
105
+
106
+
107
+ class ContextDetDemo():
108
+ def __init__(self, resume):
109
+ self.transform = T.Compose([
110
+ T.Resize(640),
111
+ T.ToTensor(),
112
+ T.Normalize([0.485, 0.456, 0.406], [0.229, 0.224, 0.225])
113
+ ])
114
+
115
+ args = parse_args()
116
+
117
+ args.llm_name = 'caption_coco_opt2.7b'
118
+ args.resume = resume
119
+
120
+ args.device = 'cuda' if torch.cuda.is_available() else 'cpu'
121
+ num_classes = 2
122
+ device = torch.device(args.device)
123
+
124
+ backbone = build_backbone(args)
125
+ transformer = build_ov_transformer(args)
126
+ llm_decoder = BLIP2Decoder(args.llm_name)
127
+ model = ContextDET(
128
+ backbone,
129
+ transformer,
130
+ num_classes=num_classes,
131
+ num_queries=args.num_queries,
132
+ num_feature_levels=args.num_feature_levels,
133
+ aux_loss=False,
134
+ with_box_refine=args.with_box_refine,
135
+ two_stage=args.two_stage,
136
+ llm_decoder=llm_decoder,
137
+ )
138
+ model = model.to(device)
139
+
140
+ checkpoint = torch.load(args.resume, map_location='cpu')
141
+ missing_keys, unexpected_keys = model.load_state_dict(checkpoint['model'], strict=False)
142
+ if len(missing_keys) > 0:
143
+ print('Missing Keys: {}'.format(missing_keys))
144
+ if len(unexpected_keys) > 0:
145
+ print('Unexpected Keys: {}'.format(unexpected_keys))
146
+
147
+ postprocessor = CondNMSPostProcess(args.num_queries)
148
+
149
+ self.model = model
150
+ self.model.eval()
151
+ self.postprocessor = postprocessor
152
+
153
+ def forward(self, image, text, task_button, history, threshold=0.3):
154
+ samples = self.transform(image).unsqueeze(0)
155
+ samples = nested_tensor_from_tensor_list(samples)
156
+ device = 'cuda' if torch.cuda.is_available() else 'cpu'
157
+ samples = samples.to(device)
158
+ vis = self.model.llm_decoder.vis_processors
159
+
160
+ if task_button == "Question Answering":
161
+ text = f"{text} Answer:"
162
+ history.append(text)
163
+ # prompt = " ".join(history)
164
+ prompt = text
165
+ elif task_button == "Captioning":
166
+ prompt = "A photo of"
167
+ else:
168
+ prompt = text
169
+
170
+ blip2_samples = {
171
+ 'image': vis['eval'](image)[None, :].to(device),
172
+ 'prompt': [prompt],
173
+ }
174
+ outputs = self.model(samples, blip2_samples, mask_infos=None, task_button=task_button)
175
+
176
+ mask_infos = outputs['mask_infos_pred']
177
+ pred_names = [list(mask_info.values()) for mask_info in mask_infos]
178
+ orig_target_sizes = torch.tensor([tuple(reversed(image.size))]).to(device)
179
+ results = self.postprocessor(outputs, orig_target_sizes, pred_names, mask_infos)[0]
180
+ image_vis = visualize_prediction(image, results, threshold)
181
+
182
+ out_text = outputs['output_text'][0]
183
+ if task_button == "Cloze Test":
184
+ history = []
185
+ chat = [
186
+ (prompt, out_text),
187
+ ]
188
+ elif task_button == "Captioning":
189
+ history = []
190
+ chat = [
191
+ ("please describe the image", out_text),
192
+ ]
193
+ elif task_button == "Question Answering":
194
+ history += [out_text]
195
+ chat = [
196
+ (history[i], history[i + 1]) for i in range(0, len(history) - 1, 2)
197
+ ]
198
+ else:
199
+ history = []
200
+ chat = []
201
+ return image_vis, chat, history
ckpt.pth ADDED
@@ -0,0 +1,3 @@
 
 
 
 
1
+ version https://git-lfs.github.com/spec/v1
2
+ oid sha256:5f6cdf5e828bf06684692fa99ead6e80d3ae1382f0f2b129cb39ee8675019deb
3
+ size 248034729
csrc/MsDeformAttn/ms_deform_attn.h ADDED
@@ -0,0 +1,64 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ /*!
2
+ **************************************************************************************************
3
+ * Deformable DETR
4
+ * Copyright (c) 2020 SenseTime. All Rights Reserved.
5
+ * Licensed under the Apache License, Version 2.0 [see LICENSE for details]
6
+ **************************************************************************************************
7
+ * Modified from https://github.com/chengdazhi/Deformable-Convolution-V2-PyTorch/tree/pytorch_1.0.0
8
+ **************************************************************************************************
9
+ */
10
+
11
+ #pragma once
12
+
13
+ #include "ms_deform_attn_cpu.h"
14
+
15
+ #ifdef WITH_CUDA
16
+ #include "ms_deform_attn_cuda.h"
17
+ #endif
18
+
19
+ namespace groundingdino {
20
+
21
+ at::Tensor
22
+ ms_deform_attn_forward(
23
+ const at::Tensor &value,
24
+ const at::Tensor &spatial_shapes,
25
+ const at::Tensor &level_start_index,
26
+ const at::Tensor &sampling_loc,
27
+ const at::Tensor &attn_weight,
28
+ const int im2col_step)
29
+ {
30
+ if (value.type().is_cuda())
31
+ {
32
+ #ifdef WITH_CUDA
33
+ return ms_deform_attn_cuda_forward(
34
+ value, spatial_shapes, level_start_index, sampling_loc, attn_weight, im2col_step);
35
+ #else
36
+ AT_ERROR("Not compiled with GPU support");
37
+ #endif
38
+ }
39
+ AT_ERROR("Not implemented on the CPU");
40
+ }
41
+
42
+ std::vector<at::Tensor>
43
+ ms_deform_attn_backward(
44
+ const at::Tensor &value,
45
+ const at::Tensor &spatial_shapes,
46
+ const at::Tensor &level_start_index,
47
+ const at::Tensor &sampling_loc,
48
+ const at::Tensor &attn_weight,
49
+ const at::Tensor &grad_output,
50
+ const int im2col_step)
51
+ {
52
+ if (value.type().is_cuda())
53
+ {
54
+ #ifdef WITH_CUDA
55
+ return ms_deform_attn_cuda_backward(
56
+ value, spatial_shapes, level_start_index, sampling_loc, attn_weight, grad_output, im2col_step);
57
+ #else
58
+ AT_ERROR("Not compiled with GPU support");
59
+ #endif
60
+ }
61
+ AT_ERROR("Not implemented on the CPU");
62
+ }
63
+
64
+ } // namespace groundingdino
csrc/MsDeformAttn/ms_deform_attn_cpu.cpp ADDED
@@ -0,0 +1,43 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ /*!
2
+ **************************************************************************************************
3
+ * Deformable DETR
4
+ * Copyright (c) 2020 SenseTime. All Rights Reserved.
5
+ * Licensed under the Apache License, Version 2.0 [see LICENSE for details]
6
+ **************************************************************************************************
7
+ * Modified from https://github.com/chengdazhi/Deformable-Convolution-V2-PyTorch/tree/pytorch_1.0.0
8
+ **************************************************************************************************
9
+ */
10
+
11
+ #include <vector>
12
+
13
+ #include <ATen/ATen.h>
14
+ #include <ATen/cuda/CUDAContext.h>
15
+
16
+ namespace groundingdino {
17
+
18
+ at::Tensor
19
+ ms_deform_attn_cpu_forward(
20
+ const at::Tensor &value,
21
+ const at::Tensor &spatial_shapes,
22
+ const at::Tensor &level_start_index,
23
+ const at::Tensor &sampling_loc,
24
+ const at::Tensor &attn_weight,
25
+ const int im2col_step)
26
+ {
27
+ AT_ERROR("Not implement on cpu");
28
+ }
29
+
30
+ std::vector<at::Tensor>
31
+ ms_deform_attn_cpu_backward(
32
+ const at::Tensor &value,
33
+ const at::Tensor &spatial_shapes,
34
+ const at::Tensor &level_start_index,
35
+ const at::Tensor &sampling_loc,
36
+ const at::Tensor &attn_weight,
37
+ const at::Tensor &grad_output,
38
+ const int im2col_step)
39
+ {
40
+ AT_ERROR("Not implement on cpu");
41
+ }
42
+
43
+ } // namespace groundingdino
csrc/MsDeformAttn/ms_deform_attn_cpu.h ADDED
@@ -0,0 +1,35 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ /*!
2
+ **************************************************************************************************
3
+ * Deformable DETR
4
+ * Copyright (c) 2020 SenseTime. All Rights Reserved.
5
+ * Licensed under the Apache License, Version 2.0 [see LICENSE for details]
6
+ **************************************************************************************************
7
+ * Modified from https://github.com/chengdazhi/Deformable-Convolution-V2-PyTorch/tree/pytorch_1.0.0
8
+ **************************************************************************************************
9
+ */
10
+
11
+ #pragma once
12
+ #include <torch/extension.h>
13
+
14
+ namespace groundingdino {
15
+
16
+ at::Tensor
17
+ ms_deform_attn_cpu_forward(
18
+ const at::Tensor &value,
19
+ const at::Tensor &spatial_shapes,
20
+ const at::Tensor &level_start_index,
21
+ const at::Tensor &sampling_loc,
22
+ const at::Tensor &attn_weight,
23
+ const int im2col_step);
24
+
25
+ std::vector<at::Tensor>
26
+ ms_deform_attn_cpu_backward(
27
+ const at::Tensor &value,
28
+ const at::Tensor &spatial_shapes,
29
+ const at::Tensor &level_start_index,
30
+ const at::Tensor &sampling_loc,
31
+ const at::Tensor &attn_weight,
32
+ const at::Tensor &grad_output,
33
+ const int im2col_step);
34
+
35
+ } // namespace groundingdino
csrc/MsDeformAttn/ms_deform_attn_cuda.cu ADDED
@@ -0,0 +1,156 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ /*!
2
+ **************************************************************************************************
3
+ * Deformable DETR
4
+ * Copyright (c) 2020 SenseTime. All Rights Reserved.
5
+ * Licensed under the Apache License, Version 2.0 [see LICENSE for details]
6
+ **************************************************************************************************
7
+ * Modified from https://github.com/chengdazhi/Deformable-Convolution-V2-PyTorch/tree/pytorch_1.0.0
8
+ **************************************************************************************************
9
+ */
10
+
11
+ #include <vector>
12
+ #include "ms_deform_im2col_cuda.cuh"
13
+
14
+ #include <ATen/ATen.h>
15
+ #include <ATen/cuda/CUDAContext.h>
16
+ #include <cuda.h>
17
+ #include <cuda_runtime.h>
18
+
19
+ namespace groundingdino {
20
+
21
+ at::Tensor ms_deform_attn_cuda_forward(
22
+ const at::Tensor &value,
23
+ const at::Tensor &spatial_shapes,
24
+ const at::Tensor &level_start_index,
25
+ const at::Tensor &sampling_loc,
26
+ const at::Tensor &attn_weight,
27
+ const int im2col_step)
28
+ {
29
+ AT_ASSERTM(value.is_contiguous(), "value tensor has to be contiguous");
30
+ AT_ASSERTM(spatial_shapes.is_contiguous(), "spatial_shapes tensor has to be contiguous");
31
+ AT_ASSERTM(level_start_index.is_contiguous(), "level_start_index tensor has to be contiguous");
32
+ AT_ASSERTM(sampling_loc.is_contiguous(), "sampling_loc tensor has to be contiguous");
33
+ AT_ASSERTM(attn_weight.is_contiguous(), "attn_weight tensor has to be contiguous");
34
+
35
+ AT_ASSERTM(value.type().is_cuda(), "value must be a CUDA tensor");
36
+ AT_ASSERTM(spatial_shapes.type().is_cuda(), "spatial_shapes must be a CUDA tensor");
37
+ AT_ASSERTM(level_start_index.type().is_cuda(), "level_start_index must be a CUDA tensor");
38
+ AT_ASSERTM(sampling_loc.type().is_cuda(), "sampling_loc must be a CUDA tensor");
39
+ AT_ASSERTM(attn_weight.type().is_cuda(), "attn_weight must be a CUDA tensor");
40
+
41
+ const int batch = value.size(0);
42
+ const int spatial_size = value.size(1);
43
+ const int num_heads = value.size(2);
44
+ const int channels = value.size(3);
45
+
46
+ const int num_levels = spatial_shapes.size(0);
47
+
48
+ const int num_query = sampling_loc.size(1);
49
+ const int num_point = sampling_loc.size(4);
50
+
51
+ const int im2col_step_ = std::min(batch, im2col_step);
52
+
53
+ AT_ASSERTM(batch % im2col_step_ == 0, "batch(%d) must divide im2col_step(%d)", batch, im2col_step_);
54
+
55
+ auto output = at::zeros({batch, num_query, num_heads, channels}, value.options());
56
+
57
+ const int batch_n = im2col_step_;
58
+ auto output_n = output.view({batch/im2col_step_, batch_n, num_query, num_heads, channels});
59
+ auto per_value_size = spatial_size * num_heads * channels;
60
+ auto per_sample_loc_size = num_query * num_heads * num_levels * num_point * 2;
61
+ auto per_attn_weight_size = num_query * num_heads * num_levels * num_point;
62
+ for (int n = 0; n < batch/im2col_step_; ++n)
63
+ {
64
+ auto columns = output_n.select(0, n);
65
+ AT_DISPATCH_FLOATING_TYPES(value.type(), "ms_deform_attn_forward_cuda", ([&] {
66
+ ms_deformable_im2col_cuda(at::cuda::getCurrentCUDAStream(),
67
+ value.data<scalar_t>() + n * im2col_step_ * per_value_size,
68
+ spatial_shapes.data<int64_t>(),
69
+ level_start_index.data<int64_t>(),
70
+ sampling_loc.data<scalar_t>() + n * im2col_step_ * per_sample_loc_size,
71
+ attn_weight.data<scalar_t>() + n * im2col_step_ * per_attn_weight_size,
72
+ batch_n, spatial_size, num_heads, channels, num_levels, num_query, num_point,
73
+ columns.data<scalar_t>());
74
+
75
+ }));
76
+ }
77
+
78
+ output = output.view({batch, num_query, num_heads*channels});
79
+
80
+ return output;
81
+ }
82
+
83
+
84
+ std::vector<at::Tensor> ms_deform_attn_cuda_backward(
85
+ const at::Tensor &value,
86
+ const at::Tensor &spatial_shapes,
87
+ const at::Tensor &level_start_index,
88
+ const at::Tensor &sampling_loc,
89
+ const at::Tensor &attn_weight,
90
+ const at::Tensor &grad_output,
91
+ const int im2col_step)
92
+ {
93
+
94
+ AT_ASSERTM(value.is_contiguous(), "value tensor has to be contiguous");
95
+ AT_ASSERTM(spatial_shapes.is_contiguous(), "spatial_shapes tensor has to be contiguous");
96
+ AT_ASSERTM(level_start_index.is_contiguous(), "level_start_index tensor has to be contiguous");
97
+ AT_ASSERTM(sampling_loc.is_contiguous(), "sampling_loc tensor has to be contiguous");
98
+ AT_ASSERTM(attn_weight.is_contiguous(), "attn_weight tensor has to be contiguous");
99
+ AT_ASSERTM(grad_output.is_contiguous(), "grad_output tensor has to be contiguous");
100
+
101
+ AT_ASSERTM(value.type().is_cuda(), "value must be a CUDA tensor");
102
+ AT_ASSERTM(spatial_shapes.type().is_cuda(), "spatial_shapes must be a CUDA tensor");
103
+ AT_ASSERTM(level_start_index.type().is_cuda(), "level_start_index must be a CUDA tensor");
104
+ AT_ASSERTM(sampling_loc.type().is_cuda(), "sampling_loc must be a CUDA tensor");
105
+ AT_ASSERTM(attn_weight.type().is_cuda(), "attn_weight must be a CUDA tensor");
106
+ AT_ASSERTM(grad_output.type().is_cuda(), "grad_output must be a CUDA tensor");
107
+
108
+ const int batch = value.size(0);
109
+ const int spatial_size = value.size(1);
110
+ const int num_heads = value.size(2);
111
+ const int channels = value.size(3);
112
+
113
+ const int num_levels = spatial_shapes.size(0);
114
+
115
+ const int num_query = sampling_loc.size(1);
116
+ const int num_point = sampling_loc.size(4);
117
+
118
+ const int im2col_step_ = std::min(batch, im2col_step);
119
+
120
+ AT_ASSERTM(batch % im2col_step_ == 0, "batch(%d) must divide im2col_step(%d)", batch, im2col_step_);
121
+
122
+ auto grad_value = at::zeros_like(value);
123
+ auto grad_sampling_loc = at::zeros_like(sampling_loc);
124
+ auto grad_attn_weight = at::zeros_like(attn_weight);
125
+
126
+ const int batch_n = im2col_step_;
127
+ auto per_value_size = spatial_size * num_heads * channels;
128
+ auto per_sample_loc_size = num_query * num_heads * num_levels * num_point * 2;
129
+ auto per_attn_weight_size = num_query * num_heads * num_levels * num_point;
130
+ auto grad_output_n = grad_output.view({batch/im2col_step_, batch_n, num_query, num_heads, channels});
131
+
132
+ for (int n = 0; n < batch/im2col_step_; ++n)
133
+ {
134
+ auto grad_output_g = grad_output_n.select(0, n);
135
+ AT_DISPATCH_FLOATING_TYPES(value.type(), "ms_deform_attn_backward_cuda", ([&] {
136
+ ms_deformable_col2im_cuda(at::cuda::getCurrentCUDAStream(),
137
+ grad_output_g.data<scalar_t>(),
138
+ value.data<scalar_t>() + n * im2col_step_ * per_value_size,
139
+ spatial_shapes.data<int64_t>(),
140
+ level_start_index.data<int64_t>(),
141
+ sampling_loc.data<scalar_t>() + n * im2col_step_ * per_sample_loc_size,
142
+ attn_weight.data<scalar_t>() + n * im2col_step_ * per_attn_weight_size,
143
+ batch_n, spatial_size, num_heads, channels, num_levels, num_query, num_point,
144
+ grad_value.data<scalar_t>() + n * im2col_step_ * per_value_size,
145
+ grad_sampling_loc.data<scalar_t>() + n * im2col_step_ * per_sample_loc_size,
146
+ grad_attn_weight.data<scalar_t>() + n * im2col_step_ * per_attn_weight_size);
147
+
148
+ }));
149
+ }
150
+
151
+ return {
152
+ grad_value, grad_sampling_loc, grad_attn_weight
153
+ };
154
+ }
155
+
156
+ } // namespace groundingdino
csrc/MsDeformAttn/ms_deform_attn_cuda.h ADDED
@@ -0,0 +1,33 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ /*!
2
+ **************************************************************************************************
3
+ * Deformable DETR
4
+ * Copyright (c) 2020 SenseTime. All Rights Reserved.
5
+ * Licensed under the Apache License, Version 2.0 [see LICENSE for details]
6
+ **************************************************************************************************
7
+ * Modified from https://github.com/chengdazhi/Deformable-Convolution-V2-PyTorch/tree/pytorch_1.0.0
8
+ **************************************************************************************************
9
+ */
10
+
11
+ #pragma once
12
+ #include <torch/extension.h>
13
+
14
+ namespace groundingdino {
15
+
16
+ at::Tensor ms_deform_attn_cuda_forward(
17
+ const at::Tensor &value,
18
+ const at::Tensor &spatial_shapes,
19
+ const at::Tensor &level_start_index,
20
+ const at::Tensor &sampling_loc,
21
+ const at::Tensor &attn_weight,
22
+ const int im2col_step);
23
+
24
+ std::vector<at::Tensor> ms_deform_attn_cuda_backward(
25
+ const at::Tensor &value,
26
+ const at::Tensor &spatial_shapes,
27
+ const at::Tensor &level_start_index,
28
+ const at::Tensor &sampling_loc,
29
+ const at::Tensor &attn_weight,
30
+ const at::Tensor &grad_output,
31
+ const int im2col_step);
32
+
33
+ } // namespace groundingdino
csrc/MsDeformAttn/ms_deform_im2col_cuda.cuh ADDED
@@ -0,0 +1,1327 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ /*!
2
+ **************************************************************************
3
+ * Deformable DETR
4
+ * Copyright (c) 2020 SenseTime. All Rights Reserved.
5
+ * Licensed under the Apache License, Version 2.0 [see LICENSE for details]
6
+ **************************************************************************
7
+ * Modified from DCN (https://github.com/msracver/Deformable-ConvNets)
8
+ * Copyright (c) 2018 Microsoft
9
+ **************************************************************************
10
+ */
11
+
12
+ #include <cstdio>
13
+ #include <algorithm>
14
+ #include <cstring>
15
+
16
+ #include <ATen/ATen.h>
17
+ #include <ATen/cuda/CUDAContext.h>
18
+
19
+ #include <THC/THCAtomics.cuh>
20
+
21
+ #define CUDA_KERNEL_LOOP(i, n) \
22
+ for (int i = blockIdx.x * blockDim.x + threadIdx.x; \
23
+ i < (n); \
24
+ i += blockDim.x * gridDim.x)
25
+
26
+ const int CUDA_NUM_THREADS = 1024;
27
+ inline int GET_BLOCKS(const int N, const int num_threads)
28
+ {
29
+ return (N + num_threads - 1) / num_threads;
30
+ }
31
+
32
+
33
+ template <typename scalar_t>
34
+ __device__ scalar_t ms_deform_attn_im2col_bilinear(const scalar_t* &bottom_data,
35
+ const int &height, const int &width, const int &nheads, const int &channels,
36
+ const scalar_t &h, const scalar_t &w, const int &m, const int &c)
37
+ {
38
+ const int h_low = floor(h);
39
+ const int w_low = floor(w);
40
+ const int h_high = h_low + 1;
41
+ const int w_high = w_low + 1;
42
+
43
+ const scalar_t lh = h - h_low;
44
+ const scalar_t lw = w - w_low;
45
+ const scalar_t hh = 1 - lh, hw = 1 - lw;
46
+
47
+ const int w_stride = nheads * channels;
48
+ const int h_stride = width * w_stride;
49
+ const int h_low_ptr_offset = h_low * h_stride;
50
+ const int h_high_ptr_offset = h_low_ptr_offset + h_stride;
51
+ const int w_low_ptr_offset = w_low * w_stride;
52
+ const int w_high_ptr_offset = w_low_ptr_offset + w_stride;
53
+ const int base_ptr = m * channels + c;
54
+
55
+ scalar_t v1 = 0;
56
+ if (h_low >= 0 && w_low >= 0)
57
+ {
58
+ const int ptr1 = h_low_ptr_offset + w_low_ptr_offset + base_ptr;
59
+ v1 = bottom_data[ptr1];
60
+ }
61
+ scalar_t v2 = 0;
62
+ if (h_low >= 0 && w_high <= width - 1)
63
+ {
64
+ const int ptr2 = h_low_ptr_offset + w_high_ptr_offset + base_ptr;
65
+ v2 = bottom_data[ptr2];
66
+ }
67
+ scalar_t v3 = 0;
68
+ if (h_high <= height - 1 && w_low >= 0)
69
+ {
70
+ const int ptr3 = h_high_ptr_offset + w_low_ptr_offset + base_ptr;
71
+ v3 = bottom_data[ptr3];
72
+ }
73
+ scalar_t v4 = 0;
74
+ if (h_high <= height - 1 && w_high <= width - 1)
75
+ {
76
+ const int ptr4 = h_high_ptr_offset + w_high_ptr_offset + base_ptr;
77
+ v4 = bottom_data[ptr4];
78
+ }
79
+
80
+ const scalar_t w1 = hh * hw, w2 = hh * lw, w3 = lh * hw, w4 = lh * lw;
81
+
82
+ const scalar_t val = (w1 * v1 + w2 * v2 + w3 * v3 + w4 * v4);
83
+ return val;
84
+ }
85
+
86
+
87
+ template <typename scalar_t>
88
+ __device__ void ms_deform_attn_col2im_bilinear(const scalar_t* &bottom_data,
89
+ const int &height, const int &width, const int &nheads, const int &channels,
90
+ const scalar_t &h, const scalar_t &w, const int &m, const int &c,
91
+ const scalar_t &top_grad,
92
+ const scalar_t &attn_weight,
93
+ scalar_t* &grad_value,
94
+ scalar_t* grad_sampling_loc,
95
+ scalar_t* grad_attn_weight)
96
+ {
97
+ const int h_low = floor(h);
98
+ const int w_low = floor(w);
99
+ const int h_high = h_low + 1;
100
+ const int w_high = w_low + 1;
101
+
102
+ const scalar_t lh = h - h_low;
103
+ const scalar_t lw = w - w_low;
104
+ const scalar_t hh = 1 - lh, hw = 1 - lw;
105
+
106
+ const int w_stride = nheads * channels;
107
+ const int h_stride = width * w_stride;
108
+ const int h_low_ptr_offset = h_low * h_stride;
109
+ const int h_high_ptr_offset = h_low_ptr_offset + h_stride;
110
+ const int w_low_ptr_offset = w_low * w_stride;
111
+ const int w_high_ptr_offset = w_low_ptr_offset + w_stride;
112
+ const int base_ptr = m * channels + c;
113
+
114
+ const scalar_t w1 = hh * hw, w2 = hh * lw, w3 = lh * hw, w4 = lh * lw;
115
+ const scalar_t top_grad_value = top_grad * attn_weight;
116
+ scalar_t grad_h_weight = 0, grad_w_weight = 0;
117
+
118
+ scalar_t v1 = 0;
119
+ if (h_low >= 0 && w_low >= 0)
120
+ {
121
+ const int ptr1 = h_low_ptr_offset + w_low_ptr_offset + base_ptr;
122
+ v1 = bottom_data[ptr1];
123
+ grad_h_weight -= hw * v1;
124
+ grad_w_weight -= hh * v1;
125
+ atomicAdd(grad_value+ptr1, w1*top_grad_value);
126
+ }
127
+ scalar_t v2 = 0;
128
+ if (h_low >= 0 && w_high <= width - 1)
129
+ {
130
+ const int ptr2 = h_low_ptr_offset + w_high_ptr_offset + base_ptr;
131
+ v2 = bottom_data[ptr2];
132
+ grad_h_weight -= lw * v2;
133
+ grad_w_weight += hh * v2;
134
+ atomicAdd(grad_value+ptr2, w2*top_grad_value);
135
+ }
136
+ scalar_t v3 = 0;
137
+ if (h_high <= height - 1 && w_low >= 0)
138
+ {
139
+ const int ptr3 = h_high_ptr_offset + w_low_ptr_offset + base_ptr;
140
+ v3 = bottom_data[ptr3];
141
+ grad_h_weight += hw * v3;
142
+ grad_w_weight -= lh * v3;
143
+ atomicAdd(grad_value+ptr3, w3*top_grad_value);
144
+ }
145
+ scalar_t v4 = 0;
146
+ if (h_high <= height - 1 && w_high <= width - 1)
147
+ {
148
+ const int ptr4 = h_high_ptr_offset + w_high_ptr_offset + base_ptr;
149
+ v4 = bottom_data[ptr4];
150
+ grad_h_weight += lw * v4;
151
+ grad_w_weight += lh * v4;
152
+ atomicAdd(grad_value+ptr4, w4*top_grad_value);
153
+ }
154
+
155
+ const scalar_t val = (w1 * v1 + w2 * v2 + w3 * v3 + w4 * v4);
156
+ *grad_attn_weight = top_grad * val;
157
+ *grad_sampling_loc = width * grad_w_weight * top_grad_value;
158
+ *(grad_sampling_loc + 1) = height * grad_h_weight * top_grad_value;
159
+ }
160
+
161
+
162
+ template <typename scalar_t>
163
+ __device__ void ms_deform_attn_col2im_bilinear_gm(const scalar_t* &bottom_data,
164
+ const int &height, const int &width, const int &nheads, const int &channels,
165
+ const scalar_t &h, const scalar_t &w, const int &m, const int &c,
166
+ const scalar_t &top_grad,
167
+ const scalar_t &attn_weight,
168
+ scalar_t* &grad_value,
169
+ scalar_t* grad_sampling_loc,
170
+ scalar_t* grad_attn_weight)
171
+ {
172
+ const int h_low = floor(h);
173
+ const int w_low = floor(w);
174
+ const int h_high = h_low + 1;
175
+ const int w_high = w_low + 1;
176
+
177
+ const scalar_t lh = h - h_low;
178
+ const scalar_t lw = w - w_low;
179
+ const scalar_t hh = 1 - lh, hw = 1 - lw;
180
+
181
+ const int w_stride = nheads * channels;
182
+ const int h_stride = width * w_stride;
183
+ const int h_low_ptr_offset = h_low * h_stride;
184
+ const int h_high_ptr_offset = h_low_ptr_offset + h_stride;
185
+ const int w_low_ptr_offset = w_low * w_stride;
186
+ const int w_high_ptr_offset = w_low_ptr_offset + w_stride;
187
+ const int base_ptr = m * channels + c;
188
+
189
+ const scalar_t w1 = hh * hw, w2 = hh * lw, w3 = lh * hw, w4 = lh * lw;
190
+ const scalar_t top_grad_value = top_grad * attn_weight;
191
+ scalar_t grad_h_weight = 0, grad_w_weight = 0;
192
+
193
+ scalar_t v1 = 0;
194
+ if (h_low >= 0 && w_low >= 0)
195
+ {
196
+ const int ptr1 = h_low_ptr_offset + w_low_ptr_offset + base_ptr;
197
+ v1 = bottom_data[ptr1];
198
+ grad_h_weight -= hw * v1;
199
+ grad_w_weight -= hh * v1;
200
+ atomicAdd(grad_value+ptr1, w1*top_grad_value);
201
+ }
202
+ scalar_t v2 = 0;
203
+ if (h_low >= 0 && w_high <= width - 1)
204
+ {
205
+ const int ptr2 = h_low_ptr_offset + w_high_ptr_offset + base_ptr;
206
+ v2 = bottom_data[ptr2];
207
+ grad_h_weight -= lw * v2;
208
+ grad_w_weight += hh * v2;
209
+ atomicAdd(grad_value+ptr2, w2*top_grad_value);
210
+ }
211
+ scalar_t v3 = 0;
212
+ if (h_high <= height - 1 && w_low >= 0)
213
+ {
214
+ const int ptr3 = h_high_ptr_offset + w_low_ptr_offset + base_ptr;
215
+ v3 = bottom_data[ptr3];
216
+ grad_h_weight += hw * v3;
217
+ grad_w_weight -= lh * v3;
218
+ atomicAdd(grad_value+ptr3, w3*top_grad_value);
219
+ }
220
+ scalar_t v4 = 0;
221
+ if (h_high <= height - 1 && w_high <= width - 1)
222
+ {
223
+ const int ptr4 = h_high_ptr_offset + w_high_ptr_offset + base_ptr;
224
+ v4 = bottom_data[ptr4];
225
+ grad_h_weight += lw * v4;
226
+ grad_w_weight += lh * v4;
227
+ atomicAdd(grad_value+ptr4, w4*top_grad_value);
228
+ }
229
+
230
+ const scalar_t val = (w1 * v1 + w2 * v2 + w3 * v3 + w4 * v4);
231
+ atomicAdd(grad_attn_weight, top_grad * val);
232
+ atomicAdd(grad_sampling_loc, width * grad_w_weight * top_grad_value);
233
+ atomicAdd(grad_sampling_loc + 1, height * grad_h_weight * top_grad_value);
234
+ }
235
+
236
+
237
+ template <typename scalar_t>
238
+ __global__ void ms_deformable_im2col_gpu_kernel(const int n,
239
+ const scalar_t *data_value,
240
+ const int64_t *data_spatial_shapes,
241
+ const int64_t *data_level_start_index,
242
+ const scalar_t *data_sampling_loc,
243
+ const scalar_t *data_attn_weight,
244
+ const int batch_size,
245
+ const int spatial_size,
246
+ const int num_heads,
247
+ const int channels,
248
+ const int num_levels,
249
+ const int num_query,
250
+ const int num_point,
251
+ scalar_t *data_col)
252
+ {
253
+ CUDA_KERNEL_LOOP(index, n)
254
+ {
255
+ int _temp = index;
256
+ const int c_col = _temp % channels;
257
+ _temp /= channels;
258
+ const int sampling_index = _temp;
259
+ const int m_col = _temp % num_heads;
260
+ _temp /= num_heads;
261
+ const int q_col = _temp % num_query;
262
+ _temp /= num_query;
263
+ const int b_col = _temp;
264
+
265
+ scalar_t *data_col_ptr = data_col + index;
266
+ int data_weight_ptr = sampling_index * num_levels * num_point;
267
+ int data_loc_w_ptr = data_weight_ptr << 1;
268
+ const int qid_stride = num_heads * channels;
269
+ const int data_value_ptr_init_offset = b_col * spatial_size * qid_stride;
270
+ scalar_t col = 0;
271
+
272
+ for (int l_col=0; l_col < num_levels; ++l_col)
273
+ {
274
+ const int level_start_id = data_level_start_index[l_col];
275
+ const int spatial_h_ptr = l_col << 1;
276
+ const int spatial_h = data_spatial_shapes[spatial_h_ptr];
277
+ const int spatial_w = data_spatial_shapes[spatial_h_ptr + 1];
278
+ const scalar_t *data_value_ptr = data_value + (data_value_ptr_init_offset + level_start_id * qid_stride);
279
+ for (int p_col=0; p_col < num_point; ++p_col)
280
+ {
281
+ const scalar_t loc_w = data_sampling_loc[data_loc_w_ptr];
282
+ const scalar_t loc_h = data_sampling_loc[data_loc_w_ptr + 1];
283
+ const scalar_t weight = data_attn_weight[data_weight_ptr];
284
+
285
+ const scalar_t h_im = loc_h * spatial_h - 0.5;
286
+ const scalar_t w_im = loc_w * spatial_w - 0.5;
287
+
288
+ if (h_im > -1 && w_im > -1 && h_im < spatial_h && w_im < spatial_w)
289
+ {
290
+ col += ms_deform_attn_im2col_bilinear(data_value_ptr, spatial_h, spatial_w, num_heads, channels, h_im, w_im, m_col, c_col) * weight;
291
+ }
292
+
293
+ data_weight_ptr += 1;
294
+ data_loc_w_ptr += 2;
295
+ }
296
+ }
297
+ *data_col_ptr = col;
298
+ }
299
+ }
300
+
301
+ template <typename scalar_t, unsigned int blockSize>
302
+ __global__ void ms_deformable_col2im_gpu_kernel_shm_blocksize_aware_reduce_v1(const int n,
303
+ const scalar_t *grad_col,
304
+ const scalar_t *data_value,
305
+ const int64_t *data_spatial_shapes,
306
+ const int64_t *data_level_start_index,
307
+ const scalar_t *data_sampling_loc,
308
+ const scalar_t *data_attn_weight,
309
+ const int batch_size,
310
+ const int spatial_size,
311
+ const int num_heads,
312
+ const int channels,
313
+ const int num_levels,
314
+ const int num_query,
315
+ const int num_point,
316
+ scalar_t *grad_value,
317
+ scalar_t *grad_sampling_loc,
318
+ scalar_t *grad_attn_weight)
319
+ {
320
+ CUDA_KERNEL_LOOP(index, n)
321
+ {
322
+ __shared__ scalar_t cache_grad_sampling_loc[blockSize * 2];
323
+ __shared__ scalar_t cache_grad_attn_weight[blockSize];
324
+ unsigned int tid = threadIdx.x;
325
+ int _temp = index;
326
+ const int c_col = _temp % channels;
327
+ _temp /= channels;
328
+ const int sampling_index = _temp;
329
+ const int m_col = _temp % num_heads;
330
+ _temp /= num_heads;
331
+ const int q_col = _temp % num_query;
332
+ _temp /= num_query;
333
+ const int b_col = _temp;
334
+
335
+ const scalar_t top_grad = grad_col[index];
336
+
337
+ int data_weight_ptr = sampling_index * num_levels * num_point;
338
+ int data_loc_w_ptr = data_weight_ptr << 1;
339
+ const int grad_sampling_ptr = data_weight_ptr;
340
+ grad_sampling_loc += grad_sampling_ptr << 1;
341
+ grad_attn_weight += grad_sampling_ptr;
342
+ const int grad_weight_stride = 1;
343
+ const int grad_loc_stride = 2;
344
+ const int qid_stride = num_heads * channels;
345
+ const int data_value_ptr_init_offset = b_col * spatial_size * qid_stride;
346
+
347
+ for (int l_col=0; l_col < num_levels; ++l_col)
348
+ {
349
+ const int level_start_id = data_level_start_index[l_col];
350
+ const int spatial_h_ptr = l_col << 1;
351
+ const int spatial_h = data_spatial_shapes[spatial_h_ptr];
352
+ const int spatial_w = data_spatial_shapes[spatial_h_ptr + 1];
353
+ const int value_ptr_offset = data_value_ptr_init_offset + level_start_id * qid_stride;
354
+ const scalar_t *data_value_ptr = data_value + value_ptr_offset;
355
+ scalar_t *grad_value_ptr = grad_value + value_ptr_offset;
356
+
357
+ for (int p_col=0; p_col < num_point; ++p_col)
358
+ {
359
+ const scalar_t loc_w = data_sampling_loc[data_loc_w_ptr];
360
+ const scalar_t loc_h = data_sampling_loc[data_loc_w_ptr + 1];
361
+ const scalar_t weight = data_attn_weight[data_weight_ptr];
362
+
363
+ const scalar_t h_im = loc_h * spatial_h - 0.5;
364
+ const scalar_t w_im = loc_w * spatial_w - 0.5;
365
+ *(cache_grad_sampling_loc+(threadIdx.x << 1)) = 0;
366
+ *(cache_grad_sampling_loc+((threadIdx.x << 1) + 1)) = 0;
367
+ *(cache_grad_attn_weight+threadIdx.x)=0;
368
+ if (h_im > -1 && w_im > -1 && h_im < spatial_h && w_im < spatial_w)
369
+ {
370
+ ms_deform_attn_col2im_bilinear(
371
+ data_value_ptr, spatial_h, spatial_w, num_heads, channels, h_im, w_im, m_col, c_col,
372
+ top_grad, weight, grad_value_ptr,
373
+ cache_grad_sampling_loc+(threadIdx.x << 1), cache_grad_attn_weight+threadIdx.x);
374
+ }
375
+
376
+ __syncthreads();
377
+ if (tid == 0)
378
+ {
379
+ scalar_t _grad_w=cache_grad_sampling_loc[0], _grad_h=cache_grad_sampling_loc[1], _grad_a=cache_grad_attn_weight[0];
380
+ int sid=2;
381
+ for (unsigned int tid = 1; tid < blockSize; ++tid)
382
+ {
383
+ _grad_w += cache_grad_sampling_loc[sid];
384
+ _grad_h += cache_grad_sampling_loc[sid + 1];
385
+ _grad_a += cache_grad_attn_weight[tid];
386
+ sid += 2;
387
+ }
388
+
389
+
390
+ *grad_sampling_loc = _grad_w;
391
+ *(grad_sampling_loc + 1) = _grad_h;
392
+ *grad_attn_weight = _grad_a;
393
+ }
394
+ __syncthreads();
395
+
396
+ data_weight_ptr += 1;
397
+ data_loc_w_ptr += 2;
398
+ grad_attn_weight += grad_weight_stride;
399
+ grad_sampling_loc += grad_loc_stride;
400
+ }
401
+ }
402
+ }
403
+ }
404
+
405
+
406
+ template <typename scalar_t, unsigned int blockSize>
407
+ __global__ void ms_deformable_col2im_gpu_kernel_shm_blocksize_aware_reduce_v2(const int n,
408
+ const scalar_t *grad_col,
409
+ const scalar_t *data_value,
410
+ const int64_t *data_spatial_shapes,
411
+ const int64_t *data_level_start_index,
412
+ const scalar_t *data_sampling_loc,
413
+ const scalar_t *data_attn_weight,
414
+ const int batch_size,
415
+ const int spatial_size,
416
+ const int num_heads,
417
+ const int channels,
418
+ const int num_levels,
419
+ const int num_query,
420
+ const int num_point,
421
+ scalar_t *grad_value,
422
+ scalar_t *grad_sampling_loc,
423
+ scalar_t *grad_attn_weight)
424
+ {
425
+ CUDA_KERNEL_LOOP(index, n)
426
+ {
427
+ __shared__ scalar_t cache_grad_sampling_loc[blockSize * 2];
428
+ __shared__ scalar_t cache_grad_attn_weight[blockSize];
429
+ unsigned int tid = threadIdx.x;
430
+ int _temp = index;
431
+ const int c_col = _temp % channels;
432
+ _temp /= channels;
433
+ const int sampling_index = _temp;
434
+ const int m_col = _temp % num_heads;
435
+ _temp /= num_heads;
436
+ const int q_col = _temp % num_query;
437
+ _temp /= num_query;
438
+ const int b_col = _temp;
439
+
440
+ const scalar_t top_grad = grad_col[index];
441
+
442
+ int data_weight_ptr = sampling_index * num_levels * num_point;
443
+ int data_loc_w_ptr = data_weight_ptr << 1;
444
+ const int grad_sampling_ptr = data_weight_ptr;
445
+ grad_sampling_loc += grad_sampling_ptr << 1;
446
+ grad_attn_weight += grad_sampling_ptr;
447
+ const int grad_weight_stride = 1;
448
+ const int grad_loc_stride = 2;
449
+ const int qid_stride = num_heads * channels;
450
+ const int data_value_ptr_init_offset = b_col * spatial_size * qid_stride;
451
+
452
+ for (int l_col=0; l_col < num_levels; ++l_col)
453
+ {
454
+ const int level_start_id = data_level_start_index[l_col];
455
+ const int spatial_h_ptr = l_col << 1;
456
+ const int spatial_h = data_spatial_shapes[spatial_h_ptr];
457
+ const int spatial_w = data_spatial_shapes[spatial_h_ptr + 1];
458
+ const int value_ptr_offset = data_value_ptr_init_offset + level_start_id * qid_stride;
459
+ const scalar_t *data_value_ptr = data_value + value_ptr_offset;
460
+ scalar_t *grad_value_ptr = grad_value + value_ptr_offset;
461
+
462
+ for (int p_col=0; p_col < num_point; ++p_col)
463
+ {
464
+ const scalar_t loc_w = data_sampling_loc[data_loc_w_ptr];
465
+ const scalar_t loc_h = data_sampling_loc[data_loc_w_ptr + 1];
466
+ const scalar_t weight = data_attn_weight[data_weight_ptr];
467
+
468
+ const scalar_t h_im = loc_h * spatial_h - 0.5;
469
+ const scalar_t w_im = loc_w * spatial_w - 0.5;
470
+ *(cache_grad_sampling_loc+(threadIdx.x << 1)) = 0;
471
+ *(cache_grad_sampling_loc+((threadIdx.x << 1) + 1)) = 0;
472
+ *(cache_grad_attn_weight+threadIdx.x)=0;
473
+ if (h_im > -1 && w_im > -1 && h_im < spatial_h && w_im < spatial_w)
474
+ {
475
+ ms_deform_attn_col2im_bilinear(
476
+ data_value_ptr, spatial_h, spatial_w, num_heads, channels, h_im, w_im, m_col, c_col,
477
+ top_grad, weight, grad_value_ptr,
478
+ cache_grad_sampling_loc+(threadIdx.x << 1), cache_grad_attn_weight+threadIdx.x);
479
+ }
480
+
481
+ __syncthreads();
482
+
483
+ for (unsigned int s=blockSize/2; s>0; s>>=1)
484
+ {
485
+ if (tid < s) {
486
+ const unsigned int xid1 = tid << 1;
487
+ const unsigned int xid2 = (tid + s) << 1;
488
+ cache_grad_attn_weight[tid] += cache_grad_attn_weight[tid + s];
489
+ cache_grad_sampling_loc[xid1] += cache_grad_sampling_loc[xid2];
490
+ cache_grad_sampling_loc[xid1 + 1] += cache_grad_sampling_loc[xid2 + 1];
491
+ }
492
+ __syncthreads();
493
+ }
494
+
495
+ if (tid == 0)
496
+ {
497
+ *grad_sampling_loc = cache_grad_sampling_loc[0];
498
+ *(grad_sampling_loc + 1) = cache_grad_sampling_loc[1];
499
+ *grad_attn_weight = cache_grad_attn_weight[0];
500
+ }
501
+ __syncthreads();
502
+
503
+ data_weight_ptr += 1;
504
+ data_loc_w_ptr += 2;
505
+ grad_attn_weight += grad_weight_stride;
506
+ grad_sampling_loc += grad_loc_stride;
507
+ }
508
+ }
509
+ }
510
+ }
511
+
512
+
513
+ template <typename scalar_t>
514
+ __global__ void ms_deformable_col2im_gpu_kernel_shm_reduce_v1(const int n,
515
+ const scalar_t *grad_col,
516
+ const scalar_t *data_value,
517
+ const int64_t *data_spatial_shapes,
518
+ const int64_t *data_level_start_index,
519
+ const scalar_t *data_sampling_loc,
520
+ const scalar_t *data_attn_weight,
521
+ const int batch_size,
522
+ const int spatial_size,
523
+ const int num_heads,
524
+ const int channels,
525
+ const int num_levels,
526
+ const int num_query,
527
+ const int num_point,
528
+ scalar_t *grad_value,
529
+ scalar_t *grad_sampling_loc,
530
+ scalar_t *grad_attn_weight)
531
+ {
532
+ CUDA_KERNEL_LOOP(index, n)
533
+ {
534
+ extern __shared__ int _s[];
535
+ scalar_t* cache_grad_sampling_loc = (scalar_t*)_s;
536
+ scalar_t* cache_grad_attn_weight = cache_grad_sampling_loc + 2 * blockDim.x;
537
+ unsigned int tid = threadIdx.x;
538
+ int _temp = index;
539
+ const int c_col = _temp % channels;
540
+ _temp /= channels;
541
+ const int sampling_index = _temp;
542
+ const int m_col = _temp % num_heads;
543
+ _temp /= num_heads;
544
+ const int q_col = _temp % num_query;
545
+ _temp /= num_query;
546
+ const int b_col = _temp;
547
+
548
+ const scalar_t top_grad = grad_col[index];
549
+
550
+ int data_weight_ptr = sampling_index * num_levels * num_point;
551
+ int data_loc_w_ptr = data_weight_ptr << 1;
552
+ const int grad_sampling_ptr = data_weight_ptr;
553
+ grad_sampling_loc += grad_sampling_ptr << 1;
554
+ grad_attn_weight += grad_sampling_ptr;
555
+ const int grad_weight_stride = 1;
556
+ const int grad_loc_stride = 2;
557
+ const int qid_stride = num_heads * channels;
558
+ const int data_value_ptr_init_offset = b_col * spatial_size * qid_stride;
559
+
560
+ for (int l_col=0; l_col < num_levels; ++l_col)
561
+ {
562
+ const int level_start_id = data_level_start_index[l_col];
563
+ const int spatial_h_ptr = l_col << 1;
564
+ const int spatial_h = data_spatial_shapes[spatial_h_ptr];
565
+ const int spatial_w = data_spatial_shapes[spatial_h_ptr + 1];
566
+ const int value_ptr_offset = data_value_ptr_init_offset + level_start_id * qid_stride;
567
+ const scalar_t *data_value_ptr = data_value + value_ptr_offset;
568
+ scalar_t *grad_value_ptr = grad_value + value_ptr_offset;
569
+
570
+ for (int p_col=0; p_col < num_point; ++p_col)
571
+ {
572
+ const scalar_t loc_w = data_sampling_loc[data_loc_w_ptr];
573
+ const scalar_t loc_h = data_sampling_loc[data_loc_w_ptr + 1];
574
+ const scalar_t weight = data_attn_weight[data_weight_ptr];
575
+
576
+ const scalar_t h_im = loc_h * spatial_h - 0.5;
577
+ const scalar_t w_im = loc_w * spatial_w - 0.5;
578
+ *(cache_grad_sampling_loc+(threadIdx.x << 1)) = 0;
579
+ *(cache_grad_sampling_loc+((threadIdx.x << 1) + 1)) = 0;
580
+ *(cache_grad_attn_weight+threadIdx.x)=0;
581
+ if (h_im > -1 && w_im > -1 && h_im < spatial_h && w_im < spatial_w)
582
+ {
583
+ ms_deform_attn_col2im_bilinear(
584
+ data_value_ptr, spatial_h, spatial_w, num_heads, channels, h_im, w_im, m_col, c_col,
585
+ top_grad, weight, grad_value_ptr,
586
+ cache_grad_sampling_loc+(threadIdx.x << 1), cache_grad_attn_weight+threadIdx.x);
587
+ }
588
+
589
+ __syncthreads();
590
+ if (tid == 0)
591
+ {
592
+ scalar_t _grad_w=cache_grad_sampling_loc[0], _grad_h=cache_grad_sampling_loc[1], _grad_a=cache_grad_attn_weight[0];
593
+ int sid=2;
594
+ for (unsigned int tid = 1; tid < blockDim.x; ++tid)
595
+ {
596
+ _grad_w += cache_grad_sampling_loc[sid];
597
+ _grad_h += cache_grad_sampling_loc[sid + 1];
598
+ _grad_a += cache_grad_attn_weight[tid];
599
+ sid += 2;
600
+ }
601
+
602
+
603
+ *grad_sampling_loc = _grad_w;
604
+ *(grad_sampling_loc + 1) = _grad_h;
605
+ *grad_attn_weight = _grad_a;
606
+ }
607
+ __syncthreads();
608
+
609
+ data_weight_ptr += 1;
610
+ data_loc_w_ptr += 2;
611
+ grad_attn_weight += grad_weight_stride;
612
+ grad_sampling_loc += grad_loc_stride;
613
+ }
614
+ }
615
+ }
616
+ }
617
+
618
+ template <typename scalar_t>
619
+ __global__ void ms_deformable_col2im_gpu_kernel_shm_reduce_v2(const int n,
620
+ const scalar_t *grad_col,
621
+ const scalar_t *data_value,
622
+ const int64_t *data_spatial_shapes,
623
+ const int64_t *data_level_start_index,
624
+ const scalar_t *data_sampling_loc,
625
+ const scalar_t *data_attn_weight,
626
+ const int batch_size,
627
+ const int spatial_size,
628
+ const int num_heads,
629
+ const int channels,
630
+ const int num_levels,
631
+ const int num_query,
632
+ const int num_point,
633
+ scalar_t *grad_value,
634
+ scalar_t *grad_sampling_loc,
635
+ scalar_t *grad_attn_weight)
636
+ {
637
+ CUDA_KERNEL_LOOP(index, n)
638
+ {
639
+ extern __shared__ int _s[];
640
+ scalar_t* cache_grad_sampling_loc = (scalar_t*)_s;
641
+ scalar_t* cache_grad_attn_weight = cache_grad_sampling_loc + 2 * blockDim.x;
642
+ unsigned int tid = threadIdx.x;
643
+ int _temp = index;
644
+ const int c_col = _temp % channels;
645
+ _temp /= channels;
646
+ const int sampling_index = _temp;
647
+ const int m_col = _temp % num_heads;
648
+ _temp /= num_heads;
649
+ const int q_col = _temp % num_query;
650
+ _temp /= num_query;
651
+ const int b_col = _temp;
652
+
653
+ const scalar_t top_grad = grad_col[index];
654
+
655
+ int data_weight_ptr = sampling_index * num_levels * num_point;
656
+ int data_loc_w_ptr = data_weight_ptr << 1;
657
+ const int grad_sampling_ptr = data_weight_ptr;
658
+ grad_sampling_loc += grad_sampling_ptr << 1;
659
+ grad_attn_weight += grad_sampling_ptr;
660
+ const int grad_weight_stride = 1;
661
+ const int grad_loc_stride = 2;
662
+ const int qid_stride = num_heads * channels;
663
+ const int data_value_ptr_init_offset = b_col * spatial_size * qid_stride;
664
+
665
+ for (int l_col=0; l_col < num_levels; ++l_col)
666
+ {
667
+ const int level_start_id = data_level_start_index[l_col];
668
+ const int spatial_h_ptr = l_col << 1;
669
+ const int spatial_h = data_spatial_shapes[spatial_h_ptr];
670
+ const int spatial_w = data_spatial_shapes[spatial_h_ptr + 1];
671
+ const int value_ptr_offset = data_value_ptr_init_offset + level_start_id * qid_stride;
672
+ const scalar_t *data_value_ptr = data_value + value_ptr_offset;
673
+ scalar_t *grad_value_ptr = grad_value + value_ptr_offset;
674
+
675
+ for (int p_col=0; p_col < num_point; ++p_col)
676
+ {
677
+ const scalar_t loc_w = data_sampling_loc[data_loc_w_ptr];
678
+ const scalar_t loc_h = data_sampling_loc[data_loc_w_ptr + 1];
679
+ const scalar_t weight = data_attn_weight[data_weight_ptr];
680
+
681
+ const scalar_t h_im = loc_h * spatial_h - 0.5;
682
+ const scalar_t w_im = loc_w * spatial_w - 0.5;
683
+ *(cache_grad_sampling_loc+(threadIdx.x << 1)) = 0;
684
+ *(cache_grad_sampling_loc+((threadIdx.x << 1) + 1)) = 0;
685
+ *(cache_grad_attn_weight+threadIdx.x)=0;
686
+ if (h_im > -1 && w_im > -1 && h_im < spatial_h && w_im < spatial_w)
687
+ {
688
+ ms_deform_attn_col2im_bilinear(
689
+ data_value_ptr, spatial_h, spatial_w, num_heads, channels, h_im, w_im, m_col, c_col,
690
+ top_grad, weight, grad_value_ptr,
691
+ cache_grad_sampling_loc+(threadIdx.x << 1), cache_grad_attn_weight+threadIdx.x);
692
+ }
693
+
694
+ __syncthreads();
695
+
696
+ for (unsigned int s=blockDim.x/2, spre=blockDim.x; s>0; s>>=1, spre>>=1)
697
+ {
698
+ if (tid < s) {
699
+ const unsigned int xid1 = tid << 1;
700
+ const unsigned int xid2 = (tid + s) << 1;
701
+ cache_grad_attn_weight[tid] += cache_grad_attn_weight[tid + s];
702
+ cache_grad_sampling_loc[xid1] += cache_grad_sampling_loc[xid2];
703
+ cache_grad_sampling_loc[xid1 + 1] += cache_grad_sampling_loc[xid2 + 1];
704
+ if (tid + (s << 1) < spre)
705
+ {
706
+ cache_grad_attn_weight[tid] += cache_grad_attn_weight[tid + (s << 1)];
707
+ cache_grad_sampling_loc[xid1] += cache_grad_sampling_loc[xid2 + (s << 1)];
708
+ cache_grad_sampling_loc[xid1 + 1] += cache_grad_sampling_loc[xid2 + 1 + (s << 1)];
709
+ }
710
+ }
711
+ __syncthreads();
712
+ }
713
+
714
+ if (tid == 0)
715
+ {
716
+ *grad_sampling_loc = cache_grad_sampling_loc[0];
717
+ *(grad_sampling_loc + 1) = cache_grad_sampling_loc[1];
718
+ *grad_attn_weight = cache_grad_attn_weight[0];
719
+ }
720
+ __syncthreads();
721
+
722
+ data_weight_ptr += 1;
723
+ data_loc_w_ptr += 2;
724
+ grad_attn_weight += grad_weight_stride;
725
+ grad_sampling_loc += grad_loc_stride;
726
+ }
727
+ }
728
+ }
729
+ }
730
+
731
+ template <typename scalar_t>
732
+ __global__ void ms_deformable_col2im_gpu_kernel_shm_reduce_v2_multi_blocks(const int n,
733
+ const scalar_t *grad_col,
734
+ const scalar_t *data_value,
735
+ const int64_t *data_spatial_shapes,
736
+ const int64_t *data_level_start_index,
737
+ const scalar_t *data_sampling_loc,
738
+ const scalar_t *data_attn_weight,
739
+ const int batch_size,
740
+ const int spatial_size,
741
+ const int num_heads,
742
+ const int channels,
743
+ const int num_levels,
744
+ const int num_query,
745
+ const int num_point,
746
+ scalar_t *grad_value,
747
+ scalar_t *grad_sampling_loc,
748
+ scalar_t *grad_attn_weight)
749
+ {
750
+ CUDA_KERNEL_LOOP(index, n)
751
+ {
752
+ extern __shared__ int _s[];
753
+ scalar_t* cache_grad_sampling_loc = (scalar_t*)_s;
754
+ scalar_t* cache_grad_attn_weight = cache_grad_sampling_loc + 2 * blockDim.x;
755
+ unsigned int tid = threadIdx.x;
756
+ int _temp = index;
757
+ const int c_col = _temp % channels;
758
+ _temp /= channels;
759
+ const int sampling_index = _temp;
760
+ const int m_col = _temp % num_heads;
761
+ _temp /= num_heads;
762
+ const int q_col = _temp % num_query;
763
+ _temp /= num_query;
764
+ const int b_col = _temp;
765
+
766
+ const scalar_t top_grad = grad_col[index];
767
+
768
+ int data_weight_ptr = sampling_index * num_levels * num_point;
769
+ int data_loc_w_ptr = data_weight_ptr << 1;
770
+ const int grad_sampling_ptr = data_weight_ptr;
771
+ grad_sampling_loc += grad_sampling_ptr << 1;
772
+ grad_attn_weight += grad_sampling_ptr;
773
+ const int grad_weight_stride = 1;
774
+ const int grad_loc_stride = 2;
775
+ const int qid_stride = num_heads * channels;
776
+ const int data_value_ptr_init_offset = b_col * spatial_size * qid_stride;
777
+
778
+ for (int l_col=0; l_col < num_levels; ++l_col)
779
+ {
780
+ const int level_start_id = data_level_start_index[l_col];
781
+ const int spatial_h_ptr = l_col << 1;
782
+ const int spatial_h = data_spatial_shapes[spatial_h_ptr];
783
+ const int spatial_w = data_spatial_shapes[spatial_h_ptr + 1];
784
+ const int value_ptr_offset = data_value_ptr_init_offset + level_start_id * qid_stride;
785
+ const scalar_t *data_value_ptr = data_value + value_ptr_offset;
786
+ scalar_t *grad_value_ptr = grad_value + value_ptr_offset;
787
+
788
+ for (int p_col=0; p_col < num_point; ++p_col)
789
+ {
790
+ const scalar_t loc_w = data_sampling_loc[data_loc_w_ptr];
791
+ const scalar_t loc_h = data_sampling_loc[data_loc_w_ptr + 1];
792
+ const scalar_t weight = data_attn_weight[data_weight_ptr];
793
+
794
+ const scalar_t h_im = loc_h * spatial_h - 0.5;
795
+ const scalar_t w_im = loc_w * spatial_w - 0.5;
796
+ *(cache_grad_sampling_loc+(threadIdx.x << 1)) = 0;
797
+ *(cache_grad_sampling_loc+((threadIdx.x << 1) + 1)) = 0;
798
+ *(cache_grad_attn_weight+threadIdx.x)=0;
799
+ if (h_im > -1 && w_im > -1 && h_im < spatial_h && w_im < spatial_w)
800
+ {
801
+ ms_deform_attn_col2im_bilinear(
802
+ data_value_ptr, spatial_h, spatial_w, num_heads, channels, h_im, w_im, m_col, c_col,
803
+ top_grad, weight, grad_value_ptr,
804
+ cache_grad_sampling_loc+(threadIdx.x << 1), cache_grad_attn_weight+threadIdx.x);
805
+ }
806
+
807
+ __syncthreads();
808
+
809
+ for (unsigned int s=blockDim.x/2, spre=blockDim.x; s>0; s>>=1, spre>>=1)
810
+ {
811
+ if (tid < s) {
812
+ const unsigned int xid1 = tid << 1;
813
+ const unsigned int xid2 = (tid + s) << 1;
814
+ cache_grad_attn_weight[tid] += cache_grad_attn_weight[tid + s];
815
+ cache_grad_sampling_loc[xid1] += cache_grad_sampling_loc[xid2];
816
+ cache_grad_sampling_loc[xid1 + 1] += cache_grad_sampling_loc[xid2 + 1];
817
+ if (tid + (s << 1) < spre)
818
+ {
819
+ cache_grad_attn_weight[tid] += cache_grad_attn_weight[tid + (s << 1)];
820
+ cache_grad_sampling_loc[xid1] += cache_grad_sampling_loc[xid2 + (s << 1)];
821
+ cache_grad_sampling_loc[xid1 + 1] += cache_grad_sampling_loc[xid2 + 1 + (s << 1)];
822
+ }
823
+ }
824
+ __syncthreads();
825
+ }
826
+
827
+ if (tid == 0)
828
+ {
829
+ atomicAdd(grad_sampling_loc, cache_grad_sampling_loc[0]);
830
+ atomicAdd(grad_sampling_loc + 1, cache_grad_sampling_loc[1]);
831
+ atomicAdd(grad_attn_weight, cache_grad_attn_weight[0]);
832
+ }
833
+ __syncthreads();
834
+
835
+ data_weight_ptr += 1;
836
+ data_loc_w_ptr += 2;
837
+ grad_attn_weight += grad_weight_stride;
838
+ grad_sampling_loc += grad_loc_stride;
839
+ }
840
+ }
841
+ }
842
+ }
843
+
844
+
845
+ template <typename scalar_t>
846
+ __global__ void ms_deformable_col2im_gpu_kernel_gm(const int n,
847
+ const scalar_t *grad_col,
848
+ const scalar_t *data_value,
849
+ const int64_t *data_spatial_shapes,
850
+ const int64_t *data_level_start_index,
851
+ const scalar_t *data_sampling_loc,
852
+ const scalar_t *data_attn_weight,
853
+ const int batch_size,
854
+ const int spatial_size,
855
+ const int num_heads,
856
+ const int channels,
857
+ const int num_levels,
858
+ const int num_query,
859
+ const int num_point,
860
+ scalar_t *grad_value,
861
+ scalar_t *grad_sampling_loc,
862
+ scalar_t *grad_attn_weight)
863
+ {
864
+ CUDA_KERNEL_LOOP(index, n)
865
+ {
866
+ int _temp = index;
867
+ const int c_col = _temp % channels;
868
+ _temp /= channels;
869
+ const int sampling_index = _temp;
870
+ const int m_col = _temp % num_heads;
871
+ _temp /= num_heads;
872
+ const int q_col = _temp % num_query;
873
+ _temp /= num_query;
874
+ const int b_col = _temp;
875
+
876
+ const scalar_t top_grad = grad_col[index];
877
+
878
+ int data_weight_ptr = sampling_index * num_levels * num_point;
879
+ int data_loc_w_ptr = data_weight_ptr << 1;
880
+ const int grad_sampling_ptr = data_weight_ptr;
881
+ grad_sampling_loc += grad_sampling_ptr << 1;
882
+ grad_attn_weight += grad_sampling_ptr;
883
+ const int grad_weight_stride = 1;
884
+ const int grad_loc_stride = 2;
885
+ const int qid_stride = num_heads * channels;
886
+ const int data_value_ptr_init_offset = b_col * spatial_size * qid_stride;
887
+
888
+ for (int l_col=0; l_col < num_levels; ++l_col)
889
+ {
890
+ const int level_start_id = data_level_start_index[l_col];
891
+ const int spatial_h_ptr = l_col << 1;
892
+ const int spatial_h = data_spatial_shapes[spatial_h_ptr];
893
+ const int spatial_w = data_spatial_shapes[spatial_h_ptr + 1];
894
+ const int value_ptr_offset = data_value_ptr_init_offset + level_start_id * qid_stride;
895
+ const scalar_t *data_value_ptr = data_value + value_ptr_offset;
896
+ scalar_t *grad_value_ptr = grad_value + value_ptr_offset;
897
+
898
+ for (int p_col=0; p_col < num_point; ++p_col)
899
+ {
900
+ const scalar_t loc_w = data_sampling_loc[data_loc_w_ptr];
901
+ const scalar_t loc_h = data_sampling_loc[data_loc_w_ptr + 1];
902
+ const scalar_t weight = data_attn_weight[data_weight_ptr];
903
+
904
+ const scalar_t h_im = loc_h * spatial_h - 0.5;
905
+ const scalar_t w_im = loc_w * spatial_w - 0.5;
906
+ if (h_im > -1 && w_im > -1 && h_im < spatial_h && w_im < spatial_w)
907
+ {
908
+ ms_deform_attn_col2im_bilinear_gm(
909
+ data_value_ptr, spatial_h, spatial_w, num_heads, channels, h_im, w_im, m_col, c_col,
910
+ top_grad, weight, grad_value_ptr,
911
+ grad_sampling_loc, grad_attn_weight);
912
+ }
913
+ data_weight_ptr += 1;
914
+ data_loc_w_ptr += 2;
915
+ grad_attn_weight += grad_weight_stride;
916
+ grad_sampling_loc += grad_loc_stride;
917
+ }
918
+ }
919
+ }
920
+ }
921
+
922
+
923
+ template <typename scalar_t>
924
+ void ms_deformable_im2col_cuda(cudaStream_t stream,
925
+ const scalar_t* data_value,
926
+ const int64_t* data_spatial_shapes,
927
+ const int64_t* data_level_start_index,
928
+ const scalar_t* data_sampling_loc,
929
+ const scalar_t* data_attn_weight,
930
+ const int batch_size,
931
+ const int spatial_size,
932
+ const int num_heads,
933
+ const int channels,
934
+ const int num_levels,
935
+ const int num_query,
936
+ const int num_point,
937
+ scalar_t* data_col)
938
+ {
939
+ const int num_kernels = batch_size * num_query * num_heads * channels;
940
+ const int num_actual_kernels = batch_size * num_query * num_heads * channels;
941
+ const int num_threads = CUDA_NUM_THREADS;
942
+ ms_deformable_im2col_gpu_kernel<scalar_t>
943
+ <<<GET_BLOCKS(num_actual_kernels, num_threads), num_threads,
944
+ 0, stream>>>(
945
+ num_kernels, data_value, data_spatial_shapes, data_level_start_index, data_sampling_loc, data_attn_weight,
946
+ batch_size, spatial_size, num_heads, channels, num_levels, num_query, num_point, data_col);
947
+
948
+ cudaError_t err = cudaGetLastError();
949
+ if (err != cudaSuccess)
950
+ {
951
+ printf("error in ms_deformable_im2col_cuda: %s\n", cudaGetErrorString(err));
952
+ }
953
+
954
+ }
955
+
956
+ template <typename scalar_t>
957
+ void ms_deformable_col2im_cuda(cudaStream_t stream,
958
+ const scalar_t* grad_col,
959
+ const scalar_t* data_value,
960
+ const int64_t * data_spatial_shapes,
961
+ const int64_t * data_level_start_index,
962
+ const scalar_t * data_sampling_loc,
963
+ const scalar_t * data_attn_weight,
964
+ const int batch_size,
965
+ const int spatial_size,
966
+ const int num_heads,
967
+ const int channels,
968
+ const int num_levels,
969
+ const int num_query,
970
+ const int num_point,
971
+ scalar_t* grad_value,
972
+ scalar_t* grad_sampling_loc,
973
+ scalar_t* grad_attn_weight)
974
+ {
975
+ const int num_threads = (channels > CUDA_NUM_THREADS)?CUDA_NUM_THREADS:channels;
976
+ const int num_kernels = batch_size * num_query * num_heads * channels;
977
+ const int num_actual_kernels = batch_size * num_query * num_heads * channels;
978
+ if (channels > 1024)
979
+ {
980
+ if ((channels & 1023) == 0)
981
+ {
982
+ ms_deformable_col2im_gpu_kernel_shm_reduce_v2_multi_blocks<scalar_t>
983
+ <<<GET_BLOCKS(num_actual_kernels, num_threads), num_threads,
984
+ num_threads*3*sizeof(scalar_t), stream>>>(
985
+ num_kernels,
986
+ grad_col,
987
+ data_value,
988
+ data_spatial_shapes,
989
+ data_level_start_index,
990
+ data_sampling_loc,
991
+ data_attn_weight,
992
+ batch_size,
993
+ spatial_size,
994
+ num_heads,
995
+ channels,
996
+ num_levels,
997
+ num_query,
998
+ num_point,
999
+ grad_value,
1000
+ grad_sampling_loc,
1001
+ grad_attn_weight);
1002
+ }
1003
+ else
1004
+ {
1005
+ ms_deformable_col2im_gpu_kernel_gm<scalar_t>
1006
+ <<<GET_BLOCKS(num_actual_kernels, num_threads), num_threads,
1007
+ 0, stream>>>(
1008
+ num_kernels,
1009
+ grad_col,
1010
+ data_value,
1011
+ data_spatial_shapes,
1012
+ data_level_start_index,
1013
+ data_sampling_loc,
1014
+ data_attn_weight,
1015
+ batch_size,
1016
+ spatial_size,
1017
+ num_heads,
1018
+ channels,
1019
+ num_levels,
1020
+ num_query,
1021
+ num_point,
1022
+ grad_value,
1023
+ grad_sampling_loc,
1024
+ grad_attn_weight);
1025
+ }
1026
+ }
1027
+ else{
1028
+ switch(channels)
1029
+ {
1030
+ case 1:
1031
+ ms_deformable_col2im_gpu_kernel_shm_blocksize_aware_reduce_v1<scalar_t, 1>
1032
+ <<<GET_BLOCKS(num_actual_kernels, num_threads), num_threads,
1033
+ 0, stream>>>(
1034
+ num_kernels,
1035
+ grad_col,
1036
+ data_value,
1037
+ data_spatial_shapes,
1038
+ data_level_start_index,
1039
+ data_sampling_loc,
1040
+ data_attn_weight,
1041
+ batch_size,
1042
+ spatial_size,
1043
+ num_heads,
1044
+ channels,
1045
+ num_levels,
1046
+ num_query,
1047
+ num_point,
1048
+ grad_value,
1049
+ grad_sampling_loc,
1050
+ grad_attn_weight);
1051
+ break;
1052
+ case 2:
1053
+ ms_deformable_col2im_gpu_kernel_shm_blocksize_aware_reduce_v1<scalar_t, 2>
1054
+ <<<GET_BLOCKS(num_actual_kernels, num_threads), num_threads,
1055
+ 0, stream>>>(
1056
+ num_kernels,
1057
+ grad_col,
1058
+ data_value,
1059
+ data_spatial_shapes,
1060
+ data_level_start_index,
1061
+ data_sampling_loc,
1062
+ data_attn_weight,
1063
+ batch_size,
1064
+ spatial_size,
1065
+ num_heads,
1066
+ channels,
1067
+ num_levels,
1068
+ num_query,
1069
+ num_point,
1070
+ grad_value,
1071
+ grad_sampling_loc,
1072
+ grad_attn_weight);
1073
+ break;
1074
+ case 4:
1075
+ ms_deformable_col2im_gpu_kernel_shm_blocksize_aware_reduce_v1<scalar_t, 4>
1076
+ <<<GET_BLOCKS(num_actual_kernels, num_threads), num_threads,
1077
+ 0, stream>>>(
1078
+ num_kernels,
1079
+ grad_col,
1080
+ data_value,
1081
+ data_spatial_shapes,
1082
+ data_level_start_index,
1083
+ data_sampling_loc,
1084
+ data_attn_weight,
1085
+ batch_size,
1086
+ spatial_size,
1087
+ num_heads,
1088
+ channels,
1089
+ num_levels,
1090
+ num_query,
1091
+ num_point,
1092
+ grad_value,
1093
+ grad_sampling_loc,
1094
+ grad_attn_weight);
1095
+ break;
1096
+ case 8:
1097
+ ms_deformable_col2im_gpu_kernel_shm_blocksize_aware_reduce_v1<scalar_t, 8>
1098
+ <<<GET_BLOCKS(num_actual_kernels, num_threads), num_threads,
1099
+ 0, stream>>>(
1100
+ num_kernels,
1101
+ grad_col,
1102
+ data_value,
1103
+ data_spatial_shapes,
1104
+ data_level_start_index,
1105
+ data_sampling_loc,
1106
+ data_attn_weight,
1107
+ batch_size,
1108
+ spatial_size,
1109
+ num_heads,
1110
+ channels,
1111
+ num_levels,
1112
+ num_query,
1113
+ num_point,
1114
+ grad_value,
1115
+ grad_sampling_loc,
1116
+ grad_attn_weight);
1117
+ break;
1118
+ case 16:
1119
+ ms_deformable_col2im_gpu_kernel_shm_blocksize_aware_reduce_v1<scalar_t, 16>
1120
+ <<<GET_BLOCKS(num_actual_kernels, num_threads), num_threads,
1121
+ 0, stream>>>(
1122
+ num_kernels,
1123
+ grad_col,
1124
+ data_value,
1125
+ data_spatial_shapes,
1126
+ data_level_start_index,
1127
+ data_sampling_loc,
1128
+ data_attn_weight,
1129
+ batch_size,
1130
+ spatial_size,
1131
+ num_heads,
1132
+ channels,
1133
+ num_levels,
1134
+ num_query,
1135
+ num_point,
1136
+ grad_value,
1137
+ grad_sampling_loc,
1138
+ grad_attn_weight);
1139
+ break;
1140
+ case 32:
1141
+ ms_deformable_col2im_gpu_kernel_shm_blocksize_aware_reduce_v1<scalar_t, 32>
1142
+ <<<GET_BLOCKS(num_actual_kernels, num_threads), num_threads,
1143
+ 0, stream>>>(
1144
+ num_kernels,
1145
+ grad_col,
1146
+ data_value,
1147
+ data_spatial_shapes,
1148
+ data_level_start_index,
1149
+ data_sampling_loc,
1150
+ data_attn_weight,
1151
+ batch_size,
1152
+ spatial_size,
1153
+ num_heads,
1154
+ channels,
1155
+ num_levels,
1156
+ num_query,
1157
+ num_point,
1158
+ grad_value,
1159
+ grad_sampling_loc,
1160
+ grad_attn_weight);
1161
+ break;
1162
+ case 64:
1163
+ ms_deformable_col2im_gpu_kernel_shm_blocksize_aware_reduce_v2<scalar_t, 64>
1164
+ <<<GET_BLOCKS(num_actual_kernels, num_threads), num_threads,
1165
+ 0, stream>>>(
1166
+ num_kernels,
1167
+ grad_col,
1168
+ data_value,
1169
+ data_spatial_shapes,
1170
+ data_level_start_index,
1171
+ data_sampling_loc,
1172
+ data_attn_weight,
1173
+ batch_size,
1174
+ spatial_size,
1175
+ num_heads,
1176
+ channels,
1177
+ num_levels,
1178
+ num_query,
1179
+ num_point,
1180
+ grad_value,
1181
+ grad_sampling_loc,
1182
+ grad_attn_weight);
1183
+ break;
1184
+ case 128:
1185
+ ms_deformable_col2im_gpu_kernel_shm_blocksize_aware_reduce_v2<scalar_t, 128>
1186
+ <<<GET_BLOCKS(num_actual_kernels, num_threads), num_threads,
1187
+ 0, stream>>>(
1188
+ num_kernels,
1189
+ grad_col,
1190
+ data_value,
1191
+ data_spatial_shapes,
1192
+ data_level_start_index,
1193
+ data_sampling_loc,
1194
+ data_attn_weight,
1195
+ batch_size,
1196
+ spatial_size,
1197
+ num_heads,
1198
+ channels,
1199
+ num_levels,
1200
+ num_query,
1201
+ num_point,
1202
+ grad_value,
1203
+ grad_sampling_loc,
1204
+ grad_attn_weight);
1205
+ break;
1206
+ case 256:
1207
+ ms_deformable_col2im_gpu_kernel_shm_blocksize_aware_reduce_v2<scalar_t, 256>
1208
+ <<<GET_BLOCKS(num_actual_kernels, num_threads), num_threads,
1209
+ 0, stream>>>(
1210
+ num_kernels,
1211
+ grad_col,
1212
+ data_value,
1213
+ data_spatial_shapes,
1214
+ data_level_start_index,
1215
+ data_sampling_loc,
1216
+ data_attn_weight,
1217
+ batch_size,
1218
+ spatial_size,
1219
+ num_heads,
1220
+ channels,
1221
+ num_levels,
1222
+ num_query,
1223
+ num_point,
1224
+ grad_value,
1225
+ grad_sampling_loc,
1226
+ grad_attn_weight);
1227
+ break;
1228
+ case 512:
1229
+ ms_deformable_col2im_gpu_kernel_shm_blocksize_aware_reduce_v2<scalar_t, 512>
1230
+ <<<GET_BLOCKS(num_actual_kernels, num_threads), num_threads,
1231
+ 0, stream>>>(
1232
+ num_kernels,
1233
+ grad_col,
1234
+ data_value,
1235
+ data_spatial_shapes,
1236
+ data_level_start_index,
1237
+ data_sampling_loc,
1238
+ data_attn_weight,
1239
+ batch_size,
1240
+ spatial_size,
1241
+ num_heads,
1242
+ channels,
1243
+ num_levels,
1244
+ num_query,
1245
+ num_point,
1246
+ grad_value,
1247
+ grad_sampling_loc,
1248
+ grad_attn_weight);
1249
+ break;
1250
+ case 1024:
1251
+ ms_deformable_col2im_gpu_kernel_shm_blocksize_aware_reduce_v2<scalar_t, 1024>
1252
+ <<<GET_BLOCKS(num_actual_kernels, num_threads), num_threads,
1253
+ 0, stream>>>(
1254
+ num_kernels,
1255
+ grad_col,
1256
+ data_value,
1257
+ data_spatial_shapes,
1258
+ data_level_start_index,
1259
+ data_sampling_loc,
1260
+ data_attn_weight,
1261
+ batch_size,
1262
+ spatial_size,
1263
+ num_heads,
1264
+ channels,
1265
+ num_levels,
1266
+ num_query,
1267
+ num_point,
1268
+ grad_value,
1269
+ grad_sampling_loc,
1270
+ grad_attn_weight);
1271
+ break;
1272
+ default:
1273
+ if (channels < 64)
1274
+ {
1275
+ ms_deformable_col2im_gpu_kernel_shm_reduce_v1<scalar_t>
1276
+ <<<GET_BLOCKS(num_actual_kernels, num_threads), num_threads,
1277
+ num_threads*3*sizeof(scalar_t), stream>>>(
1278
+ num_kernels,
1279
+ grad_col,
1280
+ data_value,
1281
+ data_spatial_shapes,
1282
+ data_level_start_index,
1283
+ data_sampling_loc,
1284
+ data_attn_weight,
1285
+ batch_size,
1286
+ spatial_size,
1287
+ num_heads,
1288
+ channels,
1289
+ num_levels,
1290
+ num_query,
1291
+ num_point,
1292
+ grad_value,
1293
+ grad_sampling_loc,
1294
+ grad_attn_weight);
1295
+ }
1296
+ else
1297
+ {
1298
+ ms_deformable_col2im_gpu_kernel_shm_reduce_v2<scalar_t>
1299
+ <<<GET_BLOCKS(num_actual_kernels, num_threads), num_threads,
1300
+ num_threads*3*sizeof(scalar_t), stream>>>(
1301
+ num_kernels,
1302
+ grad_col,
1303
+ data_value,
1304
+ data_spatial_shapes,
1305
+ data_level_start_index,
1306
+ data_sampling_loc,
1307
+ data_attn_weight,
1308
+ batch_size,
1309
+ spatial_size,
1310
+ num_heads,
1311
+ channels,
1312
+ num_levels,
1313
+ num_query,
1314
+ num_point,
1315
+ grad_value,
1316
+ grad_sampling_loc,
1317
+ grad_attn_weight);
1318
+ }
1319
+ }
1320
+ }
1321
+ cudaError_t err = cudaGetLastError();
1322
+ if (err != cudaSuccess)
1323
+ {
1324
+ printf("error in ms_deformable_col2im_cuda: %s\n", cudaGetErrorString(err));
1325
+ }
1326
+
1327
+ }
csrc/cuda_version.cu ADDED
@@ -0,0 +1,7 @@
 
 
 
 
 
 
 
 
1
+ #include <cuda_runtime_api.h>
2
+
3
+ namespace groundingdino {
4
+ int get_cudart_version() {
5
+ return CUDART_VERSION;
6
+ }
7
+ } // namespace groundingdino
csrc/vision.cpp ADDED
@@ -0,0 +1,58 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ // Copyright (c) Facebook, Inc. and its affiliates. All Rights Reserved
2
+
3
+ #include "MsDeformAttn/ms_deform_attn.h"
4
+
5
+ namespace groundingdino {
6
+
7
+ #ifdef WITH_CUDA
8
+ extern int get_cudart_version();
9
+ #endif
10
+
11
+ std::string get_cuda_version() {
12
+ #ifdef WITH_CUDA
13
+ std::ostringstream oss;
14
+
15
+ // copied from
16
+ // https://github.com/pytorch/pytorch/blob/master/aten/src/ATen/cuda/detail/CUDAHooks.cpp#L231
17
+ auto printCudaStyleVersion = [&](int v) {
18
+ oss << (v / 1000) << "." << (v / 10 % 100);
19
+ if (v % 10 != 0) {
20
+ oss << "." << (v % 10);
21
+ }
22
+ };
23
+ printCudaStyleVersion(get_cudart_version());
24
+ return oss.str();
25
+ #else
26
+ return std::string("not available");
27
+ #endif
28
+ }
29
+
30
+ // similar to
31
+ // https://github.com/pytorch/pytorch/blob/master/aten/src/ATen/Version.cpp
32
+ std::string get_compiler_version() {
33
+ std::ostringstream ss;
34
+ #if defined(__GNUC__)
35
+ #ifndef __clang__
36
+ { ss << "GCC " << __GNUC__ << "." << __GNUC_MINOR__; }
37
+ #endif
38
+ #endif
39
+
40
+ #if defined(__clang_major__)
41
+ {
42
+ ss << "clang " << __clang_major__ << "." << __clang_minor__ << "."
43
+ << __clang_patchlevel__;
44
+ }
45
+ #endif
46
+
47
+ #if defined(_MSC_VER)
48
+ { ss << "MSVC " << _MSC_FULL_VER; }
49
+ #endif
50
+ return ss.str();
51
+ }
52
+
53
+ PYBIND11_MODULE(TORCH_EXTENSION_NAME, m) {
54
+ m.def("ms_deform_attn_forward", &ms_deform_attn_forward, "ms_deform_attn_forward");
55
+ m.def("ms_deform_attn_backward", &ms_deform_attn_backward, "ms_deform_attn_backward");
56
+ }
57
+
58
+ } // namespace groundingdino
main_1.jpg ADDED
main_2.jpg ADDED
main_3.jpg ADDED
main_4.jpg ADDED
main_5.jpg ADDED
main_6.jpeg ADDED
models/__init__.py ADDED
File without changes
models/blip2_decoder.py ADDED
@@ -0,0 +1,190 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ import contextlib
2
+ import logging
3
+
4
+ import torch
5
+ import torch.nn as nn
6
+ from lavis.common.registry import registry
7
+ from lavis.models import Blip2OPT, load_preprocess
8
+ from omegaconf import OmegaConf
9
+
10
+
11
+ @registry.register_model("blip2_opt_det")
12
+ class Blip2OPTDet(Blip2OPT):
13
+ def __init__(
14
+ self,
15
+ **kwargs
16
+ ):
17
+ super().__init__(**kwargs)
18
+ self.opt_tokenizer.add_special_tokens({"mask_token": "<mask>"})
19
+
20
+ def maybe_autocast(self, dtype=torch.float16):
21
+ # if on cpu, don't use autocast
22
+ # if on gpu, use autocast with dtype if provided, otherwise use torch.float16
23
+ enable_autocast = self.device != torch.device("cpu")
24
+
25
+ if enable_autocast:
26
+ return torch.cuda.amp.autocast(dtype=dtype)
27
+ else:
28
+ return contextlib.nullcontext()
29
+
30
+ @torch.no_grad()
31
+ def forward(self, samples,
32
+ use_nucleus_sampling=False,
33
+ num_beams=5,
34
+ max_length=30,
35
+ min_length=1,
36
+ top_p=0.9,
37
+ repetition_penalty=1.0,
38
+ length_penalty=1.0,
39
+ num_captions=1,
40
+ temperature=1,
41
+ task_button=None):
42
+ image = samples["image"]
43
+ with self.maybe_autocast():
44
+ image_embeds = self.ln_vision(self.visual_encoder(image))
45
+ image_atts = torch.ones(image_embeds.size()[:-1], dtype=torch.long).to(
46
+ image.device
47
+ )
48
+
49
+ query_tokens = self.query_tokens.expand(image_embeds.shape[0], -1, -1)
50
+ query_output = self.Qformer.bert(
51
+ query_embeds=query_tokens,
52
+ encoder_hidden_states=image_embeds,
53
+ encoder_attention_mask=image_atts,
54
+ return_dict=True,
55
+ )
56
+
57
+ inputs_opt = self.opt_proj(query_output.last_hidden_state)
58
+ atts_opt = torch.ones(inputs_opt.size()[:-1], dtype=torch.long).to(image.device)
59
+
60
+ self.opt_tokenizer.padding_side = "right"
61
+
62
+ if "text_input" in samples.keys():
63
+ # text = [t + "\n" for t in samples["text_input"]]
64
+ text = [t for t in samples["text_input"]]
65
+ opt_tokens = self.opt_tokenizer(
66
+ text,
67
+ return_tensors="pt",
68
+ padding="longest",
69
+ ).to(image.device)
70
+ input_ids = opt_tokens.input_ids
71
+ attention_mask = opt_tokens.attention_mask
72
+ output_text = text
73
+ elif "input_ids" in samples.keys():
74
+ input_ids = samples["input_ids"]
75
+ attention_mask = samples["attention_mask"]
76
+ output_text = []
77
+ else:
78
+ assert "prompt" in samples.keys()
79
+ prompt = samples["prompt"]
80
+ assert len(prompt) == image.size(0)
81
+
82
+ opt_tokens = self.opt_tokenizer(prompt, return_tensors="pt", padding=True).to(
83
+ image.device
84
+ )
85
+ input_ids = opt_tokens.input_ids
86
+ attention_mask = torch.cat([atts_opt, opt_tokens.attention_mask], dim=1)
87
+
88
+ if use_nucleus_sampling:
89
+ query_embeds = inputs_opt.repeat_interleave(num_captions, dim=0)
90
+ num_beams = 1
91
+ else:
92
+ query_embeds = inputs_opt.repeat_interleave(num_beams, dim=0)
93
+
94
+ with self.maybe_autocast():
95
+ outputs = self.opt_model.generate(
96
+ input_ids=input_ids,
97
+ query_embeds=query_embeds,
98
+ attention_mask=attention_mask,
99
+ do_sample=use_nucleus_sampling,
100
+ top_p=top_p,
101
+ temperature=temperature,
102
+ num_beams=num_beams,
103
+ max_new_tokens=max_length,
104
+ min_length=min_length,
105
+ eos_token_id=self.eos_token_id,
106
+ repetition_penalty=repetition_penalty,
107
+ length_penalty=length_penalty,
108
+ num_return_sequences=num_captions,
109
+ )
110
+
111
+ prompt_length = opt_tokens.input_ids.shape[1]
112
+ output_text = self.opt_tokenizer.batch_decode(
113
+ outputs[:, prompt_length:], skip_special_tokens=True
114
+ )
115
+ output_text = [text.strip() for text in output_text]
116
+ if task_button == 'Question Answering' or task_button == "Captioning":
117
+ output_text_input = [prompt[0] + ' ' + output_text[0]]
118
+ opt_tokens = self.opt_tokenizer(
119
+ output_text_input,
120
+ return_tensors="pt",
121
+ padding="longest",
122
+ ).to(image.device)
123
+ input_ids = opt_tokens.input_ids
124
+ attention_mask = opt_tokens.attention_mask
125
+
126
+ inputs_embeds = self.opt_model.model.decoder.embed_tokens(input_ids)
127
+ inputs_embeds = torch.cat([inputs_opt, inputs_embeds], dim=1)
128
+ attention_mask = torch.cat([atts_opt, attention_mask], dim=1)
129
+ with self.maybe_autocast():
130
+ outputs = self.opt_model(
131
+ inputs_embeds=inputs_embeds,
132
+ attention_mask=attention_mask,
133
+ return_dict=True,
134
+ output_hidden_states=True
135
+ )
136
+ n_queries = query_tokens.shape[1]
137
+ out_logits = outputs['logits'][:, n_queries:]
138
+ out_hidden = outputs['hidden_states'][-1][:, n_queries:]
139
+ return out_logits, out_hidden, input_ids, output_text
140
+
141
+
142
+ def load_model_and_preprocess(name, model_type, is_eval=False, device="cpu"):
143
+ model_cls = registry.get_model_class(name)
144
+
145
+ # load model
146
+ model = model_cls.from_pretrained(model_type=model_type)
147
+
148
+ if is_eval:
149
+ model.eval()
150
+
151
+ # load preprocess
152
+ cfg = OmegaConf.load(model_cls.default_config_path(model_type))
153
+ if cfg is not None:
154
+ preprocess_cfg = cfg.preprocess
155
+
156
+ vis_processors, txt_processors = load_preprocess(preprocess_cfg)
157
+ else:
158
+ vis_processors, txt_processors = None, None
159
+ logging.info(
160
+ f"""No default preprocess for model {name} ({model_type}).
161
+ This can happen if the model is not finetuned on downstream datasets,
162
+ or it is not intended for direct use without finetuning.
163
+ """
164
+ )
165
+
166
+ if device == "cpu" or device == torch.device("cpu"):
167
+ model = model.float()
168
+
169
+ return model.to(device), vis_processors, txt_processors
170
+
171
+
172
+ class BLIP2Decoder(nn.Module):
173
+ def __init__(self, llm_name):
174
+ super(BLIP2Decoder, self).__init__()
175
+
176
+ self.device = torch.device("cuda") if torch.cuda.is_available() else "cpu"
177
+ if llm_name not in ['pretrain_opt2.7b', 'caption_coco_opt2.7b',
178
+ 'pretrain_opt6.7b', 'caption_coco_opt6.7b']:
179
+ raise ValueError(f"{llm_name} is not support yet")
180
+ model_type = llm_name
181
+ model, vis, _ = load_model_and_preprocess(name="blip2_opt_det",
182
+ model_type=model_type,
183
+ is_eval=True, device=self.device)
184
+ self.model = model
185
+ self.vis_processors = vis
186
+ self.freeze_layers()
187
+
188
+ def freeze_layers(self):
189
+ for p in self.model.parameters():
190
+ p.requires_grad = False
models/contextdet_blip2.py ADDED
@@ -0,0 +1,219 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ import math
2
+ import random
3
+
4
+ import torch
5
+ import torch.nn as nn
6
+ import torch.nn.functional as F
7
+
8
+ from util.misc import (NestedTensor, inverse_sigmoid,
9
+ nested_tensor_from_tensor_list)
10
+
11
+ from .blip2_decoder import BLIP2Decoder
12
+ from .deformable_detr.backbone import build_backbone
13
+ from .deformable_detr.deformable_detr import DeformableDETR
14
+ from .transformer import build_ov_transformer
15
+
16
+
17
+ class ContextDET(DeformableDETR):
18
+ def __init__(self, backbone, transformer, num_classes, num_queries, num_feature_levels,
19
+ aux_loss=True, with_box_refine=False, two_stage=False, llm_decoder=None):
20
+ super().__init__(backbone, transformer, num_classes, num_queries, num_feature_levels,
21
+ aux_loss, with_box_refine, two_stage)
22
+ self.device = torch.device('cuda' if torch.cuda.is_available() else 'cpu')
23
+ self.llm_decoder = llm_decoder
24
+ hidden_dim = transformer.d_model
25
+ out_size = self.llm_decoder.model.opt_proj.out_features
26
+ self.llm_proj = nn.Linear(out_size, hidden_dim, device=self.device)
27
+ self.start_end_proj = nn.Linear(hidden_dim, 2)
28
+ for layer in [self.llm_proj, self.start_end_proj]:
29
+ nn.init.kaiming_normal_(layer.weight, mode='fan_in', nonlinearity='relu')
30
+ nn.init.zeros_(layer.bias)
31
+ # word_embed_proj_dim = llm_decoder.model.opt_model.config.word_embed_proj_dim
32
+ vocab_size = llm_decoder.model.opt_model.config.vocab_size
33
+ self.fc_logits = nn.Linear(hidden_dim, vocab_size)
34
+
35
+ def forward(self, samples, blip2_samples, mask_infos=None, task_button=None, threshold=0.3):
36
+ logits, hidden_states, input_ids, output_text = self.llm_decoder.model.forward(
37
+ blip2_samples, task_button=task_button)
38
+ hidden_states = hidden_states.detach()
39
+ hidden_states = self.llm_proj(hidden_states)
40
+
41
+ if not isinstance(samples, NestedTensor):
42
+ samples = nested_tensor_from_tensor_list(samples)
43
+ features, pos = self.backbone(samples)
44
+
45
+ srcs = []
46
+ masks = []
47
+ for l, feat in enumerate(features):
48
+ src, mask = feat.decompose()
49
+ srcs.append(self.input_proj[l](src))
50
+ masks.append(mask)
51
+ assert mask is not None
52
+ if self.num_feature_levels > len(srcs):
53
+ _len_srcs = len(srcs)
54
+ for l in range(_len_srcs, self.num_feature_levels):
55
+ if l == _len_srcs:
56
+ src = self.input_proj[l](features[-1].tensors)
57
+ else:
58
+ src = self.input_proj[l](srcs[-1])
59
+ m = samples.mask
60
+ mask = F.interpolate(m[None].float(), size=src.shape[-2:]).to(torch.bool)[0]
61
+ pos_l = self.backbone[1](NestedTensor(src, mask)).to(src.dtype)
62
+ srcs.append(src)
63
+ masks.append(mask)
64
+ pos.append(pos_l)
65
+
66
+ out = {}
67
+ start_end_proj = self.start_end_proj(hidden_states)
68
+ out['pred_mlm_logits'] = self.fc_logits(hidden_states)
69
+ out['pred_start'] = start_end_proj[:, :, 0:1]
70
+ out['pred_end'] = start_end_proj[:, :, 1:2]
71
+ out['output_text'] = output_text
72
+ if self.training:
73
+ k = min([len(mask_info) for mask_info in mask_infos])
74
+ k = min(k, 2)
75
+ select_ids = [random.sample(mask_info.keys(), k) for mask_info in mask_infos]
76
+ # select_ids = [random.choices(list(mask_info.keys()), k=4) for mask_info in mask_infos]
77
+ llm_feat = []
78
+ for b in range(len(select_ids)):
79
+ llm_feat_b = []
80
+ hidden_states_b = hidden_states[b, :, :]
81
+ for start, end in select_ids[b]:
82
+ llm_feat_b.append(hidden_states_b[start: end + 1].mean(dim=0, keepdim=True))
83
+ llm_feat.append(torch.cat(llm_feat_b)[None])
84
+ llm_feat = torch.cat(llm_feat)
85
+ query_embeds = None
86
+ if not self.two_stage:
87
+ query_embeds = self.query_embed.weight
88
+ hs, init_reference, inter_references, enc_outputs_class, enc_outputs_coord_unact, anchors = (
89
+ self.transformer(srcs, masks, pos, query_embeds, llm_feat, k)
90
+ )
91
+ outputs_classes = []
92
+ outputs_coords = []
93
+ for lvl in range(hs.shape[0]):
94
+ if lvl == 0:
95
+ reference = init_reference
96
+ else:
97
+ reference = inter_references[lvl - 1]
98
+ reference = inverse_sigmoid(reference)
99
+ outputs_class = self.class_embed[lvl](hs[lvl])
100
+ tmp = self.bbox_embed[lvl](hs[lvl])
101
+ if reference.shape[-1] == 4:
102
+ tmp += reference
103
+ else:
104
+ assert reference.shape[-1] == 2
105
+ tmp[..., :2] += reference
106
+ outputs_coord = tmp.sigmoid()
107
+ outputs_classes.append(outputs_class)
108
+ outputs_coords.append(outputs_coord)
109
+ outputs_class = torch.stack(outputs_classes)
110
+ outputs_coord = torch.stack(outputs_coords)
111
+
112
+ out.update({'pred_logits': outputs_class[-1], 'pred_boxes': outputs_coord[-1],
113
+ 'init_reference': init_reference})
114
+ out['select_ids'] = select_ids
115
+
116
+ if self.aux_loss:
117
+ out['aux_outputs'] = self._set_aux_loss(outputs_class, outputs_coord)
118
+ for temp in out["aux_outputs"]:
119
+ temp["select_ids"] = select_ids
120
+
121
+ if self.two_stage:
122
+ enc_outputs_coord = enc_outputs_coord_unact.sigmoid()
123
+ out['enc_outputs'] = {
124
+ 'pred_logits': enc_outputs_class,
125
+ 'pred_boxes': enc_outputs_coord,
126
+ 'anchors': anchors,
127
+ }
128
+ else:
129
+ bs = len(samples.tensors)
130
+ mask_infos_pred = [{} for _ in range(bs)]
131
+ llm_feat = []
132
+ tokenizer = self.llm_decoder.model.opt_tokenizer
133
+ if mask_infos is None:
134
+ if task_button == 'Cloze Test':
135
+ mask_infos = []
136
+ output_texts = []
137
+ for b in range(bs):
138
+ mask_infos_b = {}
139
+ output_texts_b = []
140
+ for ind, token in enumerate(input_ids[b]):
141
+ if token == tokenizer.mask_token_id:
142
+ mask_infos_b[(ind, ind)] = ''
143
+ pred_token = out['pred_mlm_logits'][b, ind:ind + 1, :]
144
+ pred_token = pred_token.argmax(1).item()
145
+ output_texts_b.append( pred_token )
146
+ output_texts_b.append( 1437 )
147
+ input_ids[b, ind: ind + 1] = pred_token
148
+ else:
149
+ output_texts_b.append( token.item() )
150
+ mask_infos.append(mask_infos_b)
151
+ output_texts.append(tokenizer.decode(output_texts_b[1:]))
152
+ out['output_text'] = output_texts
153
+ else:
154
+ mask_infos = []
155
+ for b in range(bs):
156
+ starts = (out['pred_start'][b, :, 0].sigmoid() > threshold).nonzero().squeeze(1)
157
+ ends = (out['pred_end'][b, :, 0].sigmoid() > threshold).nonzero().squeeze(1)
158
+ if len(starts) == 0:
159
+ starts = out['pred_start'][b, :].argmax(0)
160
+ if len(ends) == 0:
161
+ ends = out['pred_end'][b, :].argmax(0)
162
+ mask_infos_b = {}
163
+ for start, end in zip(starts, ends):
164
+ mask_infos_b[(int(start), int(end))] = ''
165
+ mask_infos.append(mask_infos_b)
166
+ for b in range(bs):
167
+ llm_feat_b = []
168
+ hidden_states_b = hidden_states[b, :, :]
169
+ for start, end in mask_infos[b].keys():
170
+ llm_feat_b.append(hidden_states_b[start: end + 1].mean(dim=0, keepdim=True))
171
+ pred_name = tokenizer.decode(input_ids[b, start: end + 1]).strip()
172
+ mask_infos_pred[b][(int(start), int(end))] = pred_name
173
+ llm_feat.append(torch.cat(llm_feat_b)[None])
174
+ out['mask_infos_pred'] = mask_infos_pred
175
+
176
+ query_embeds = None
177
+ if not self.two_stage:
178
+ query_embeds = self.query_embed.weight
179
+
180
+ outputs_classes_list = []
181
+ outputs_coords_list = []
182
+ for b in range(bs):
183
+ srcs_b = [i[b: b + 1] for i in srcs]
184
+ masks_b = [i[b: b + 1] for i in masks]
185
+ pos_b = [i[b: b + 1] for i in pos]
186
+ k = len(mask_infos[b])
187
+ if k == 0:
188
+ outputs_classes_list.append(torch.zeros(0, 2).to(self.device))
189
+ outputs_coords_list.append(torch.zeros(0, 4).to(self.device))
190
+ continue
191
+ num_repeat = math.ceil(k / 4)
192
+ outputs_classes = []
193
+ outputs_coords = []
194
+ for ind in range(num_repeat):
195
+ llm_feat_b = llm_feat[b][:, ind * 4: (ind + 1) * 4]
196
+ hs, init_reference, inter_references, enc_outputs_class, enc_outputs_coord_unact, anchors = (
197
+ self.transformer(srcs_b, masks_b, pos_b, query_embeds, llm_feat_b, llm_feat_b.shape[1])
198
+ )
199
+ lvl = hs.shape[0] - 1
200
+ reference = inter_references[lvl - 1]
201
+ reference = inverse_sigmoid(reference)
202
+ outputs_class = self.class_embed[lvl](hs[lvl])
203
+ tmp = self.bbox_embed[lvl](hs[lvl])
204
+ if reference.shape[-1] == 4:
205
+ tmp += reference
206
+ else:
207
+ assert reference.shape[-1] == 2
208
+ tmp[..., :2] += reference
209
+ outputs_coord = tmp.sigmoid()
210
+ outputs_classes.append(outputs_class.flatten(0, 1))
211
+ outputs_coords.append(outputs_coord.flatten(0, 1))
212
+ outputs_classes = torch.cat(outputs_classes)[None]
213
+ outputs_coords = torch.cat(outputs_coords)[None]
214
+ outputs_classes_list.append(outputs_classes)
215
+ outputs_coords_list.append(outputs_coords)
216
+
217
+ out.update({'pred_logits': outputs_classes_list,
218
+ 'pred_boxes': outputs_coords_list})
219
+ return out
models/deformable_detr/README.md ADDED
@@ -0,0 +1,23 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ The code in this directory is taken from [Deformable DETR][deformable-detr] and [DETA][deta] with minor modifications to accommodate the latest PyTorch API.
2
+
3
+ [deformable-detr]: https://github.com/fundamentalvision/Deformable-DETR
4
+
5
+ [deta]: https://github.com/jozhang97/DETA
6
+
7
+ ```bibtex
8
+ @article{zhu2020deformable,
9
+ title={Deformable DETR: Deformable Transformers for End-to-End Object Detection},
10
+ author={Zhu, Xizhou and Su, Weijie and Lu, Lewei and Li, Bin and Wang, Xiaogang and Dai, Jifeng},
11
+ journal={arXiv preprint arXiv:2010.04159},
12
+ year={2020}
13
+ }
14
+ ```
15
+
16
+ ```bibtex
17
+ @article{ouyangzhang2022nms,
18
+ title={NMS Strikes Back},
19
+ author={Ouyang-Zhang, Jeffrey and Cho, Jang Hyun and Zhou, Xingyi and Kr{\"a}henb{\"u}hl, Philipp},
20
+ journal={arXiv preprint arXiv:2212.06137},
21
+ year={2022}
22
+ }
23
+ ```
models/deformable_detr/assigner.py ADDED
@@ -0,0 +1,338 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ # Copyright (c) Facebook, Inc. and its affiliates.
2
+ # Modified by Jeffrey Ouyang-Zhang
3
+
4
+ from typing import List
5
+
6
+ import torch
7
+ import torch.nn as nn
8
+
9
+ from util.box_ops import (box_cxcywh_to_xyxy, box_iou, box_xyxy_to_cxcywh,
10
+ generalized_box_iou)
11
+
12
+
13
+ # from https://github.com/facebookresearch/detectron2/blob/cbbc1ce26473cb2a5cc8f58e8ada9ae14cb41052/detectron2/layers/wrappers.py#L100
14
+ def nonzero_tuple(x):
15
+ """
16
+ A 'as_tuple=True' version of torch.nonzero to support torchscript.
17
+ because of https://github.com/pytorch/pytorch/issues/38718
18
+ """
19
+ if torch.jit.is_scripting():
20
+ if x.dim() == 0:
21
+ return x.unsqueeze(0).nonzero().unbind(1)
22
+ return x.nonzero().unbind(1)
23
+ else:
24
+ return x.nonzero(as_tuple=True)
25
+
26
+ # from https://github.com/facebookresearch/detectron2/blob/9921a2caa585d4fa66c4b534b6fab6e74d89b582/detectron2/modeling/matcher.py#L9
27
+ class Matcher(object):
28
+ """
29
+ This class assigns to each predicted "element" (e.g., a box) a ground-truth
30
+ element. Each predicted element will have exactly zero or one matches; each
31
+ ground-truth element may be matched to zero or more predicted elements.
32
+
33
+ The matching is determined by the MxN match_quality_matrix, that characterizes
34
+ how well each (ground-truth, prediction)-pair match each other. For example,
35
+ if the elements are boxes, this matrix may contain box intersection-over-union
36
+ overlap values.
37
+
38
+ The matcher returns (a) a vector of length N containing the index of the
39
+ ground-truth element m in [0, M) that matches to prediction n in [0, N).
40
+ (b) a vector of length N containing the labels for each prediction.
41
+ """
42
+
43
+ def __init__(
44
+ self, thresholds: List[float], labels: List[int], allow_low_quality_matches: bool = False
45
+ ):
46
+ """
47
+ Args:
48
+ thresholds (list): a list of thresholds used to stratify predictions
49
+ into levels.
50
+ labels (list): a list of values to label predictions belonging at
51
+ each level. A label can be one of {-1, 0, 1} signifying
52
+ {ignore, negative class, positive class}, respectively.
53
+ allow_low_quality_matches (bool): if True, produce additional matches
54
+ for predictions with maximum match quality lower than high_threshold.
55
+ See set_low_quality_matches_ for more details.
56
+
57
+ For example,
58
+ thresholds = [0.3, 0.5]
59
+ labels = [0, -1, 1]
60
+ All predictions with iou < 0.3 will be marked with 0 and
61
+ thus will be considered as false positives while training.
62
+ All predictions with 0.3 <= iou < 0.5 will be marked with -1 and
63
+ thus will be ignored.
64
+ All predictions with 0.5 <= iou will be marked with 1 and
65
+ thus will be considered as true positives.
66
+ """
67
+ # Add -inf and +inf to first and last position in thresholds
68
+ thresholds = thresholds[:]
69
+ assert thresholds[0] > 0
70
+ thresholds.insert(0, -float("inf"))
71
+ thresholds.append(float("inf"))
72
+ # Currently torchscript does not support all + generator
73
+ assert all([low <= high for (low, high) in zip(thresholds[:-1], thresholds[1:])]), thresholds
74
+ assert all([l in [-1, 0, 1] for l in labels])
75
+ assert len(labels) == len(thresholds) - 1
76
+ self.thresholds = thresholds
77
+ self.labels = labels
78
+ self.allow_low_quality_matches = allow_low_quality_matches
79
+
80
+ def __call__(self, match_quality_matrix):
81
+ """
82
+ Args:
83
+ match_quality_matrix (Tensor[float]): an MxN tensor, containing the
84
+ pairwise quality between M ground-truth elements and N predicted
85
+ elements. All elements must be >= 0 (due to the us of `torch.nonzero`
86
+ for selecting indices in :meth:`set_low_quality_matches_`).
87
+
88
+ Returns:
89
+ matches (Tensor[int64]): a vector of length N, where matches[i] is a matched
90
+ ground-truth index in [0, M)
91
+ match_labels (Tensor[int8]): a vector of length N, where pred_labels[i] indicates
92
+ whether a prediction is a true or false positive or ignored
93
+ """
94
+ assert match_quality_matrix.dim() == 2
95
+ if match_quality_matrix.numel() == 0:
96
+ default_matches = match_quality_matrix.new_full(
97
+ (match_quality_matrix.size(1),), 0, dtype=torch.int64
98
+ )
99
+ # When no gt boxes exist, we define IOU = 0 and therefore set labels
100
+ # to `self.labels[0]`, which usually defaults to background class 0
101
+ # To choose to ignore instead, can make labels=[-1,0,-1,1] + set appropriate thresholds
102
+ default_match_labels = match_quality_matrix.new_full(
103
+ (match_quality_matrix.size(1),), self.labels[0], dtype=torch.int8
104
+ )
105
+ return default_matches, default_match_labels
106
+
107
+ assert torch.all(match_quality_matrix >= 0)
108
+
109
+ # match_quality_matrix is M (gt) x N (predicted)
110
+ # Max over gt elements (dim 0) to find best gt candidate for each prediction
111
+ matched_vals, matches = match_quality_matrix.max(dim=0)
112
+
113
+ match_labels = matches.new_full(matches.size(), 1, dtype=torch.int8)
114
+
115
+ for (l, low, high) in zip(self.labels, self.thresholds[:-1], self.thresholds[1:]):
116
+ low_high = (matched_vals >= low) & (matched_vals < high)
117
+ match_labels[low_high] = l
118
+
119
+ if self.allow_low_quality_matches:
120
+ self.set_low_quality_matches_(match_labels, match_quality_matrix)
121
+
122
+ return matches, match_labels
123
+
124
+ def set_low_quality_matches_(self, match_labels, match_quality_matrix):
125
+ """
126
+ Produce additional matches for predictions that have only low-quality matches.
127
+ Specifically, for each ground-truth G find the set of predictions that have
128
+ maximum overlap with it (including ties); for each prediction in that set, if
129
+ it is unmatched, then match it to the ground-truth G.
130
+
131
+ This function implements the RPN assignment case (i) in Sec. 3.1.2 of
132
+ :paper:`Faster R-CNN`.
133
+ """
134
+ # For each gt, find the prediction with which it has highest quality
135
+ highest_quality_foreach_gt, _ = match_quality_matrix.max(dim=1)
136
+ # Find the highest quality match available, even if it is low, including ties.
137
+ # Note that the matches qualities must be positive due to the use of
138
+ # `torch.nonzero`.
139
+ _, pred_inds_with_highest_quality = nonzero_tuple(
140
+ match_quality_matrix == highest_quality_foreach_gt[:, None]
141
+ )
142
+ # If an anchor was labeled positive only due to a low-quality match
143
+ # with gt_A, but it has larger overlap with gt_B, it's matched index will still be gt_B.
144
+ # This follows the implementation in Detectron, and is found to have no significant impact.
145
+ match_labels[pred_inds_with_highest_quality] = 1
146
+
147
+ # from https://github.com/facebookresearch/detectron2/blob/cbbc1ce26473cb2a5cc8f58e8ada9ae14cb41052/detectron2/modeling/sampling.py#L9
148
+ def subsample_labels(
149
+ labels: torch.Tensor, num_samples: int, positive_fraction: float, bg_label: int
150
+ ):
151
+ """
152
+ Return `num_samples` (or fewer, if not enough found)
153
+ random samples from `labels` which is a mixture of positives & negatives.
154
+ It will try to return as many positives as possible without
155
+ exceeding `positive_fraction * num_samples`, and then try to
156
+ fill the remaining slots with negatives.
157
+
158
+ Args:
159
+ labels (Tensor): (N, ) label vector with values:
160
+ * -1: ignore
161
+ * bg_label: background ("negative") class
162
+ * otherwise: one or more foreground ("positive") classes
163
+ num_samples (int): The total number of labels with value >= 0 to return.
164
+ Values that are not sampled will be filled with -1 (ignore).
165
+ positive_fraction (float): The number of subsampled labels with values > 0
166
+ is `min(num_positives, int(positive_fraction * num_samples))`. The number
167
+ of negatives sampled is `min(num_negatives, num_samples - num_positives_sampled)`.
168
+ In order words, if there are not enough positives, the sample is filled with
169
+ negatives. If there are also not enough negatives, then as many elements are
170
+ sampled as is possible.
171
+ bg_label (int): label index of background ("negative") class.
172
+
173
+ Returns:
174
+ pos_idx, neg_idx (Tensor):
175
+ 1D vector of indices. The total length of both is `num_samples` or fewer.
176
+ """
177
+ positive = nonzero_tuple((labels != -1) & (labels != bg_label))[0]
178
+ negative = nonzero_tuple(labels == bg_label)[0]
179
+
180
+ num_pos = int(num_samples * positive_fraction)
181
+ # protect against not enough positive examples
182
+ num_pos = min(positive.numel(), num_pos)
183
+ num_neg = num_samples - num_pos
184
+ # protect against not enough negative examples
185
+ num_neg = min(negative.numel(), num_neg)
186
+
187
+ # randomly select positive and negative examples
188
+ perm1 = torch.randperm(positive.numel(), device=positive.device)[:num_pos]
189
+ perm2 = torch.randperm(negative.numel(), device=negative.device)[:num_neg]
190
+
191
+ pos_idx = positive[perm1]
192
+ neg_idx = negative[perm2]
193
+ return pos_idx, neg_idx
194
+
195
+ def sample_topk_per_gt(pr_inds, gt_inds, iou, k):
196
+ if len(gt_inds) == 0:
197
+ return pr_inds, gt_inds
198
+ # find topk matches for each gt
199
+ gt_inds2, counts = gt_inds.unique(return_counts=True)
200
+ scores, pr_inds2 = iou[gt_inds2].topk(k, dim=1)
201
+ gt_inds2 = gt_inds2[:,None].repeat(1, k)
202
+
203
+ # filter to as many matches that gt has
204
+ pr_inds3 = torch.cat([pr[:c] for c, pr in zip(counts, pr_inds2)])
205
+ gt_inds3 = torch.cat([gt[:c] for c, gt in zip(counts, gt_inds2)])
206
+ return pr_inds3, gt_inds3
207
+
208
+ # modified from https://github.com/facebookresearch/detectron2/blob/cbbc1ce26473cb2a5cc8f58e8ada9ae14cb41052/detectron2/modeling/roi_heads/roi_heads.py#L123
209
+ class Stage2Assigner(nn.Module):
210
+ def __init__(self, num_queries, max_k=4):
211
+ super().__init__()
212
+ self.positive_fraction = 0.25
213
+ self.bg_label = 400 # number > 91 to filter out later
214
+ self.batch_size_per_image = num_queries
215
+ self.proposal_matcher = Matcher(thresholds=[0.6], labels=[0, 1], allow_low_quality_matches=True)
216
+ self.k = max_k
217
+
218
+ def _sample_proposals(
219
+ self, matched_idxs: torch.Tensor, matched_labels: torch.Tensor, gt_classes: torch.Tensor
220
+ ):
221
+ """
222
+ Based on the matching between N proposals and M groundtruth,
223
+ sample the proposals and set their classification labels.
224
+
225
+ Args:
226
+ matched_idxs (Tensor): a vector of length N, each is the best-matched
227
+ gt index in [0, M) for each proposal.
228
+ matched_labels (Tensor): a vector of length N, the matcher's label
229
+ (one of cfg.MODEL.ROI_HEADS.IOU_LABELS) for each proposal.
230
+ gt_classes (Tensor): a vector of length M.
231
+
232
+ Returns:
233
+ Tensor: a vector of indices of sampled proposals. Each is in [0, N).
234
+ Tensor: a vector of the same length, the classification label for
235
+ each sampled proposal. Each sample is labeled as either a category in
236
+ [0, num_classes) or the background (num_classes).
237
+ """
238
+ has_gt = gt_classes.numel() > 0
239
+ # Get the corresponding GT for each proposal
240
+ if has_gt:
241
+ gt_classes = gt_classes[matched_idxs]
242
+ # Label unmatched proposals (0 label from matcher) as background (label=num_classes)
243
+ gt_classes[matched_labels == 0] = self.bg_label
244
+ # Label ignore proposals (-1 label)
245
+ gt_classes[matched_labels == -1] = -1
246
+ else:
247
+ gt_classes = torch.zeros_like(matched_idxs) + self.bg_label
248
+
249
+ sampled_fg_idxs, sampled_bg_idxs = subsample_labels(
250
+ gt_classes, self.batch_size_per_image, self.positive_fraction, self.bg_label
251
+ )
252
+
253
+ sampled_idxs = torch.cat([sampled_fg_idxs, sampled_bg_idxs], dim=0)
254
+ return sampled_idxs, gt_classes[sampled_idxs]
255
+
256
+ def forward(self, outputs, targets, return_cost_matrix=False):
257
+ # COCO categories are from 1 to 90. They set num_classes=91 and apply sigmoid.
258
+
259
+ bs = len(targets)
260
+ indices = []
261
+ ious = []
262
+ for b in range(bs):
263
+ iou, _ = box_iou(
264
+ box_cxcywh_to_xyxy(targets[b]['boxes']),
265
+ box_cxcywh_to_xyxy(outputs['init_reference'][b].detach()),
266
+ )
267
+ matched_idxs, matched_labels = self.proposal_matcher(iou) # proposal_id -> highest_iou_gt_id, proposal_id -> [1 if iou > 0.6, 0 ow]
268
+ sampled_idxs, sampled_gt_classes = self._sample_proposals( # list of sampled proposal_ids, sampled_id -> [0, num_classes)+[bg_label]
269
+ matched_idxs, matched_labels, targets[b]['labels']
270
+ )
271
+ pos_pr_inds = sampled_idxs[sampled_gt_classes != self.bg_label]
272
+ pos_gt_inds = matched_idxs[pos_pr_inds]
273
+ pos_pr_inds, pos_gt_inds = self.postprocess_indices(pos_pr_inds, pos_gt_inds, iou)
274
+ indices.append((pos_pr_inds, pos_gt_inds))
275
+ ious.append(iou)
276
+ if return_cost_matrix:
277
+ return indices, ious
278
+ return indices
279
+
280
+ def postprocess_indices(self, pr_inds, gt_inds, iou):
281
+ return sample_topk_per_gt(pr_inds, gt_inds, iou, self.k)
282
+
283
+ # modified from https://github.com/facebookresearch/detectron2/blob/cbbc1ce26473cb2a5cc8f58e8ada9ae14cb41052/detectron2/modeling/proposal_generator/rpn.py#L181
284
+ class Stage1Assigner(nn.Module):
285
+ def __init__(self, t_low=0.3, t_high=0.7, max_k=4):
286
+ super().__init__()
287
+ self.positive_fraction = 0.5
288
+ self.batch_size_per_image = 256
289
+ self.k = max_k
290
+ self.t_low = t_low
291
+ self.t_high = t_high
292
+ self.anchor_matcher = Matcher(thresholds=[t_low, t_high], labels=[0, -1, 1], allow_low_quality_matches=True)
293
+
294
+ def _subsample_labels(self, label):
295
+ """
296
+ Randomly sample a subset of positive and negative examples, and overwrite
297
+ the label vector to the ignore value (-1) for all elements that are not
298
+ included in the sample.
299
+
300
+ Args:
301
+ labels (Tensor): a vector of -1, 0, 1. Will be modified in-place and returned.
302
+ """
303
+ pos_idx, neg_idx = subsample_labels(
304
+ label, self.batch_size_per_image, self.positive_fraction, 0
305
+ )
306
+ # Fill with the ignore label (-1), then set positive and negative labels
307
+ label.fill_(-1)
308
+ label.scatter_(0, pos_idx, 1)
309
+ label.scatter_(0, neg_idx, 0)
310
+ return label
311
+
312
+ def forward(self, outputs, targets):
313
+ bs = len(targets)
314
+ indices = []
315
+ for b in range(bs):
316
+ anchors = outputs['anchors'][b]
317
+ if len(targets[b]['boxes']) == 0:
318
+ indices.append((torch.tensor([], dtype=torch.long, device=anchors.device),
319
+ torch.tensor([], dtype=torch.long, device=anchors.device)))
320
+ continue
321
+ iou, _ = box_iou(
322
+ box_cxcywh_to_xyxy(targets[b]['boxes']),
323
+ box_cxcywh_to_xyxy(anchors),
324
+ )
325
+ matched_idxs, matched_labels = self.anchor_matcher(iou) # proposal_id -> highest_iou_gt_id, proposal_id -> [1 if iou > 0.7, 0 if iou < 0.3, -1 ow]
326
+ matched_labels = self._subsample_labels(matched_labels)
327
+
328
+ all_pr_inds = torch.arange(len(anchors))
329
+ pos_pr_inds = all_pr_inds[matched_labels == 1]
330
+ pos_gt_inds = matched_idxs[pos_pr_inds]
331
+ pos_ious = iou[pos_gt_inds, pos_pr_inds]
332
+ pos_pr_inds, pos_gt_inds = self.postprocess_indices(pos_pr_inds, pos_gt_inds, iou)
333
+ pos_pr_inds, pos_gt_inds = pos_pr_inds.to(anchors.device), pos_gt_inds.to(anchors.device)
334
+ indices.append((pos_pr_inds, pos_gt_inds))
335
+ return indices
336
+
337
+ def postprocess_indices(self, pr_inds, gt_inds, iou):
338
+ return sample_topk_per_gt(pr_inds, gt_inds, iou, self.k)
models/deformable_detr/backbone.py ADDED
@@ -0,0 +1,163 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ # ------------------------------------------------------------------------
2
+ # Deformable DETR
3
+ # Copyright (c) 2020 SenseTime. All Rights Reserved.
4
+ # Licensed under the Apache License, Version 2.0 [see LICENSE for details]
5
+ # ------------------------------------------------------------------------
6
+ # Modified from DETR (https://github.com/facebookresearch/detr)
7
+ # Copyright (c) Facebook, Inc. and its affiliates. All Rights Reserved
8
+ # ------------------------------------------------------------------------
9
+
10
+ """
11
+ Backbone modules.
12
+ """
13
+ from collections import OrderedDict
14
+ from typing import Dict, List
15
+
16
+ import torch
17
+ import torch.nn.functional as F
18
+ import torchvision
19
+ from torch import nn
20
+ from torchvision.models._utils import IntermediateLayerGetter
21
+
22
+ from util.misc import NestedTensor, is_main_process
23
+
24
+ from .position_encoding import build_position_encoding
25
+ from .swin import get_swinb, get_swinl
26
+
27
+
28
+ class FrozenBatchNorm2d(torch.nn.Module):
29
+ """
30
+ BatchNorm2d where the batch statistics and the affine parameters are fixed.
31
+
32
+ Copy-paste from torchvision.misc.ops with added eps before rqsrt,
33
+ without which any other models than torchvision.models.resnet[18,34,50,101]
34
+ produce nans.
35
+ """
36
+
37
+ def __init__(self, n, eps=1e-5):
38
+ super(FrozenBatchNorm2d, self).__init__()
39
+ self.register_buffer("weight", torch.ones(n))
40
+ self.register_buffer("bias", torch.zeros(n))
41
+ self.register_buffer("running_mean", torch.zeros(n))
42
+ self.register_buffer("running_var", torch.ones(n))
43
+ self.eps = eps
44
+
45
+ def _load_from_state_dict(self, state_dict, prefix, local_metadata, strict,
46
+ missing_keys, unexpected_keys, error_msgs):
47
+ num_batches_tracked_key = prefix + 'num_batches_tracked'
48
+ if num_batches_tracked_key in state_dict:
49
+ del state_dict[num_batches_tracked_key]
50
+
51
+ super(FrozenBatchNorm2d, self)._load_from_state_dict(
52
+ state_dict, prefix, local_metadata, strict,
53
+ missing_keys, unexpected_keys, error_msgs)
54
+
55
+ def forward(self, x):
56
+ # move reshapes to the beginning
57
+ # to make it fuser-friendly
58
+ w = self.weight.reshape(1, -1, 1, 1)
59
+ b = self.bias.reshape(1, -1, 1, 1)
60
+ rv = self.running_var.reshape(1, -1, 1, 1)
61
+ rm = self.running_mean.reshape(1, -1, 1, 1)
62
+ eps = self.eps
63
+ scale = w * (rv + eps).rsqrt()
64
+ bias = b - rm * scale
65
+ return x * scale + bias
66
+
67
+
68
+ class BackboneBase(nn.Module):
69
+
70
+ def __init__(self, backbone: nn.Module, train_backbone: bool, return_interm_layers: bool):
71
+ super().__init__()
72
+ for name, parameter in backbone.named_parameters():
73
+ if not train_backbone or 'layer2' not in name and 'layer3' not in name and 'layer4' not in name:
74
+ parameter.requires_grad_(False)
75
+ if return_interm_layers:
76
+ # return_layers = {"layer1": "0", "layer2": "1", "layer3": "2", "layer4": "3"}
77
+ return_layers = {"layer2": "0", "layer3": "1", "layer4": "2"}
78
+ self.strides = [8, 16, 32]
79
+ self.num_channels = [512, 1024, 2048]
80
+ else:
81
+ return_layers = {'layer4': "0"}
82
+ self.strides = [32]
83
+ self.num_channels = [2048]
84
+ self.body = IntermediateLayerGetter(backbone, return_layers=return_layers)
85
+
86
+ def forward(self, tensor_list: NestedTensor):
87
+ xs = self.body(tensor_list.tensors)
88
+ out: Dict[str, NestedTensor] = {}
89
+ for name, x in xs.items():
90
+ m = tensor_list.mask
91
+ assert m is not None
92
+ mask = F.interpolate(m[None].float(), size=x.shape[-2:]).to(torch.bool)[0]
93
+ out[name] = NestedTensor(x, mask)
94
+ return out
95
+
96
+
97
+ class Backbone(BackboneBase):
98
+ """ResNet backbone with frozen BatchNorm."""
99
+ def __init__(self, name: str,
100
+ train_backbone: bool,
101
+ return_interm_layers: bool,
102
+ dilation: bool):
103
+ norm_layer = FrozenBatchNorm2d
104
+ backbone = getattr(torchvision.models, name)(
105
+ replace_stride_with_dilation=[False, False, dilation],
106
+ pretrained=is_main_process(), norm_layer=norm_layer)
107
+ assert name not in ('resnet18', 'resnet34'), "number of channels are hard coded"
108
+ super().__init__(backbone, train_backbone, return_interm_layers)
109
+ if dilation:
110
+ self.strides[-1] = self.strides[-1] // 2
111
+
112
+
113
+ class SwinBackbone(nn.Module):
114
+ def __init__(self):
115
+ # we skip R50 FrozenBatchNorm2d, dilation, train l{2,3,4} only
116
+ super().__init__()
117
+ # self.body = get_swinl()
118
+ self.body = get_swinb()
119
+ self.features = ['res3', 'res4', 'res5']
120
+ self.strides = [8, 16, 32]
121
+ self.num_channels = [256, 512, 1024]
122
+
123
+ def forward(self, tensor_list: NestedTensor):
124
+ xs = self.body(tensor_list.tensors)
125
+ m = tensor_list.mask[None]
126
+ assert m is not None
127
+ out: Dict[str, NestedTensor] = {}
128
+ for name in self.features:
129
+ mask = F.interpolate(m.float(), size=xs[name].shape[-2:]).to(torch.bool)[0]
130
+ out[name] = NestedTensor(xs[name], mask)
131
+ return out
132
+
133
+
134
+ class Joiner(nn.Sequential):
135
+ def __init__(self, backbone, position_embedding):
136
+ super().__init__(backbone, position_embedding)
137
+ self.strides = backbone.strides
138
+ self.num_channels = backbone.num_channels
139
+
140
+ def forward(self, tensor_list: NestedTensor):
141
+ xs = self[0](tensor_list)
142
+ out: List[NestedTensor] = []
143
+ pos = []
144
+ for name, x in sorted(xs.items()):
145
+ out.append(x)
146
+
147
+ # position encoding
148
+ for x in out:
149
+ pos.append(self[1](x).to(x.tensors.dtype))
150
+
151
+ return out, pos
152
+
153
+
154
+ def build_backbone(args):
155
+ position_embedding = build_position_encoding(args)
156
+ train_backbone = args.lr_backbone > 0
157
+ return_interm_layers = args.masks or (args.num_feature_levels > 1)
158
+ if 'swin' in args.backbone:
159
+ backbone = SwinBackbone()
160
+ else:
161
+ backbone = Backbone(args.backbone, train_backbone, return_interm_layers, args.dilation)
162
+ model = Joiner(backbone, position_embedding)
163
+ return model
models/deformable_detr/deformable_detr.py ADDED
@@ -0,0 +1,582 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ # ------------------------------------------------------------------------
2
+ # Deformable DETR
3
+ # Copyright (c) 2020 SenseTime. All Rights Reserved.
4
+ # Licensed under the Apache License, Version 2.0 [see LICENSE for details]
5
+ # ------------------------------------------------------------------------
6
+ # Modified from DETR (https://github.com/facebookresearch/detr)
7
+ # Copyright (c) Facebook, Inc. and its affiliates. All Rights Reserved
8
+ # ------------------------------------------------------------------------
9
+
10
+ """
11
+ Deformable DETR model and criterion classes.
12
+ """
13
+ import copy
14
+ import math
15
+
16
+ import torch
17
+ import torch.nn.functional as F
18
+ from torch import nn
19
+ from torchvision.ops.boxes import batched_nms
20
+
21
+ from util import box_ops
22
+ from util.misc import (NestedTensor, accuracy, get_world_size, interpolate,
23
+ inverse_sigmoid, is_dist_avail_and_initialized,
24
+ nested_tensor_from_tensor_list)
25
+
26
+ from .assigner import Stage1Assigner, Stage2Assigner
27
+ from .backbone import build_backbone
28
+ from .deformable_transformer import build_deforamble_transformer
29
+ from .matcher import build_matcher
30
+ from .segmentation import (DETRsegm, PostProcessPanoptic, PostProcessSegm,
31
+ dice_loss, sigmoid_focal_loss)
32
+
33
+
34
+ def _get_clones(module, N):
35
+ return nn.ModuleList([copy.deepcopy(module) for i in range(N)])
36
+
37
+
38
+ class DeformableDETR(nn.Module):
39
+ """ This is the Deformable DETR module that performs object detection """
40
+ def __init__(self, backbone, transformer, num_classes, num_queries, num_feature_levels,
41
+ aux_loss=True, with_box_refine=False, two_stage=False):
42
+ """ Initializes the model.
43
+ Parameters:
44
+ backbone: torch module of the backbone to be used. See backbone.py
45
+ transformer: torch module of the transformer architecture. See transformer.py
46
+ num_classes: number of object classes
47
+ num_queries: number of object queries, ie detection slot. This is the maximal number of objects
48
+ DETR can detect in a single image. For COCO, we recommend 100 queries.
49
+ aux_loss: True if auxiliary decoding losses (loss at each decoder layer) are to be used.
50
+ with_box_refine: iterative bounding box refinement
51
+ two_stage: two-stage Deformable DETR
52
+ """
53
+ super().__init__()
54
+ self.num_queries = num_queries
55
+ self.transformer = transformer
56
+ hidden_dim = transformer.d_model
57
+ self.class_embed = nn.Linear(hidden_dim, num_classes)
58
+ self.bbox_embed = MLP(hidden_dim, hidden_dim, 4, 3)
59
+ self.num_feature_levels = num_feature_levels
60
+ if not two_stage:
61
+ self.query_embed = nn.Embedding(num_queries, hidden_dim*2)
62
+ if num_feature_levels > 1:
63
+ num_backbone_outs = len(backbone.strides)
64
+ input_proj_list = []
65
+ for _ in range(num_backbone_outs):
66
+ in_channels = backbone.num_channels[_]
67
+ input_proj_list.append(nn.Sequential(
68
+ nn.Conv2d(in_channels, hidden_dim, kernel_size=1),
69
+ nn.GroupNorm(32, hidden_dim),
70
+ ))
71
+ for _ in range(num_feature_levels - num_backbone_outs):
72
+ input_proj_list.append(nn.Sequential(
73
+ nn.Conv2d(in_channels, hidden_dim, kernel_size=3, stride=2, padding=1),
74
+ nn.GroupNorm(32, hidden_dim),
75
+ ))
76
+ in_channels = hidden_dim
77
+ self.input_proj = nn.ModuleList(input_proj_list)
78
+ else:
79
+ self.input_proj = nn.ModuleList([
80
+ nn.Sequential(
81
+ nn.Conv2d(backbone.num_channels[0], hidden_dim, kernel_size=1),
82
+ nn.GroupNorm(32, hidden_dim),
83
+ )])
84
+ self.backbone = backbone
85
+ self.aux_loss = aux_loss
86
+ self.with_box_refine = with_box_refine
87
+ self.two_stage = two_stage
88
+
89
+ prior_prob = 0.01
90
+ bias_value = -math.log((1 - prior_prob) / prior_prob)
91
+ self.class_embed.bias.data = torch.ones(num_classes) * bias_value
92
+ nn.init.constant_(self.bbox_embed.layers[-1].weight.data, 0)
93
+ nn.init.constant_(self.bbox_embed.layers[-1].bias.data, 0)
94
+ for proj in self.input_proj:
95
+ nn.init.xavier_uniform_(proj[0].weight, gain=1)
96
+ nn.init.constant_(proj[0].bias, 0)
97
+
98
+ # if two-stage, the last class_embed and bbox_embed is for region proposal generation
99
+ num_pred = (transformer.decoder.num_layers + 1) if two_stage else transformer.decoder.num_layers
100
+ if with_box_refine:
101
+ self.class_embed = _get_clones(self.class_embed, num_pred)
102
+ self.bbox_embed = _get_clones(self.bbox_embed, num_pred)
103
+ nn.init.constant_(self.bbox_embed[0].layers[-1].bias.data[2:], -2.0)
104
+ # hack implementation for iterative bounding box refinement
105
+ self.transformer.decoder.bbox_embed = self.bbox_embed
106
+ else:
107
+ nn.init.constant_(self.bbox_embed.layers[-1].bias.data[2:], -2.0)
108
+ self.class_embed = nn.ModuleList([self.class_embed for _ in range(num_pred)])
109
+ self.bbox_embed = nn.ModuleList([self.bbox_embed for _ in range(num_pred)])
110
+ self.transformer.decoder.bbox_embed = None
111
+ if two_stage:
112
+ # hack implementation for two-stage
113
+ self.transformer.decoder.class_embed = self.class_embed
114
+ for box_embed in self.bbox_embed:
115
+ nn.init.constant_(box_embed.layers[-1].bias.data[2:], 0.0)
116
+
117
+ def forward(self, samples: NestedTensor):
118
+ """ The forward expects a NestedTensor, which consists of:
119
+ - samples.tensor: batched images, of shape [batch_size x 3 x H x W]
120
+ - samples.mask: a binary mask of shape [batch_size x H x W], containing 1 on padded pixels
121
+
122
+ It returns a dict with the following elements:
123
+ - "pred_logits": the classification logits (including no-object) for all queries.
124
+ Shape= [batch_size x num_queries x (num_classes + 1)]
125
+ - "pred_boxes": The normalized boxes coordinates for all queries, represented as
126
+ (center_x, center_y, height, width). These values are normalized in [0, 1],
127
+ relative to the size of each individual image (disregarding possible padding).
128
+ See PostProcess for information on how to retrieve the unnormalized bounding box.
129
+ - "aux_outputs": Optional, only returned when auxilary losses are activated. It is a list of
130
+ dictionnaries containing the two above keys for each decoder layer.
131
+ """
132
+ if not isinstance(samples, NestedTensor):
133
+ samples = nested_tensor_from_tensor_list(samples)
134
+ features, pos = self.backbone(samples)
135
+
136
+ srcs = []
137
+ masks = []
138
+ for l, feat in enumerate(features):
139
+ src, mask = feat.decompose()
140
+ srcs.append(self.input_proj[l](src))
141
+ masks.append(mask)
142
+ assert mask is not None
143
+ if self.num_feature_levels > len(srcs):
144
+ _len_srcs = len(srcs)
145
+ for l in range(_len_srcs, self.num_feature_levels):
146
+ if l == _len_srcs:
147
+ src = self.input_proj[l](features[-1].tensors)
148
+ else:
149
+ src = self.input_proj[l](srcs[-1])
150
+ m = samples.mask
151
+ mask = F.interpolate(m[None].float(), size=src.shape[-2:]).to(torch.bool)[0]
152
+ pos_l = self.backbone[1](NestedTensor(src, mask)).to(src.dtype)
153
+ srcs.append(src)
154
+ masks.append(mask)
155
+ pos.append(pos_l)
156
+
157
+ query_embeds = None
158
+ if not self.two_stage:
159
+ query_embeds = self.query_embed.weight
160
+ hs, init_reference, inter_references, enc_outputs_class, enc_outputs_coord_unact, anchors = self.transformer(srcs, masks, pos, query_embeds)
161
+
162
+ outputs_classes = []
163
+ outputs_coords = []
164
+ for lvl in range(hs.shape[0]):
165
+ if lvl == 0:
166
+ reference = init_reference
167
+ else:
168
+ reference = inter_references[lvl - 1]
169
+ reference = inverse_sigmoid(reference)
170
+ outputs_class = self.class_embed[lvl](hs[lvl])
171
+ tmp = self.bbox_embed[lvl](hs[lvl])
172
+ if reference.shape[-1] == 4:
173
+ tmp += reference
174
+ else:
175
+ assert reference.shape[-1] == 2
176
+ tmp[..., :2] += reference
177
+ outputs_coord = tmp.sigmoid()
178
+ outputs_classes.append(outputs_class)
179
+ outputs_coords.append(outputs_coord)
180
+ outputs_class = torch.stack(outputs_classes)
181
+ outputs_coord = torch.stack(outputs_coords)
182
+
183
+ out = {'pred_logits': outputs_class[-1], 'pred_boxes': outputs_coord[-1],
184
+ 'init_reference': init_reference}
185
+ if self.aux_loss:
186
+ out['aux_outputs'] = self._set_aux_loss(outputs_class, outputs_coord)
187
+
188
+ if self.two_stage:
189
+ enc_outputs_coord = enc_outputs_coord_unact.sigmoid()
190
+ out['enc_outputs'] = {
191
+ 'pred_logits': enc_outputs_class,
192
+ 'pred_boxes': enc_outputs_coord,
193
+ 'anchors': anchors,
194
+ }
195
+ return out
196
+
197
+ @torch.jit.unused
198
+ def _set_aux_loss(self, outputs_class, outputs_coord):
199
+ # this is a workaround to make torchscript happy, as torchscript
200
+ # doesn't support dictionary with non-homogeneous values, such
201
+ # as a dict having both a Tensor and a list.
202
+ return [{'pred_logits': a, 'pred_boxes': b}
203
+ for a, b in zip(outputs_class[:-1], outputs_coord[:-1])]
204
+
205
+
206
+ class SetCriterion(nn.Module):
207
+ """ This class computes the loss for DETR.
208
+ The process happens in two steps:
209
+ 1) we compute hungarian assignment between ground truth boxes and the outputs of the model
210
+ 2) we supervise each pair of matched ground-truth / prediction (supervise class and box)
211
+ """
212
+ def __init__(self, num_classes, matcher, weight_dict, losses, focal_alpha=0.25,
213
+ num_queries=300, assign_first_stage=False, assign_second_stage=False):
214
+ """ Create the criterion.
215
+ Parameters:
216
+ num_classes: number of object categories, omitting the special no-object category
217
+ matcher: module able to compute a matching between targets and proposals
218
+ weight_dict: dict containing as key the names of the losses and as values their relative weight.
219
+ losses: list of all the losses to be applied. See get_loss for list of available losses.
220
+ focal_alpha: alpha in Focal Loss
221
+ """
222
+ super().__init__()
223
+ self.num_classes = num_classes
224
+ self.matcher = matcher
225
+ self.weight_dict = weight_dict
226
+ self.losses = losses
227
+ self.focal_alpha = focal_alpha
228
+ self.assign_first_stage = assign_first_stage
229
+ self.assign_second_stage = assign_second_stage
230
+
231
+ if self.assign_first_stage:
232
+ self.stg1_assigner = Stage1Assigner()
233
+ if self.assign_second_stage:
234
+ self.stg2_assigner = Stage2Assigner(num_queries)
235
+
236
+ def loss_labels(self, outputs, targets, indices, num_boxes, log=True):
237
+ """Classification loss (NLL)
238
+ targets dicts must contain the key "labels" containing a tensor of dim [nb_target_boxes]
239
+ """
240
+ assert 'pred_logits' in outputs
241
+ src_logits = outputs['pred_logits']
242
+
243
+ idx = self._get_src_permutation_idx(indices)
244
+ target_classes_o = torch.cat([t["labels"][J] for t, (_, J) in zip(targets, indices)])
245
+ target_classes = torch.full(src_logits.shape[:2], self.num_classes,
246
+ dtype=torch.int64, device=src_logits.device)
247
+ target_classes[idx] = target_classes_o
248
+
249
+ target_classes_onehot = torch.zeros([src_logits.shape[0], src_logits.shape[1], src_logits.shape[2] + 1],
250
+ dtype=src_logits.dtype, layout=src_logits.layout, device=src_logits.device)
251
+ target_classes_onehot.scatter_(2, target_classes.unsqueeze(-1), 1)
252
+
253
+ target_classes_onehot = target_classes_onehot[:,:,:-1]
254
+ loss_ce = sigmoid_focal_loss(src_logits, target_classes_onehot, num_boxes, alpha=self.focal_alpha, gamma=2) * src_logits.shape[1]
255
+ losses = {'loss_ce': loss_ce}
256
+
257
+ if log:
258
+ # TODO this should probably be a separate loss, not hacked in this one here
259
+ losses['class_error'] = 100 - accuracy(src_logits[idx], target_classes_o)[0]
260
+ return losses
261
+
262
+ @torch.no_grad()
263
+ def loss_cardinality(self, outputs, targets, indices, num_boxes):
264
+ """ Compute the cardinality error, ie the absolute error in the number of predicted non-empty boxes
265
+ This is not really a loss, it is intended for logging purposes only. It doesn't propagate gradients
266
+ """
267
+ pred_logits = outputs['pred_logits']
268
+ device = pred_logits.device
269
+ tgt_lengths = torch.as_tensor([len(v["labels"]) for v in targets], device=device)
270
+ # Count the number of predictions that are NOT "no-object" (which is the last class)
271
+ card_pred = (pred_logits.argmax(-1) != pred_logits.shape[-1] - 1).sum(1)
272
+ card_err = F.l1_loss(card_pred.float(), tgt_lengths.float())
273
+ losses = {'cardinality_error': card_err}
274
+ return losses
275
+
276
+ def loss_boxes(self, outputs, targets, indices, num_boxes):
277
+ """Compute the losses related to the bounding boxes, the L1 regression loss and the GIoU loss
278
+ targets dicts must contain the key "boxes" containing a tensor of dim [nb_target_boxes, 4]
279
+ The target boxes are expected in format (center_x, center_y, h, w), normalized by the image size.
280
+ """
281
+ assert 'pred_boxes' in outputs
282
+ idx = self._get_src_permutation_idx(indices)
283
+ src_boxes = outputs['pred_boxes'][idx]
284
+ target_boxes = torch.cat([t['boxes'][i] for t, (_, i) in zip(targets, indices)], dim=0)
285
+
286
+ loss_bbox = F.l1_loss(src_boxes, target_boxes, reduction='none')
287
+
288
+ losses = {}
289
+ losses['loss_bbox'] = loss_bbox.sum() / num_boxes
290
+
291
+ loss_giou = 1 - torch.diag(box_ops.generalized_box_iou(
292
+ box_ops.box_cxcywh_to_xyxy(src_boxes),
293
+ box_ops.box_cxcywh_to_xyxy(target_boxes)))
294
+ losses['loss_giou'] = loss_giou.sum() / num_boxes
295
+ return losses
296
+
297
+ def loss_masks(self, outputs, targets, indices, num_boxes):
298
+ """Compute the losses related to the masks: the focal loss and the dice loss.
299
+ targets dicts must contain the key "masks" containing a tensor of dim [nb_target_boxes, h, w]
300
+ """
301
+ assert "pred_masks" in outputs
302
+
303
+ src_idx = self._get_src_permutation_idx(indices)
304
+ tgt_idx = self._get_tgt_permutation_idx(indices)
305
+
306
+ src_masks = outputs["pred_masks"]
307
+
308
+ # TODO use valid to mask invalid areas due to padding in loss
309
+ target_masks, valid = nested_tensor_from_tensor_list([t["masks"] for t in targets]).decompose()
310
+ target_masks = target_masks.to(src_masks)
311
+
312
+ src_masks = src_masks[src_idx]
313
+ # upsample predictions to the target size
314
+ src_masks = interpolate(src_masks[:, None], size=target_masks.shape[-2:],
315
+ mode="bilinear", align_corners=False)
316
+ src_masks = src_masks[:, 0].flatten(1)
317
+
318
+ target_masks = target_masks[tgt_idx].flatten(1)
319
+
320
+ losses = {
321
+ "loss_mask": sigmoid_focal_loss(src_masks, target_masks, num_boxes),
322
+ "loss_dice": dice_loss(src_masks, target_masks, num_boxes),
323
+ }
324
+ return losses
325
+
326
+ def _get_src_permutation_idx(self, indices):
327
+ # permute predictions following indices
328
+ batch_idx = torch.cat([torch.full_like(src, i) for i, (src, _) in enumerate(indices)])
329
+ src_idx = torch.cat([src for (src, _) in indices])
330
+ return batch_idx, src_idx
331
+
332
+ def _get_tgt_permutation_idx(self, indices):
333
+ # permute targets following indices
334
+ batch_idx = torch.cat([torch.full_like(tgt, i) for i, (_, tgt) in enumerate(indices)])
335
+ tgt_idx = torch.cat([tgt for (_, tgt) in indices])
336
+ return batch_idx, tgt_idx
337
+
338
+ def get_loss(self, loss, outputs, targets, indices, num_boxes, **kwargs):
339
+ loss_map = {
340
+ 'labels': self.loss_labels,
341
+ 'cardinality': self.loss_cardinality,
342
+ 'boxes': self.loss_boxes,
343
+ 'masks': self.loss_masks
344
+ }
345
+ assert loss in loss_map, f'do you really want to compute {loss} loss?'
346
+ return loss_map[loss](outputs, targets, indices, num_boxes, **kwargs)
347
+
348
+ def forward(self, outputs, targets):
349
+ """ This performs the loss computation.
350
+ Parameters:
351
+ outputs: dict of tensors, see the output specification of the model for the format
352
+ targets: list of dicts, such that len(targets) == batch_size.
353
+ The expected keys in each dict depends on the losses applied, see each loss' doc
354
+ """
355
+ outputs_without_aux = {k: v for k, v in outputs.items() if k != 'aux_outputs' and k != 'enc_outputs'}
356
+
357
+ # Retrieve the matching between the outputs of the last layer and the targets
358
+ if self.assign_second_stage:
359
+ indices = self.stg2_assigner(outputs_without_aux, targets)
360
+ else:
361
+ indices = self.matcher(outputs_without_aux, targets)
362
+
363
+ # Compute the average number of target boxes accross all nodes, for normalization purposes
364
+ num_boxes = sum(len(t["labels"]) for t in targets)
365
+ num_boxes = torch.as_tensor([num_boxes], dtype=torch.float, device=next(iter(outputs.values())).device)
366
+ if is_dist_avail_and_initialized():
367
+ torch.distributed.all_reduce(num_boxes)
368
+ num_boxes = torch.clamp(num_boxes / get_world_size(), min=1).item()
369
+
370
+ # Compute all the requested losses
371
+ losses = {}
372
+ for loss in self.losses:
373
+ kwargs = {}
374
+ losses.update(self.get_loss(loss, outputs, targets, indices, num_boxes, **kwargs))
375
+
376
+ # In case of auxiliary losses, we repeat this process with the output of each intermediate layer.
377
+ if 'aux_outputs' in outputs:
378
+ for i, aux_outputs in enumerate(outputs['aux_outputs']):
379
+ if not self.assign_second_stage:
380
+ indices = self.matcher(aux_outputs, targets)
381
+ for loss in self.losses:
382
+ if loss == 'masks':
383
+ # Intermediate masks losses are too costly to compute, we ignore them.
384
+ continue
385
+ kwargs = {}
386
+ if loss == 'labels':
387
+ # Logging is enabled only for the last layer
388
+ kwargs['log'] = False
389
+ l_dict = self.get_loss(loss, aux_outputs, targets, indices, num_boxes, **kwargs)
390
+ l_dict = {k + f'_{i}': v for k, v in l_dict.items()}
391
+ losses.update(l_dict)
392
+
393
+ if 'enc_outputs' in outputs:
394
+ enc_outputs = outputs['enc_outputs']
395
+ bin_targets = copy.deepcopy(targets)
396
+ for bt in bin_targets:
397
+ bt['labels'] = torch.zeros_like(bt['labels'])
398
+ if self.assign_first_stage:
399
+ indices = self.stg1_assigner(enc_outputs, bin_targets)
400
+ else:
401
+ indices = self.matcher(enc_outputs, bin_targets)
402
+ for loss in self.losses:
403
+ if loss == 'masks':
404
+ # Intermediate masks losses are too costly to compute, we ignore them.
405
+ continue
406
+ kwargs = {}
407
+ if loss == 'labels':
408
+ # Logging is enabled only for the last layer
409
+ kwargs['log'] = False
410
+ l_dict = self.get_loss(loss, enc_outputs, bin_targets, indices, num_boxes, **kwargs)
411
+ l_dict = {k + f'_enc': v for k, v in l_dict.items()}
412
+ losses.update(l_dict)
413
+
414
+ return losses
415
+
416
+
417
+ class PostProcess(nn.Module):
418
+ """ This module converts the model's output into the format expected by the coco api"""
419
+
420
+ @torch.no_grad()
421
+ def forward(self, outputs, target_sizes):
422
+ """ Perform the computation
423
+ Parameters:
424
+ outputs: raw outputs of the model
425
+ target_sizes: tensor of dimension [batch_size x 2] containing the size of each images of the batch
426
+ For evaluation, this must be the original image size (before any data augmentation)
427
+ For visualization, this should be the image size after data augment, but before padding
428
+ """
429
+ out_logits, out_bbox = outputs['pred_logits'], outputs['pred_boxes']
430
+
431
+ assert len(out_logits) == len(target_sizes)
432
+ assert target_sizes.shape[1] == 2
433
+
434
+ prob = out_logits.sigmoid()
435
+ topk_values, topk_indexes = torch.topk(prob.view(out_logits.shape[0], -1), 100, dim=1)
436
+ scores = topk_values
437
+ # topk_boxes = topk_indexes // out_logits.shape[2]
438
+ topk_boxes = torch.div(topk_indexes, out_logits.shape[2], rounding_mode='floor')
439
+ labels = topk_indexes % out_logits.shape[2]
440
+ boxes = box_ops.box_cxcywh_to_xyxy(out_bbox)
441
+ boxes = torch.gather(boxes, 1, topk_boxes.unsqueeze(-1).repeat(1,1,4))
442
+
443
+ # and from relative [0, 1] to absolute [0, height] coordinates
444
+ img_h, img_w = target_sizes.unbind(1)
445
+ scale_fct = torch.stack([img_w, img_h, img_w, img_h], dim=1)
446
+ boxes = boxes * scale_fct[:, None, :]
447
+
448
+ results = [{'scores': s, 'labels': l, 'boxes': b} for s, l, b in zip(scores, labels, boxes)]
449
+
450
+ return results
451
+
452
+ class NMSPostProcess(nn.Module):
453
+ """ This module converts the model's output into the format expected by the coco api"""
454
+
455
+ @torch.no_grad()
456
+ def forward(self, outputs, target_sizes):
457
+ """ Perform the computation
458
+ Parameters:
459
+ outputs: raw outputs of the model
460
+ target_sizes: tensor of dimension [batch_size x 2] containing the size of each images of the batch
461
+ For evaluation, this must be the original image size (before any data augmentation)
462
+ For visualization, this should be the image size after data augment, but before padding
463
+ """
464
+ out_logits, out_bbox = outputs['pred_logits'], outputs['pred_boxes']
465
+ bs, n_queries, n_cls = out_logits.shape
466
+
467
+ assert len(out_logits) == len(target_sizes)
468
+ assert target_sizes.shape[1] == 2
469
+
470
+ prob = out_logits.sigmoid()
471
+
472
+ all_scores = prob.view(bs, n_queries * n_cls).to(out_logits.device)
473
+ all_indexes = torch.arange(n_queries * n_cls)[None].repeat(bs, 1).to(out_logits.device)
474
+ all_boxes = all_indexes // out_logits.shape[2]
475
+ all_labels = all_indexes % out_logits.shape[2]
476
+
477
+ boxes = box_ops.box_cxcywh_to_xyxy(out_bbox)
478
+ boxes = torch.gather(boxes, 1, all_boxes.unsqueeze(-1).repeat(1,1,4))
479
+
480
+ # and from relative [0, 1] to absolute [0, height] coordinates
481
+ img_h, img_w = target_sizes.unbind(1)
482
+ scale_fct = torch.stack([img_w, img_h, img_w, img_h], dim=1)
483
+ boxes = boxes * scale_fct[:, None, :]
484
+
485
+ results = []
486
+ for b in range(bs):
487
+ box = boxes[b]
488
+ score = all_scores[b]
489
+ lbls = all_labels[b]
490
+
491
+ topk = min(len(score), 10000)
492
+ pre_topk = score.topk(topk).indices
493
+ box = box[pre_topk]
494
+ score = score[pre_topk]
495
+ lbls = lbls[pre_topk]
496
+
497
+ keep_inds = batched_nms(box, score, lbls, 0.7)[:100]
498
+ results.append({
499
+ 'scores': score[keep_inds],
500
+ 'labels': lbls[keep_inds],
501
+ 'boxes': box[keep_inds],
502
+ })
503
+
504
+ return results
505
+
506
+
507
+
508
+ class MLP(nn.Module):
509
+ """ Very simple multi-layer perceptron (also called FFN)"""
510
+
511
+ def __init__(self, input_dim, hidden_dim, output_dim, num_layers):
512
+ super().__init__()
513
+ self.num_layers = num_layers
514
+ h = [hidden_dim] * (num_layers - 1)
515
+ self.layers = nn.ModuleList(nn.Linear(n, k) for n, k in zip([input_dim] + h, h + [output_dim]))
516
+
517
+ def forward(self, x):
518
+ for i, layer in enumerate(self.layers):
519
+ x = F.relu(layer(x)) if i < self.num_layers - 1 else layer(x)
520
+ return x
521
+
522
+
523
+ def build(args):
524
+ if args.dataset_file == 'coco':
525
+ num_classes = 91
526
+ elif args.dataset_file in ['refcoco', 'refcoco+', 'refcocog']:
527
+ num_classes = 91
528
+ elif args.dataset_file == "coco_panoptic":
529
+ num_classes = 250
530
+ else:
531
+ num_classes = 20
532
+ device = torch.device(args.device)
533
+
534
+ backbone = build_backbone(args)
535
+
536
+ transformer = build_deforamble_transformer(args)
537
+ model = DeformableDETR(
538
+ backbone,
539
+ transformer,
540
+ num_classes=num_classes,
541
+ num_queries=args.num_queries,
542
+ num_feature_levels=args.num_feature_levels,
543
+ aux_loss=args.aux_loss,
544
+ with_box_refine=args.with_box_refine,
545
+ two_stage=args.two_stage,
546
+ )
547
+ if args.masks:
548
+ model = DETRsegm(model, freeze_detr=(args.frozen_weights is not None))
549
+ matcher = build_matcher(args)
550
+ weight_dict = {'loss_ce': args.cls_loss_coef, 'loss_bbox': args.bbox_loss_coef}
551
+ weight_dict['loss_giou'] = args.giou_loss_coef
552
+ if args.masks:
553
+ weight_dict["loss_mask"] = args.mask_loss_coef
554
+ weight_dict["loss_dice"] = args.dice_loss_coef
555
+ # TODO this is a hack
556
+ if args.aux_loss:
557
+ aux_weight_dict = {}
558
+ for i in range(args.dec_layers - 1):
559
+ aux_weight_dict.update({k + f'_{i}': v for k, v in weight_dict.items()})
560
+ aux_weight_dict.update({k + f'_enc': v for k, v in weight_dict.items()})
561
+ weight_dict.update(aux_weight_dict)
562
+
563
+ losses = ['labels', 'boxes', 'cardinality']
564
+ if args.masks:
565
+ losses += ["masks"]
566
+ # num_classes, matcher, weight_dict, losses, focal_alpha=0.25
567
+ criterion = SetCriterion(num_classes, matcher, weight_dict, losses, focal_alpha=args.focal_alpha,
568
+ num_queries = args.num_queries,
569
+ assign_first_stage=args.assign_first_stage,
570
+ assign_second_stage=args.assign_second_stage)
571
+ criterion.to(device)
572
+ if args.assign_second_stage:
573
+ postprocessors = {'bbox': NMSPostProcess()}
574
+ else:
575
+ postprocessors = {'bbox': PostProcess()}
576
+ if args.masks:
577
+ postprocessors['segm'] = PostProcessSegm()
578
+ if args.dataset_file == "coco_panoptic":
579
+ is_thing_map = {i: i <= 90 for i in range(201)}
580
+ postprocessors["panoptic"] = PostProcessPanoptic(is_thing_map, threshold=0.85)
581
+
582
+ return model, criterion, postprocessors
models/deformable_detr/deformable_transformer.py ADDED
@@ -0,0 +1,462 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ # ------------------------------------------------------------------------
2
+ # Deformable DETR
3
+ # Copyright (c) 2020 SenseTime. All Rights Reserved.
4
+ # Licensed under the Apache License, Version 2.0 [see LICENSE for details]
5
+ # ------------------------------------------------------------------------
6
+ # Modified from DETR (https://github.com/facebookresearch/detr)
7
+ # Copyright (c) Facebook, Inc. and its affiliates. All Rights Reserved
8
+ # ------------------------------------------------------------------------
9
+
10
+ import copy
11
+ import math
12
+ from typing import List, Optional
13
+
14
+ import torch
15
+ import torch.nn.functional as F
16
+ from torch import Tensor, nn
17
+ from torch.nn.init import constant_, normal_, uniform_, xavier_uniform_
18
+ from torchvision.ops.boxes import batched_nms
19
+
20
+ # from models.ops.modules import MSDeformAttn
21
+ from .ms_deform_attn import MultiScaleDeformableAttention as MSDeformAttn
22
+ from util.box_ops import box_cxcywh_to_xyxy
23
+ from util.misc import inverse_sigmoid
24
+
25
+
26
+ class DeformableTransformer(nn.Module):
27
+ def __init__(self, d_model=256, nhead=8,
28
+ num_encoder_layers=6, num_decoder_layers=6, dim_feedforward=1024, dropout=0.1,
29
+ activation="relu", return_intermediate_dec=False,
30
+ num_feature_levels=4, dec_n_points=4, enc_n_points=4,
31
+ two_stage=False, two_stage_num_proposals=300,
32
+ assign_first_stage=False):
33
+ super().__init__()
34
+
35
+ self.d_model = d_model
36
+ self.nhead = nhead
37
+ self.two_stage = two_stage
38
+ self.two_stage_num_proposals = two_stage_num_proposals
39
+ self.assign_first_stage = assign_first_stage
40
+
41
+ encoder_layer = DeformableTransformerEncoderLayer(d_model, dim_feedforward,
42
+ dropout, activation,
43
+ num_feature_levels, nhead, enc_n_points)
44
+ self.encoder = DeformableTransformerEncoder(encoder_layer, num_encoder_layers)
45
+
46
+ decoder_layer = DeformableTransformerDecoderLayer(d_model, dim_feedforward,
47
+ dropout, activation,
48
+ num_feature_levels, nhead, dec_n_points)
49
+ self.decoder = DeformableTransformerDecoder(decoder_layer, num_decoder_layers, return_intermediate_dec)
50
+
51
+ self.level_embed = nn.Parameter(torch.Tensor(num_feature_levels, d_model))
52
+
53
+ if two_stage:
54
+ self.enc_output = nn.Linear(d_model, d_model)
55
+ self.enc_output_norm = nn.LayerNorm(d_model)
56
+ self.pos_trans = nn.Linear(d_model * 2, d_model * 2)
57
+ self.pos_trans_norm = nn.LayerNorm(d_model * 2)
58
+ self.pix_trans = nn.Linear(d_model, d_model)
59
+ self.pix_trans_norm = nn.LayerNorm(d_model)
60
+ else:
61
+ self.reference_points = nn.Linear(d_model, 2)
62
+
63
+ self._reset_parameters()
64
+
65
+ def _reset_parameters(self):
66
+ for p in self.parameters():
67
+ if p.dim() > 1:
68
+ nn.init.xavier_uniform_(p)
69
+ for m in self.modules():
70
+ if isinstance(m, MSDeformAttn):
71
+ m._reset_parameters()
72
+ if not self.two_stage:
73
+ xavier_uniform_(self.reference_points.weight.data, gain=1.0)
74
+ constant_(self.reference_points.bias.data, 0.)
75
+ normal_(self.level_embed)
76
+
77
+ def get_proposal_pos_embed(self, proposals):
78
+ num_pos_feats = 128
79
+ temperature = 10000
80
+ scale = 2 * math.pi
81
+
82
+ dim_t = torch.arange(num_pos_feats, dtype=torch.float32, device=proposals.device)
83
+ dim_t = torch.div(dim_t, 2, rounding_mode='floor')
84
+ dim_t = temperature ** (2 * dim_t / num_pos_feats)
85
+ # N, L, 4
86
+ proposals = proposals.sigmoid() * scale
87
+ # N, L, 4, 128
88
+ pos = proposals[:, :, :, None] / dim_t
89
+ # N, L, 4, 64, 2
90
+ pos = torch.stack((pos[:, :, :, 0::2].sin(), pos[:, :, :, 1::2].cos()), dim=4).flatten(2)
91
+ return pos
92
+
93
+ def gen_encoder_output_proposals(self, memory, memory_padding_mask, spatial_shapes):
94
+ N_, S_, C_ = memory.shape
95
+ base_scale = 4.0
96
+ proposals = []
97
+ _cur = 0
98
+ level_ids = []
99
+ for lvl, (H_, W_) in enumerate(spatial_shapes):
100
+ mask_flatten_ = memory_padding_mask[:, _cur:(_cur + H_ * W_)].view(N_, H_, W_, 1)
101
+ valid_H = torch.sum(~mask_flatten_[:, :, 0, 0], 1)
102
+ valid_W = torch.sum(~mask_flatten_[:, 0, :, 0], 1)
103
+
104
+ grid_y, grid_x = torch.meshgrid(torch.linspace(0, H_ - 1, H_, dtype=torch.float32, device=memory.device),
105
+ torch.linspace(0, W_ - 1, W_, dtype=torch.float32, device=memory.device))
106
+ grid = torch.cat([grid_x.unsqueeze(-1), grid_y.unsqueeze(-1)], -1)
107
+
108
+ scale = torch.cat([valid_W.unsqueeze(-1), valid_H.unsqueeze(-1)], 1).view(N_, 1, 1, 2)
109
+ grid = (grid.unsqueeze(0).expand(N_, -1, -1, -1) + 0.5) / scale
110
+ wh = torch.ones_like(grid) * 0.05 * (2.0 ** lvl)
111
+ proposal = torch.cat((grid, wh), -1).view(N_, -1, 4)
112
+ proposals.append(proposal)
113
+ _cur += (H_ * W_)
114
+ level_ids.append(grid.new_ones(H_ * W_, dtype=torch.long) * lvl)
115
+ output_proposals = torch.cat(proposals, 1)
116
+ output_proposals_valid = ((output_proposals > 0.01) & (output_proposals < 0.99)).all(-1, keepdim=True)
117
+ output_proposals = torch.log(output_proposals / (1 - output_proposals))
118
+ output_proposals = output_proposals.masked_fill(memory_padding_mask.unsqueeze(-1), float('inf'))
119
+ output_proposals = output_proposals.masked_fill(~output_proposals_valid, float('inf'))
120
+
121
+ output_memory = memory
122
+ output_memory = output_memory.masked_fill(memory_padding_mask.unsqueeze(-1), float(0))
123
+ output_memory = output_memory.masked_fill(~output_proposals_valid, float(0))
124
+ output_memory = self.enc_output_norm(self.enc_output(output_memory))
125
+ level_ids = torch.cat(level_ids)
126
+ return output_memory, output_proposals, level_ids
127
+
128
+ def get_valid_ratio(self, mask):
129
+ _, H, W = mask.shape
130
+ valid_H = torch.sum(~mask[:, :, 0], 1)
131
+ valid_W = torch.sum(~mask[:, 0, :], 1)
132
+ valid_ratio_h = valid_H.float() / H
133
+ valid_ratio_w = valid_W.float() / W
134
+ valid_ratio = torch.stack([valid_ratio_w, valid_ratio_h], -1)
135
+ return valid_ratio
136
+
137
+ def forward(self, srcs, masks, pos_embeds, query_embed=None):
138
+ assert self.two_stage or query_embed is not None
139
+
140
+ # prepare input for encoder
141
+ src_flatten = []
142
+ mask_flatten = []
143
+ lvl_pos_embed_flatten = []
144
+ spatial_shapes = []
145
+ for lvl, (src, mask, pos_embed) in enumerate(zip(srcs, masks, pos_embeds)):
146
+ bs, c, h, w = src.shape
147
+ spatial_shape = (h, w)
148
+ spatial_shapes.append(spatial_shape)
149
+ src = src.flatten(2).transpose(1, 2)
150
+ mask = mask.flatten(1)
151
+ pos_embed = pos_embed.flatten(2).transpose(1, 2)
152
+ lvl_pos_embed = pos_embed + self.level_embed[lvl].view(1, 1, -1)
153
+ lvl_pos_embed_flatten.append(lvl_pos_embed)
154
+ src_flatten.append(src)
155
+ mask_flatten.append(mask)
156
+ src_flatten = torch.cat(src_flatten, 1)
157
+ mask_flatten = torch.cat(mask_flatten, 1)
158
+ lvl_pos_embed_flatten = torch.cat(lvl_pos_embed_flatten, 1)
159
+ spatial_shapes = torch.as_tensor(spatial_shapes, dtype=torch.long, device=src_flatten.device)
160
+ level_start_index = torch.cat((spatial_shapes.new_zeros((1, )), spatial_shapes.prod(1).cumsum(0)[:-1]))
161
+ valid_ratios = torch.stack([self.get_valid_ratio(m) for m in masks], 1)
162
+
163
+ # encoder
164
+ memory = self.encoder(src_flatten, spatial_shapes, level_start_index, valid_ratios, lvl_pos_embed_flatten, mask_flatten)
165
+
166
+ # prepare input for decoder
167
+ bs, _, c = memory.shape
168
+ if self.two_stage:
169
+ output_memory, output_proposals, level_ids = self.gen_encoder_output_proposals(memory, mask_flatten, spatial_shapes)
170
+
171
+ # hack implementation for two-stage Deformable DETR
172
+ enc_outputs_class = self.decoder.class_embed[self.decoder.num_layers](output_memory)
173
+ enc_outputs_coord_unact = self.decoder.bbox_embed[self.decoder.num_layers](output_memory) + output_proposals
174
+
175
+ topk = self.two_stage_num_proposals
176
+ proposal_logit = enc_outputs_class[..., 0]
177
+
178
+ if self.assign_first_stage:
179
+ proposal_boxes = box_cxcywh_to_xyxy(enc_outputs_coord_unact.sigmoid().float()).clamp(0, 1)
180
+ topk_proposals = []
181
+ for b in range(bs):
182
+ prop_boxes_b = proposal_boxes[b]
183
+ prop_logits_b = proposal_logit[b]
184
+
185
+ # pre-nms per-level topk
186
+ pre_nms_topk = 1000
187
+ pre_nms_inds = []
188
+ for lvl in range(len(spatial_shapes)):
189
+ lvl_mask = level_ids == lvl
190
+ pre_nms_inds.append(torch.topk(prop_logits_b.sigmoid() * lvl_mask, pre_nms_topk)[1])
191
+ pre_nms_inds = torch.cat(pre_nms_inds)
192
+
193
+ # nms on topk indices
194
+ post_nms_inds = batched_nms(prop_boxes_b[pre_nms_inds], prop_logits_b[pre_nms_inds], level_ids[pre_nms_inds], 0.9)
195
+ keep_inds = pre_nms_inds[post_nms_inds]
196
+
197
+ if len(keep_inds) < self.two_stage_num_proposals:
198
+ print(f'[WARNING] nms proposals ({len(keep_inds)}) < {self.two_stage_num_proposals}, running naive topk')
199
+ keep_inds = torch.topk(proposal_logit[b], topk)[1]
200
+
201
+ # keep top Q/L indices for L levels
202
+ q_per_l = topk // len(spatial_shapes)
203
+ is_level_ordered = level_ids[keep_inds][None] == torch.arange(len(spatial_shapes), device=level_ids.device)[:,None] # LS
204
+ keep_inds_mask = is_level_ordered & (is_level_ordered.cumsum(1) <= q_per_l) # LS
205
+ keep_inds_mask = keep_inds_mask.any(0) # S
206
+
207
+ # pad to Q indices (might let ones filtered from pre-nms sneak by... unlikely because we pick high conf anyways)
208
+ if keep_inds_mask.sum() < topk:
209
+ num_to_add = topk - keep_inds_mask.sum()
210
+ pad_inds = (~keep_inds_mask).nonzero()[:num_to_add]
211
+ keep_inds_mask[pad_inds] = True
212
+
213
+ # index
214
+ keep_inds_topk = keep_inds[keep_inds_mask]
215
+ topk_proposals.append(keep_inds_topk)
216
+ topk_proposals = torch.stack(topk_proposals)
217
+ else:
218
+ topk_proposals = torch.topk(proposal_logit, topk, dim=1)[1]
219
+
220
+ topk_coords_unact = torch.gather(enc_outputs_coord_unact, 1, topk_proposals.unsqueeze(-1).repeat(1, 1, 4))
221
+ topk_coords_unact = topk_coords_unact.detach()
222
+ reference_points = topk_coords_unact.sigmoid()
223
+ init_reference_out = reference_points
224
+ pos_trans_out = self.pos_trans_norm(self.pos_trans(self.get_proposal_pos_embed(topk_coords_unact)))
225
+ query_embed, tgt = torch.split(pos_trans_out, c, dim=2)
226
+
227
+ topk_feats = torch.stack([output_memory[b][topk_proposals[b]] for b in range(bs)]).detach()
228
+ tgt = tgt + self.pix_trans_norm(self.pix_trans(topk_feats))
229
+ else:
230
+ query_embed, tgt = torch.split(query_embed, c, dim=1)
231
+ query_embed = query_embed.unsqueeze(0).expand(bs, -1, -1)
232
+ tgt = tgt.unsqueeze(0).expand(bs, -1, -1)
233
+ reference_points = self.reference_points(query_embed).sigmoid()
234
+ init_reference_out = reference_points
235
+
236
+ # decoder
237
+ hs, inter_references = self.decoder(tgt, reference_points, memory,
238
+ spatial_shapes, level_start_index, valid_ratios, query_embed, mask_flatten)
239
+
240
+ inter_references_out = inter_references
241
+ if self.two_stage:
242
+ return hs, init_reference_out, inter_references_out, enc_outputs_class, enc_outputs_coord_unact, output_proposals.sigmoid()
243
+ return hs, init_reference_out, inter_references_out, None, None, None
244
+
245
+
246
+ class DeformableTransformerEncoderLayer(nn.Module):
247
+ def __init__(self,
248
+ d_model=256, d_ffn=1024,
249
+ dropout=0.1, activation="relu",
250
+ n_levels=4, n_heads=8, n_points=4):
251
+ super().__init__()
252
+
253
+ # self attention
254
+ self.self_attn = MSDeformAttn(d_model, n_levels, n_heads, n_points, batch_first=True)
255
+ self.dropout1 = nn.Dropout(dropout)
256
+ self.norm1 = nn.LayerNorm(d_model)
257
+
258
+ # ffn
259
+ self.linear1 = nn.Linear(d_model, d_ffn)
260
+ self.activation = _get_activation_fn(activation)
261
+ self.dropout2 = nn.Dropout(dropout)
262
+ self.linear2 = nn.Linear(d_ffn, d_model)
263
+ self.dropout3 = nn.Dropout(dropout)
264
+ self.norm2 = nn.LayerNorm(d_model)
265
+
266
+ @staticmethod
267
+ def with_pos_embed(tensor, pos):
268
+ return tensor if pos is None else tensor + pos
269
+
270
+ def forward_ffn(self, src):
271
+ src2 = self.linear2(self.dropout2(self.activation(self.linear1(src))))
272
+ src = src + self.dropout3(src2)
273
+ src = self.norm2(src)
274
+ return src
275
+
276
+ def forward(self, src, pos, reference_points, spatial_shapes, level_start_index, padding_mask=None):
277
+ # self attention
278
+ src2 = self.self_attn(
279
+ query=self.with_pos_embed(src, pos),
280
+ reference_points=reference_points,
281
+ value=src,
282
+ spatial_shapes=spatial_shapes,
283
+ level_start_index=level_start_index,
284
+ key_padding_mask=padding_mask,
285
+ )
286
+ src = src + self.dropout1(src2)
287
+ src = self.norm1(src)
288
+
289
+ # ffn
290
+ src = self.forward_ffn(src)
291
+
292
+ return src
293
+
294
+
295
+ class DeformableTransformerEncoder(nn.Module):
296
+ def __init__(self, encoder_layer, num_layers):
297
+ super().__init__()
298
+ self.layers = _get_clones(encoder_layer, num_layers)
299
+ self.num_layers = num_layers
300
+
301
+ @staticmethod
302
+ def get_reference_points(spatial_shapes, valid_ratios, device):
303
+ reference_points_list = []
304
+ for lvl, (H_, W_) in enumerate(spatial_shapes):
305
+
306
+ ref_y, ref_x = torch.meshgrid(torch.linspace(0.5, H_ - 0.5, H_, dtype=torch.float32, device=device),
307
+ torch.linspace(0.5, W_ - 0.5, W_, dtype=torch.float32, device=device))
308
+ ref_y = ref_y.reshape(-1)[None] / (valid_ratios[:, None, lvl, 1] * H_)
309
+ ref_x = ref_x.reshape(-1)[None] / (valid_ratios[:, None, lvl, 0] * W_)
310
+ ref = torch.stack((ref_x, ref_y), -1)
311
+ reference_points_list.append(ref)
312
+ reference_points = torch.cat(reference_points_list, 1)
313
+ reference_points = reference_points[:, :, None] * valid_ratios[:, None]
314
+ return reference_points
315
+
316
+ def forward(self, src, spatial_shapes, level_start_index, valid_ratios, pos=None, padding_mask=None):
317
+ output = src
318
+ reference_points = self.get_reference_points(spatial_shapes, valid_ratios, device=src.device)
319
+ for _, layer in enumerate(self.layers):
320
+ output = layer(output, pos, reference_points, spatial_shapes, level_start_index, padding_mask)
321
+
322
+ return output
323
+
324
+
325
+ class DeformableTransformerDecoderLayer(nn.Module):
326
+ def __init__(self, d_model=256, d_ffn=1024,
327
+ dropout=0.1, activation="relu",
328
+ n_levels=4, n_heads=8, n_points=4):
329
+ super().__init__()
330
+
331
+ # cross attention
332
+ self.cross_attn = MSDeformAttn(d_model, n_levels, n_heads, n_points, batch_first=True)
333
+ self.dropout1 = nn.Dropout(dropout)
334
+ self.norm1 = nn.LayerNorm(d_model)
335
+
336
+ # self attention
337
+ self.self_attn = nn.MultiheadAttention(d_model, n_heads, dropout=dropout)
338
+ self.dropout2 = nn.Dropout(dropout)
339
+ self.norm2 = nn.LayerNorm(d_model)
340
+
341
+ # ffn
342
+ self.linear1 = nn.Linear(d_model, d_ffn)
343
+ self.activation = _get_activation_fn(activation)
344
+ self.dropout3 = nn.Dropout(dropout)
345
+ self.linear2 = nn.Linear(d_ffn, d_model)
346
+ self.dropout4 = nn.Dropout(dropout)
347
+ self.norm3 = nn.LayerNorm(d_model)
348
+
349
+ @staticmethod
350
+ def with_pos_embed(tensor, pos):
351
+ return tensor if pos is None else tensor + pos
352
+
353
+ def forward_ffn(self, tgt):
354
+ tgt2 = self.linear2(self.dropout3(self.activation(self.linear1(tgt))))
355
+ tgt = tgt + self.dropout4(tgt2)
356
+ tgt = self.norm3(tgt)
357
+ return tgt
358
+
359
+ def forward(self, tgt, query_pos, reference_points, src, src_spatial_shapes, level_start_index,
360
+ src_padding_mask=None, tgt_mask=None):
361
+ # self attention
362
+ q = k = self.with_pos_embed(tgt, query_pos)
363
+ tgt2 = self.self_attn(q.transpose(0, 1), k.transpose(0, 1), tgt.transpose(0, 1), attn_mask=tgt_mask)[0].transpose(0, 1)
364
+ tgt = tgt + self.dropout2(tgt2)
365
+ tgt = self.norm2(tgt)
366
+
367
+ # cross attention
368
+ tgt2 = self.cross_attn(self.with_pos_embed(tgt, query_pos),
369
+ reference_points=reference_points,
370
+ value=src,
371
+ spatial_shapes=src_spatial_shapes,
372
+ level_start_index=level_start_index,
373
+ key_padding_mask=src_padding_mask)
374
+ tgt = tgt + self.dropout1(tgt2)
375
+ tgt = self.norm1(tgt)
376
+
377
+ # ffn
378
+ tgt = self.forward_ffn(tgt)
379
+
380
+ return tgt
381
+
382
+
383
+ class DeformableTransformerDecoder(nn.Module):
384
+ def __init__(self, decoder_layer, num_layers, return_intermediate=False):
385
+ super().__init__()
386
+ self.layers = _get_clones(decoder_layer, num_layers)
387
+ self.num_layers = num_layers
388
+ self.return_intermediate = return_intermediate
389
+ # hack implementation for iterative bounding box refinement and two-stage Deformable DETR
390
+ self.bbox_embed = None
391
+ self.class_embed = None
392
+
393
+ def forward(self, tgt, reference_points, src, src_spatial_shapes, src_level_start_index, src_valid_ratios,
394
+ query_pos=None, src_padding_mask=None, tgt_mask=None):
395
+ output = tgt
396
+
397
+ intermediate = []
398
+ intermediate_reference_points = []
399
+ for lid, layer in enumerate(self.layers):
400
+ if reference_points.shape[-1] == 4:
401
+ reference_points_input = reference_points[:, :, None] \
402
+ * torch.cat([src_valid_ratios, src_valid_ratios], -1)[:, None]
403
+ else:
404
+ assert reference_points.shape[-1] == 2
405
+ reference_points_input = reference_points[:, :, None] * src_valid_ratios[:, None]
406
+ output = layer(output, query_pos, reference_points_input, src, src_spatial_shapes, src_level_start_index, src_padding_mask, tgt_mask=tgt_mask)
407
+
408
+ # hack implementation for iterative bounding box refinement
409
+ if self.bbox_embed is not None:
410
+ tmp = self.bbox_embed[lid](output)
411
+ if reference_points.shape[-1] == 4:
412
+ new_reference_points = tmp + inverse_sigmoid(reference_points)
413
+ new_reference_points = new_reference_points.sigmoid()
414
+ else:
415
+ assert reference_points.shape[-1] == 2
416
+ new_reference_points = tmp
417
+ new_reference_points[..., :2] = tmp[..., :2] + inverse_sigmoid(reference_points)
418
+ new_reference_points = new_reference_points.sigmoid()
419
+ reference_points = new_reference_points.detach()
420
+
421
+ if self.return_intermediate:
422
+ intermediate.append(output)
423
+ intermediate_reference_points.append(reference_points)
424
+
425
+ if self.return_intermediate:
426
+ return torch.stack(intermediate), torch.stack(intermediate_reference_points)
427
+
428
+ return output, reference_points
429
+
430
+
431
+ def _get_clones(module, N):
432
+ return nn.ModuleList([copy.deepcopy(module) for i in range(N)])
433
+
434
+
435
+ def _get_activation_fn(activation):
436
+ """Return an activation function given a string"""
437
+ if activation == "relu":
438
+ return F.relu
439
+ if activation == "gelu":
440
+ return F.gelu
441
+ if activation == "glu":
442
+ return F.glu
443
+ raise RuntimeError(F"activation should be relu/gelu, not {activation}.")
444
+
445
+
446
+ def build_deforamble_transformer(args):
447
+ return DeformableTransformer(
448
+ d_model=args.hidden_dim,
449
+ nhead=args.nheads,
450
+ num_encoder_layers=args.enc_layers,
451
+ num_decoder_layers=args.dec_layers,
452
+ dim_feedforward=args.dim_feedforward,
453
+ dropout=args.dropout,
454
+ activation="relu",
455
+ return_intermediate_dec=True,
456
+ num_feature_levels=args.num_feature_levels,
457
+ dec_n_points=args.dec_n_points,
458
+ enc_n_points=args.enc_n_points,
459
+ two_stage=args.two_stage,
460
+ two_stage_num_proposals=args.num_queries,
461
+ assign_first_stage=args.assign_first_stage,
462
+ )
models/deformable_detr/matcher.py ADDED
@@ -0,0 +1,101 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ # ------------------------------------------------------------------------
2
+ # Deformable DETR
3
+ # Copyright (c) 2020 SenseTime. All Rights Reserved.
4
+ # Licensed under the Apache License, Version 2.0 [see LICENSE for details]
5
+ # ------------------------------------------------------------------------
6
+ # Modified from DETR (https://github.com/facebookresearch/detr)
7
+ # Copyright (c) Facebook, Inc. and its affiliates. All Rights Reserved
8
+ # ------------------------------------------------------------------------
9
+
10
+ """
11
+ Modules to compute the matching cost and solve the corresponding LSAP.
12
+ """
13
+ import torch
14
+ from scipy.optimize import linear_sum_assignment
15
+ from torch import nn
16
+
17
+ from util.box_ops import box_cxcywh_to_xyxy, generalized_box_iou
18
+
19
+
20
+ class HungarianMatcher(nn.Module):
21
+ """This class computes an assignment between the targets and the predictions of the network
22
+
23
+ For efficiency reasons, the targets don't include the no_object. Because of this, in general,
24
+ there are more predictions than targets. In this case, we do a 1-to-1 matching of the best predictions,
25
+ while the others are un-matched (and thus treated as non-objects).
26
+ """
27
+
28
+ def __init__(self,
29
+ cost_class: float = 1,
30
+ cost_bbox: float = 1,
31
+ cost_giou: float = 1):
32
+ """Creates the matcher
33
+
34
+ Params:
35
+ cost_class: This is the relative weight of the classification error in the matching cost
36
+ cost_bbox: This is the relative weight of the L1 error of the bounding box coordinates in the matching cost
37
+ cost_giou: This is the relative weight of the giou loss of the bounding box in the matching cost
38
+ """
39
+ super().__init__()
40
+ self.cost_class = cost_class
41
+ self.cost_bbox = cost_bbox
42
+ self.cost_giou = cost_giou
43
+ assert cost_class != 0 or cost_bbox != 0 or cost_giou != 0, "all costs cant be 0"
44
+
45
+ def forward(self, outputs, targets):
46
+ """ Performs the matching
47
+
48
+ Params:
49
+ outputs: This is a dict that contains at least these entries:
50
+ "pred_logits": Tensor of dim [batch_size, num_queries, num_classes] with the classification logits
51
+ "pred_boxes": Tensor of dim [batch_size, num_queries, 4] with the predicted box coordinates
52
+
53
+ targets: This is a list of targets (len(targets) = batch_size), where each target is a dict containing:
54
+ "labels": Tensor of dim [num_target_boxes] (where num_target_boxes is the number of ground-truth
55
+ objects in the target) containing the class labels
56
+ "boxes": Tensor of dim [num_target_boxes, 4] containing the target box coordinates
57
+
58
+ Returns:
59
+ A list of size batch_size, containing tuples of (index_i, index_j) where:
60
+ - index_i is the indices of the selected predictions (in order)
61
+ - index_j is the indices of the corresponding selected targets (in order)
62
+ For each batch element, it holds:
63
+ len(index_i) = len(index_j) = min(num_queries, num_target_boxes)
64
+ """
65
+ with torch.no_grad():
66
+ bs, num_queries = outputs["pred_logits"].shape[:2]
67
+
68
+ # We flatten to compute the cost matrices in a batch
69
+ out_prob = outputs["pred_logits"].flatten(0, 1).sigmoid()
70
+ out_bbox = outputs["pred_boxes"].flatten(0, 1) # [batch_size * num_queries, 4]
71
+
72
+ # Also concat the target labels and boxes
73
+ tgt_ids = torch.cat([v["labels"] for v in targets])
74
+ tgt_bbox = torch.cat([v["boxes"] for v in targets])
75
+
76
+ # Compute the classification cost.
77
+ alpha = 0.25
78
+ gamma = 2.0
79
+ neg_cost_class = (1 - alpha) * (out_prob ** gamma) * (-(1 - out_prob + 1e-8).log())
80
+ pos_cost_class = alpha * ((1 - out_prob) ** gamma) * (-(out_prob + 1e-8).log())
81
+ cost_class = pos_cost_class[:, tgt_ids] - neg_cost_class[:, tgt_ids]
82
+
83
+ # Compute the L1 cost between boxes
84
+ cost_bbox = torch.cdist(out_bbox, tgt_bbox, p=1)
85
+
86
+ # Compute the giou cost betwen boxes
87
+ cost_giou = -generalized_box_iou(box_cxcywh_to_xyxy(out_bbox),
88
+ box_cxcywh_to_xyxy(tgt_bbox))
89
+
90
+ # Final cost matrix
91
+ C = self.cost_bbox * cost_bbox + self.cost_class * cost_class + self.cost_giou * cost_giou
92
+ C = C.view(bs, num_queries, -1).cpu()
93
+
94
+ sizes = [len(v["boxes"]) for v in targets]
95
+ indices = [linear_sum_assignment(c[i]) for i, c in enumerate(C.split(sizes, -1))]
96
+ return [(torch.as_tensor(i, dtype=torch.int64), torch.as_tensor(j, dtype=torch.int64)) for i, j in indices]
97
+
98
+
99
+ def build_matcher(args):
100
+ return HungarianMatcher(cost_class=args.set_cost_class, cost_bbox=args.set_cost_bbox,
101
+ cost_giou=args.set_cost_giou)
models/deformable_detr/ms_deform_attn.py ADDED
@@ -0,0 +1,412 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ # ------------------------------------------------------------------------
2
+ # Grounding DINO
3
+ # url: https://github.com/IDEA-Research/GroundingDINO
4
+ # Copyright (c) 2023 IDEA. All Rights Reserved.
5
+ # Licensed under the Apache License, Version 2.0 [see LICENSE for details]
6
+ # ------------------------------------------------------------------------
7
+ # Deformable DETR
8
+ # Copyright (c) 2020 SenseTime. All Rights Reserved.
9
+ # Licensed under the Apache License, Version 2.0 [see LICENSE for details]
10
+ # ------------------------------------------------------------------------------------------------
11
+ # Modified from:
12
+ # https://github.com/fundamentalvision/Deformable-DETR/blob/main/models/ops/functions/ms_deform_attn_func.py
13
+ # https://github.com/fundamentalvision/Deformable-DETR/blob/main/models/ops/modules/ms_deform_attn.py
14
+ # https://github.com/open-mmlab/mmcv/blob/master/mmcv/ops/multi_scale_deform_attn.py
15
+ # ------------------------------------------------------------------------------------------------
16
+
17
+ import math
18
+ import warnings
19
+ from typing import Optional
20
+
21
+ import torch
22
+ import torch.nn as nn
23
+ import torch.nn.functional as F
24
+ from torch.autograd import Function
25
+ from torch.autograd.function import once_differentiable
26
+ from torch.nn.init import constant_, xavier_uniform_
27
+
28
+ try:
29
+ from csrc import _C
30
+ except:
31
+ warnings.warn("Failed to load custom C++ ops. Running on CPU mode Only!")
32
+
33
+
34
+ # helpers
35
+ def _is_power_of_2(n):
36
+ if (not isinstance(n, int)) or (n < 0):
37
+ raise ValueError("invalid input for _is_power_of_2: {} (type: {})".format(n, type(n)))
38
+ return (n & (n - 1) == 0) and n != 0
39
+
40
+
41
+ class MultiScaleDeformableAttnFunction(Function):
42
+ @staticmethod
43
+ def forward(
44
+ ctx,
45
+ value,
46
+ value_spatial_shapes,
47
+ value_level_start_index,
48
+ sampling_locations,
49
+ attention_weights,
50
+ im2col_step,
51
+ ):
52
+ ctx.im2col_step = im2col_step
53
+ output = _C.ms_deform_attn_forward(
54
+ value,
55
+ value_spatial_shapes,
56
+ value_level_start_index,
57
+ sampling_locations,
58
+ attention_weights,
59
+ ctx.im2col_step,
60
+ )
61
+ ctx.save_for_backward(
62
+ value,
63
+ value_spatial_shapes,
64
+ value_level_start_index,
65
+ sampling_locations,
66
+ attention_weights,
67
+ )
68
+ return output
69
+
70
+ @staticmethod
71
+ @once_differentiable
72
+ def backward(ctx, grad_output):
73
+ (
74
+ value,
75
+ value_spatial_shapes,
76
+ value_level_start_index,
77
+ sampling_locations,
78
+ attention_weights,
79
+ ) = ctx.saved_tensors
80
+ grad_value, grad_sampling_loc, grad_attn_weight = _C.ms_deform_attn_backward(
81
+ value,
82
+ value_spatial_shapes,
83
+ value_level_start_index,
84
+ sampling_locations,
85
+ attention_weights,
86
+ grad_output,
87
+ ctx.im2col_step,
88
+ )
89
+
90
+ return grad_value, None, None, grad_sampling_loc, grad_attn_weight, None
91
+
92
+
93
+ def multi_scale_deformable_attn_pytorch(
94
+ value: torch.Tensor,
95
+ value_spatial_shapes: torch.Tensor,
96
+ sampling_locations: torch.Tensor,
97
+ attention_weights: torch.Tensor,
98
+ ) -> torch.Tensor:
99
+
100
+ bs, _, num_heads, embed_dims = value.shape
101
+ _, num_queries, num_heads, num_levels, num_points, _ = sampling_locations.shape
102
+ value_list = value.split([H_ * W_ for H_, W_ in value_spatial_shapes], dim=1)
103
+ sampling_grids = 2 * sampling_locations - 1
104
+ sampling_value_list = []
105
+ for level, (H_, W_) in enumerate(value_spatial_shapes):
106
+ # bs, H_*W_, num_heads, embed_dims ->
107
+ # bs, H_*W_, num_heads*embed_dims ->
108
+ # bs, num_heads*embed_dims, H_*W_ ->
109
+ # bs*num_heads, embed_dims, H_, W_
110
+ value_l_ = (
111
+ value_list[level].flatten(2).transpose(1, 2).reshape(bs * num_heads, embed_dims, H_, W_)
112
+ )
113
+ # bs, num_queries, num_heads, num_points, 2 ->
114
+ # bs, num_heads, num_queries, num_points, 2 ->
115
+ # bs*num_heads, num_queries, num_points, 2
116
+ sampling_grid_l_ = sampling_grids[:, :, :, level].transpose(1, 2).flatten(0, 1)
117
+ # bs*num_heads, embed_dims, num_queries, num_points
118
+ sampling_value_l_ = F.grid_sample(
119
+ value_l_, sampling_grid_l_, mode="bilinear", padding_mode="zeros", align_corners=False
120
+ )
121
+ sampling_value_list.append(sampling_value_l_)
122
+ # (bs, num_queries, num_heads, num_levels, num_points) ->
123
+ # (bs, num_heads, num_queries, num_levels, num_points) ->
124
+ # (bs, num_heads, 1, num_queries, num_levels*num_points)
125
+ attention_weights = attention_weights.transpose(1, 2).reshape(
126
+ bs * num_heads, 1, num_queries, num_levels * num_points
127
+ )
128
+ output = (
129
+ (torch.stack(sampling_value_list, dim=-2).flatten(-2) * attention_weights)
130
+ .sum(-1)
131
+ .view(bs, num_heads * embed_dims, num_queries)
132
+ )
133
+ return output.transpose(1, 2).contiguous()
134
+
135
+
136
+ class MultiScaleDeformableAttention(nn.Module):
137
+ """Multi-Scale Deformable Attention Module used in Deformable-DETR
138
+
139
+ `Deformable DETR: Deformable Transformers for End-to-End Object Detection.
140
+ <https://arxiv.org/pdf/2010.04159.pdf>`_.
141
+
142
+ Args:
143
+ embed_dim (int): The embedding dimension of Attention. Default: 256.
144
+ num_heads (int): The number of attention heads. Default: 8.
145
+ num_levels (int): The number of feature map used in Attention. Default: 4.
146
+ num_points (int): The number of sampling points for each query
147
+ in each head. Default: 4.
148
+ img2col_steps (int): The step used in image_to_column. Defualt: 64.
149
+ dropout (float): Dropout layer used in output. Default: 0.1.
150
+ batch_first (bool): if ``True``, then the input and output tensor will be
151
+ provided as `(bs, n, embed_dim)`. Default: False. `(n, bs, embed_dim)`
152
+ """
153
+
154
+ def __init__(
155
+ self,
156
+ embed_dim: int = 256,
157
+ num_levels: int = 4,
158
+ num_heads: int = 8,
159
+ num_points: int = 4,
160
+ img2col_step: int = 64,
161
+ batch_first: bool = False,
162
+ ):
163
+ super().__init__()
164
+ if embed_dim % num_heads != 0:
165
+ raise ValueError(
166
+ "embed_dim must be divisible by num_heads, but got {} and {}".format(
167
+ embed_dim, num_heads
168
+ )
169
+ )
170
+ head_dim = embed_dim // num_heads
171
+
172
+ self.batch_first = batch_first
173
+
174
+ if not _is_power_of_2(head_dim):
175
+ warnings.warn(
176
+ """
177
+ You'd better set d_model in MSDeformAttn to make sure that
178
+ each dim of the attention head a power of 2, which is more efficient.
179
+ """
180
+ )
181
+
182
+ self.im2col_step = img2col_step
183
+ self.embed_dim = embed_dim
184
+ self.num_heads = num_heads
185
+ self.num_levels = num_levels
186
+ self.num_points = num_points
187
+ self.sampling_offsets = nn.Linear(embed_dim, num_heads * num_levels * num_points * 2)
188
+ self.attention_weights = nn.Linear(embed_dim, num_heads * num_levels * num_points)
189
+ self.value_proj = nn.Linear(embed_dim, embed_dim)
190
+ self.output_proj = nn.Linear(embed_dim, embed_dim)
191
+
192
+ self.init_weights()
193
+
194
+ def _reset_parameters(self):
195
+ return self.init_weights()
196
+
197
+ def init_weights(self):
198
+ """
199
+ Default initialization for Parameters of Module.
200
+ """
201
+ constant_(self.sampling_offsets.weight.data, 0.0)
202
+ thetas = torch.arange(self.num_heads, dtype=torch.float32) * (
203
+ 2.0 * math.pi / self.num_heads
204
+ )
205
+ grid_init = torch.stack([thetas.cos(), thetas.sin()], -1)
206
+ grid_init = (
207
+ (grid_init / grid_init.abs().max(-1, keepdim=True)[0])
208
+ .view(self.num_heads, 1, 1, 2)
209
+ .repeat(1, self.num_levels, self.num_points, 1)
210
+ )
211
+ for i in range(self.num_points):
212
+ grid_init[:, :, i, :] *= i + 1
213
+ with torch.no_grad():
214
+ self.sampling_offsets.bias = nn.Parameter(grid_init.view(-1))
215
+ constant_(self.attention_weights.weight.data, 0.0)
216
+ constant_(self.attention_weights.bias.data, 0.0)
217
+ xavier_uniform_(self.value_proj.weight.data)
218
+ constant_(self.value_proj.bias.data, 0.0)
219
+ xavier_uniform_(self.output_proj.weight.data)
220
+ constant_(self.output_proj.bias.data, 0.0)
221
+
222
+ def freeze_sampling_offsets(self):
223
+ print("Freeze sampling offsets")
224
+ self.sampling_offsets.weight.requires_grad = False
225
+ self.sampling_offsets.bias.requires_grad = False
226
+
227
+ def freeze_attention_weights(self):
228
+ print("Freeze attention weights")
229
+ self.attention_weights.weight.requires_grad = False
230
+ self.attention_weights.bias.requires_grad = False
231
+
232
+ def forward(
233
+ self,
234
+ query: torch.Tensor,
235
+ key: Optional[torch.Tensor] = None,
236
+ value: Optional[torch.Tensor] = None,
237
+ query_pos: Optional[torch.Tensor] = None,
238
+ key_padding_mask: Optional[torch.Tensor] = None,
239
+ reference_points: Optional[torch.Tensor] = None,
240
+ spatial_shapes: Optional[torch.Tensor] = None,
241
+ level_start_index: Optional[torch.Tensor] = None,
242
+ **kwargs
243
+ ) -> torch.Tensor:
244
+
245
+ """Forward Function of MultiScaleDeformableAttention
246
+
247
+ Args:
248
+ query (torch.Tensor): Query embeddings with shape
249
+ `(num_query, bs, embed_dim)`
250
+ key (torch.Tensor): Key embeddings with shape
251
+ `(num_key, bs, embed_dim)`
252
+ value (torch.Tensor): Value embeddings with shape
253
+ `(num_key, bs, embed_dim)`
254
+ query_pos (torch.Tensor): The position embedding for `query`. Default: None.
255
+ key_padding_mask (torch.Tensor): ByteTensor for `query`, with shape `(bs, num_key)`,
256
+ indicating which elements within `key` to be ignored in attention.
257
+ reference_points (torch.Tensor): The normalized reference points
258
+ with shape `(bs, num_query, num_levels, 2)`,
259
+ all elements is range in [0, 1], top-left (0, 0),
260
+ bottom-right (1, 1), including padding are.
261
+ or `(N, Length_{query}, num_levels, 4)`, add additional
262
+ two dimensions `(h, w)` to form reference boxes.
263
+ spatial_shapes (torch.Tensor): Spatial shape of features in different levels.
264
+ With shape `(num_levels, 2)`, last dimension represents `(h, w)`.
265
+ level_start_index (torch.Tensor): The start index of each level. A tensor with
266
+ shape `(num_levels, )` which can be represented as
267
+ `[0, h_0 * w_0, h_0 * w_0 + h_1 * w_1, ...]`.
268
+
269
+ Returns:
270
+ torch.Tensor: forward results with shape `(num_query, bs, embed_dim)`
271
+ """
272
+ if value is None:
273
+ value = query
274
+
275
+ if query_pos is not None:
276
+ query = query + query_pos
277
+
278
+ if not self.batch_first:
279
+ # change to (bs, num_query ,embed_dims)
280
+ query = query.permute(1, 0, 2)
281
+ value = value.permute(1, 0, 2)
282
+
283
+ bs, num_query, _ = query.shape
284
+ bs, num_value, _ = value.shape
285
+
286
+ assert (spatial_shapes[:, 0] * spatial_shapes[:, 1]).sum() == num_value
287
+
288
+ value = self.value_proj(value)
289
+ if key_padding_mask is not None:
290
+ value = value.masked_fill(key_padding_mask[..., None], float(0))
291
+ value = value.view(bs, num_value, self.num_heads, -1)
292
+ sampling_offsets = self.sampling_offsets(query).view(
293
+ bs, num_query, self.num_heads, self.num_levels, self.num_points, 2
294
+ )
295
+ attention_weights = self.attention_weights(query).view(
296
+ bs, num_query, self.num_heads, self.num_levels * self.num_points
297
+ )
298
+ attention_weights = attention_weights.softmax(-1)
299
+ attention_weights = attention_weights.view(
300
+ bs,
301
+ num_query,
302
+ self.num_heads,
303
+ self.num_levels,
304
+ self.num_points,
305
+ )
306
+
307
+ # bs, num_query, num_heads, num_levels, num_points, 2
308
+ if reference_points.shape[-1] == 2:
309
+ offset_normalizer = torch.stack([spatial_shapes[..., 1], spatial_shapes[..., 0]], -1)
310
+ sampling_locations = (
311
+ reference_points[:, :, None, :, None, :]
312
+ + sampling_offsets / offset_normalizer[None, None, None, :, None, :]
313
+ )
314
+ elif reference_points.shape[-1] == 4:
315
+ sampling_locations = (
316
+ reference_points[:, :, None, :, None, :2]
317
+ + sampling_offsets
318
+ / self.num_points
319
+ * reference_points[:, :, None, :, None, 2:]
320
+ * 0.5
321
+ )
322
+ else:
323
+ raise ValueError(
324
+ "Last dim of reference_points must be 2 or 4, but get {} instead.".format(
325
+ reference_points.shape[-1]
326
+ )
327
+ )
328
+
329
+ if torch.cuda.is_available() and value.is_cuda:
330
+ halffloat = False
331
+ if value.dtype == torch.float16:
332
+ halffloat = True
333
+ value = value.float()
334
+ sampling_locations = sampling_locations.float()
335
+ attention_weights = attention_weights.float()
336
+
337
+ output = MultiScaleDeformableAttnFunction.apply(
338
+ value,
339
+ spatial_shapes,
340
+ level_start_index,
341
+ sampling_locations,
342
+ attention_weights,
343
+ self.im2col_step,
344
+ )
345
+
346
+ if halffloat:
347
+ output = output.half()
348
+ else:
349
+ output = multi_scale_deformable_attn_pytorch(
350
+ value, spatial_shapes, sampling_locations, attention_weights
351
+ )
352
+
353
+ output = self.output_proj(output)
354
+
355
+ if not self.batch_first:
356
+ output = output.permute(1, 0, 2)
357
+
358
+ return output
359
+
360
+
361
+ def create_dummy_class(klass, dependency, message=""):
362
+ """
363
+ When a dependency of a class is not available, create a dummy class which throws ImportError
364
+ when used.
365
+
366
+ Args:
367
+ klass (str): name of the class.
368
+ dependency (str): name of the dependency.
369
+ message: extra message to print
370
+ Returns:
371
+ class: a class object
372
+ """
373
+ err = "Cannot import '{}', therefore '{}' is not available.".format(dependency, klass)
374
+ if message:
375
+ err = err + " " + message
376
+
377
+ class _DummyMetaClass(type):
378
+ # throw error on class attribute access
379
+ def __getattr__(_, __): # noqa: B902
380
+ raise ImportError(err)
381
+
382
+ class _Dummy(object, metaclass=_DummyMetaClass):
383
+ # throw error on constructor
384
+ def __init__(self, *args, **kwargs):
385
+ raise ImportError(err)
386
+
387
+ return _Dummy
388
+
389
+
390
+ def create_dummy_func(func, dependency, message=""):
391
+ """
392
+ When a dependency of a function is not available, create a dummy function which throws
393
+ ImportError when used.
394
+
395
+ Args:
396
+ func (str): name of the function.
397
+ dependency (str or list[str]): name(s) of the dependency.
398
+ message: extra message to print
399
+ Returns:
400
+ function: a function object
401
+ """
402
+ err = "Cannot import '{}', therefore '{}' is not available.".format(dependency, func)
403
+ if message:
404
+ err = err + " " + message
405
+
406
+ if isinstance(dependency, (list, tuple)):
407
+ dependency = ",".join(dependency)
408
+
409
+ def _dummy(*args, **kwargs):
410
+ raise ImportError(err)
411
+
412
+ return _dummy
models/deformable_detr/position_encoding.py ADDED
@@ -0,0 +1,100 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ # ------------------------------------------------------------------------
2
+ # Deformable DETR
3
+ # Copyright (c) 2020 SenseTime. All Rights Reserved.
4
+ # Licensed under the Apache License, Version 2.0 [see LICENSE for details]
5
+ # ------------------------------------------------------------------------
6
+ # Modified from DETR (https://github.com/facebookresearch/detr)
7
+ # Copyright (c) Facebook, Inc. and its affiliates. All Rights Reserved
8
+ # ------------------------------------------------------------------------
9
+
10
+ """
11
+ Various positional encodings for the transformer.
12
+ """
13
+ import math
14
+
15
+ import torch
16
+ from torch import nn
17
+
18
+ from util.misc import NestedTensor
19
+
20
+
21
+ class PositionEmbeddingSine(nn.Module):
22
+ """
23
+ This is a more standard version of the position embedding, very similar to the one
24
+ used by the Attention is all you need paper, generalized to work on images.
25
+ """
26
+ def __init__(self, num_pos_feats=64, temperature=10000, normalize=False, scale=None):
27
+ super().__init__()
28
+ self.num_pos_feats = num_pos_feats
29
+ self.temperature = temperature
30
+ self.normalize = normalize
31
+ if scale is not None and normalize is False:
32
+ raise ValueError("normalize should be True if scale is passed")
33
+ if scale is None:
34
+ scale = 2 * math.pi
35
+ self.scale = scale
36
+
37
+ def forward(self, tensor_list: NestedTensor):
38
+ x = tensor_list.tensors
39
+ mask = tensor_list.mask
40
+ assert mask is not None
41
+ not_mask = ~mask
42
+ y_embed = not_mask.cumsum(1, dtype=torch.float32)
43
+ x_embed = not_mask.cumsum(2, dtype=torch.float32)
44
+ if self.normalize:
45
+ eps = 1e-6
46
+ y_embed = (y_embed - 0.5) / (y_embed[:, -1:, :] + eps) * self.scale
47
+ x_embed = (x_embed - 0.5) / (x_embed[:, :, -1:] + eps) * self.scale
48
+
49
+ dim_t = torch.arange(self.num_pos_feats, dtype=torch.float32, device=x.device)
50
+ # dim_t = self.temperature ** (2 * (dim_t // 2) / self.num_pos_feats)
51
+ dim_t = torch.div(dim_t, 2, rounding_mode='floor')
52
+ dim_t = self.temperature ** (2 * dim_t / self.num_pos_feats)
53
+
54
+ pos_x = x_embed[:, :, :, None] / dim_t
55
+ pos_y = y_embed[:, :, :, None] / dim_t
56
+ pos_x = torch.stack((pos_x[:, :, :, 0::2].sin(), pos_x[:, :, :, 1::2].cos()), dim=4).flatten(3)
57
+ pos_y = torch.stack((pos_y[:, :, :, 0::2].sin(), pos_y[:, :, :, 1::2].cos()), dim=4).flatten(3)
58
+ pos = torch.cat((pos_y, pos_x), dim=3).permute(0, 3, 1, 2)
59
+ return pos
60
+
61
+
62
+ class PositionEmbeddingLearned(nn.Module):
63
+ """
64
+ Absolute pos embedding, learned.
65
+ """
66
+ def __init__(self, num_pos_feats=256):
67
+ super().__init__()
68
+ self.row_embed = nn.Embedding(50, num_pos_feats)
69
+ self.col_embed = nn.Embedding(50, num_pos_feats)
70
+ self.reset_parameters()
71
+
72
+ def reset_parameters(self):
73
+ nn.init.uniform_(self.row_embed.weight)
74
+ nn.init.uniform_(self.col_embed.weight)
75
+
76
+ def forward(self, tensor_list: NestedTensor):
77
+ x = tensor_list.tensors
78
+ h, w = x.shape[-2:]
79
+ i = torch.arange(w, device=x.device)
80
+ j = torch.arange(h, device=x.device)
81
+ x_emb = self.col_embed(i)
82
+ y_emb = self.row_embed(j)
83
+ pos = torch.cat([
84
+ x_emb.unsqueeze(0).repeat(h, 1, 1),
85
+ y_emb.unsqueeze(1).repeat(1, w, 1),
86
+ ], dim=-1).permute(2, 0, 1).unsqueeze(0).repeat(x.shape[0], 1, 1, 1)
87
+ return pos
88
+
89
+
90
+ def build_position_encoding(args):
91
+ N_steps = args.hidden_dim // 2
92
+ if args.position_embedding in ('v2', 'sine'):
93
+ # TODO find a better way of exposing other arguments
94
+ position_embedding = PositionEmbeddingSine(N_steps, normalize=True)
95
+ elif args.position_embedding in ('v3', 'learned'):
96
+ position_embedding = PositionEmbeddingLearned(N_steps)
97
+ else:
98
+ raise ValueError(f"not supported {args.position_embedding}")
99
+
100
+ return position_embedding
models/deformable_detr/segmentation.py ADDED
@@ -0,0 +1,369 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ # ------------------------------------------------------------------------
2
+ # Deformable DETR
3
+ # Copyright (c) 2020 SenseTime. All Rights Reserved.
4
+ # Licensed under the Apache License, Version 2.0 [see LICENSE for details]
5
+ # ------------------------------------------------------------------------
6
+ # Modified from DETR (https://github.com/facebookresearch/detr)
7
+ # Copyright (c) Facebook, Inc. and its affiliates. All Rights Reserved
8
+ # ------------------------------------------------------------------------
9
+
10
+ """
11
+ This file provides the definition of the convolutional heads used to predict masks, as well as the losses
12
+ """
13
+ import io
14
+ from collections import defaultdict
15
+
16
+ import torch
17
+ import torch.nn as nn
18
+ import torch.nn.functional as F
19
+ from PIL import Image
20
+
21
+ import util.box_ops as box_ops
22
+ from util.misc import NestedTensor, interpolate, nested_tensor_from_tensor_list
23
+
24
+ try:
25
+ from panopticapi.utils import id2rgb, rgb2id
26
+ except ImportError:
27
+ pass
28
+
29
+
30
+ class DETRsegm(nn.Module):
31
+ def __init__(self, detr, freeze_detr=False):
32
+ super().__init__()
33
+ self.detr = detr
34
+
35
+ if freeze_detr:
36
+ for p in self.parameters():
37
+ p.requires_grad_(False)
38
+
39
+ hidden_dim, nheads = detr.transformer.d_model, detr.transformer.nhead
40
+ self.bbox_attention = MHAttentionMap(hidden_dim, hidden_dim, nheads, dropout=0)
41
+ self.mask_head = MaskHeadSmallConv(hidden_dim + nheads, [1024, 512, 256], hidden_dim)
42
+
43
+ def forward(self, samples: NestedTensor):
44
+ if not isinstance(samples, NestedTensor):
45
+ samples = nested_tensor_from_tensor_list(samples)
46
+ features, pos = self.detr.backbone(samples)
47
+
48
+ bs = features[-1].tensors.shape[0]
49
+
50
+ src, mask = features[-1].decompose()
51
+ src_proj = self.detr.input_proj(src)
52
+ hs, memory = self.detr.transformer(src_proj, mask, self.detr.query_embed.weight, pos[-1])
53
+
54
+ outputs_class = self.detr.class_embed(hs)
55
+ outputs_coord = self.detr.bbox_embed(hs).sigmoid()
56
+ out = {"pred_logits": outputs_class[-1], "pred_boxes": outputs_coord[-1]}
57
+ if self.detr.aux_loss:
58
+ out["aux_outputs"] = [
59
+ {"pred_logits": a, "pred_boxes": b} for a, b in zip(outputs_class[:-1], outputs_coord[:-1])
60
+ ]
61
+
62
+ # FIXME h_boxes takes the last one computed, keep this in mind
63
+ bbox_mask = self.bbox_attention(hs[-1], memory, mask=mask)
64
+
65
+ seg_masks = self.mask_head(src_proj, bbox_mask, [features[2].tensors, features[1].tensors, features[0].tensors])
66
+ outputs_seg_masks = seg_masks.view(bs, self.detr.num_queries, seg_masks.shape[-2], seg_masks.shape[-1])
67
+
68
+ out["pred_masks"] = outputs_seg_masks
69
+ return out
70
+
71
+
72
+ class MaskHeadSmallConv(nn.Module):
73
+ """
74
+ Simple convolutional head, using group norm.
75
+ Upsampling is done using a FPN approach
76
+ """
77
+
78
+ def __init__(self, dim, fpn_dims, context_dim):
79
+ super().__init__()
80
+
81
+ inter_dims = [dim, context_dim // 2, context_dim // 4, context_dim // 8, context_dim // 16, context_dim // 64]
82
+ self.lay1 = torch.nn.Conv2d(dim, dim, 3, padding=1)
83
+ self.gn1 = torch.nn.GroupNorm(8, dim)
84
+ self.lay2 = torch.nn.Conv2d(dim, inter_dims[1], 3, padding=1)
85
+ self.gn2 = torch.nn.GroupNorm(8, inter_dims[1])
86
+ self.lay3 = torch.nn.Conv2d(inter_dims[1], inter_dims[2], 3, padding=1)
87
+ self.gn3 = torch.nn.GroupNorm(8, inter_dims[2])
88
+ self.lay4 = torch.nn.Conv2d(inter_dims[2], inter_dims[3], 3, padding=1)
89
+ self.gn4 = torch.nn.GroupNorm(8, inter_dims[3])
90
+ self.lay5 = torch.nn.Conv2d(inter_dims[3], inter_dims[4], 3, padding=1)
91
+ self.gn5 = torch.nn.GroupNorm(8, inter_dims[4])
92
+ self.out_lay = torch.nn.Conv2d(inter_dims[4], 1, 3, padding=1)
93
+
94
+ self.dim = dim
95
+
96
+ self.adapter1 = torch.nn.Conv2d(fpn_dims[0], inter_dims[1], 1)
97
+ self.adapter2 = torch.nn.Conv2d(fpn_dims[1], inter_dims[2], 1)
98
+ self.adapter3 = torch.nn.Conv2d(fpn_dims[2], inter_dims[3], 1)
99
+
100
+ for m in self.modules():
101
+ if isinstance(m, nn.Conv2d):
102
+ nn.init.kaiming_uniform_(m.weight, a=1)
103
+ nn.init.constant_(m.bias, 0)
104
+
105
+ def forward(self, x, bbox_mask, fpns):
106
+ def expand(tensor, length):
107
+ return tensor.unsqueeze(1).repeat(1, int(length), 1, 1, 1).flatten(0, 1)
108
+
109
+ x = torch.cat([expand(x, bbox_mask.shape[1]), bbox_mask.flatten(0, 1)], 1)
110
+
111
+ x = self.lay1(x)
112
+ x = self.gn1(x)
113
+ x = F.relu(x)
114
+ x = self.lay2(x)
115
+ x = self.gn2(x)
116
+ x = F.relu(x)
117
+
118
+ cur_fpn = self.adapter1(fpns[0])
119
+ if cur_fpn.size(0) != x.size(0):
120
+ cur_fpn = expand(cur_fpn, x.size(0) / cur_fpn.size(0))
121
+ x = cur_fpn + F.interpolate(x, size=cur_fpn.shape[-2:], mode="nearest")
122
+ x = self.lay3(x)
123
+ x = self.gn3(x)
124
+ x = F.relu(x)
125
+
126
+ cur_fpn = self.adapter2(fpns[1])
127
+ if cur_fpn.size(0) != x.size(0):
128
+ cur_fpn = expand(cur_fpn, x.size(0) / cur_fpn.size(0))
129
+ x = cur_fpn + F.interpolate(x, size=cur_fpn.shape[-2:], mode="nearest")
130
+ x = self.lay4(x)
131
+ x = self.gn4(x)
132
+ x = F.relu(x)
133
+
134
+ cur_fpn = self.adapter3(fpns[2])
135
+ if cur_fpn.size(0) != x.size(0):
136
+ cur_fpn = expand(cur_fpn, x.size(0) / cur_fpn.size(0))
137
+ x = cur_fpn + F.interpolate(x, size=cur_fpn.shape[-2:], mode="nearest")
138
+ x = self.lay5(x)
139
+ x = self.gn5(x)
140
+ x = F.relu(x)
141
+
142
+ x = self.out_lay(x)
143
+ return x
144
+
145
+
146
+ class MHAttentionMap(nn.Module):
147
+ """This is a 2D attention module, which only returns the attention softmax (no multiplication by value)"""
148
+
149
+ def __init__(self, query_dim, hidden_dim, num_heads, dropout=0, bias=True):
150
+ super().__init__()
151
+ self.num_heads = num_heads
152
+ self.hidden_dim = hidden_dim
153
+ self.dropout = nn.Dropout(dropout)
154
+
155
+ self.q_linear = nn.Linear(query_dim, hidden_dim, bias=bias)
156
+ self.k_linear = nn.Linear(query_dim, hidden_dim, bias=bias)
157
+
158
+ nn.init.zeros_(self.k_linear.bias)
159
+ nn.init.zeros_(self.q_linear.bias)
160
+ nn.init.xavier_uniform_(self.k_linear.weight)
161
+ nn.init.xavier_uniform_(self.q_linear.weight)
162
+ self.normalize_fact = float(hidden_dim / self.num_heads) ** -0.5
163
+
164
+ def forward(self, q, k, mask=None):
165
+ q = self.q_linear(q)
166
+ k = F.conv2d(k, self.k_linear.weight.unsqueeze(-1).unsqueeze(-1), self.k_linear.bias)
167
+ qh = q.view(q.shape[0], q.shape[1], self.num_heads, self.hidden_dim // self.num_heads)
168
+ kh = k.view(k.shape[0], self.num_heads, self.hidden_dim // self.num_heads, k.shape[-2], k.shape[-1])
169
+ weights = torch.einsum("bqnc,bnchw->bqnhw", qh * self.normalize_fact, kh)
170
+
171
+ if mask is not None:
172
+ weights.masked_fill_(mask.unsqueeze(1).unsqueeze(1), float("-inf"))
173
+ weights = F.softmax(weights.flatten(2), dim=-1).view_as(weights)
174
+ weights = self.dropout(weights)
175
+ return weights
176
+
177
+
178
+ def dice_loss(inputs, targets, num_boxes):
179
+ """
180
+ Compute the DICE loss, similar to generalized IOU for masks
181
+ Args:
182
+ inputs: A float tensor of arbitrary shape.
183
+ The predictions for each example.
184
+ targets: A float tensor with the same shape as inputs. Stores the binary
185
+ classification label for each element in inputs
186
+ (0 for the negative class and 1 for the positive class).
187
+ """
188
+ inputs = inputs.sigmoid()
189
+ inputs = inputs.flatten(1)
190
+ numerator = 2 * (inputs * targets).sum(1)
191
+ denominator = inputs.sum(-1) + targets.sum(-1)
192
+ loss = 1 - (numerator + 1) / (denominator + 1)
193
+ return loss.sum() / num_boxes
194
+
195
+
196
+ def sigmoid_focal_loss(inputs, targets, num_boxes, alpha: float = 0.25, gamma: float = 2):
197
+ """
198
+ Loss used in RetinaNet for dense detection: https://arxiv.org/abs/1708.02002.
199
+ Args:
200
+ inputs: A float tensor of arbitrary shape.
201
+ The predictions for each example.
202
+ targets: A float tensor with the same shape as inputs. Stores the binary
203
+ classification label for each element in inputs
204
+ (0 for the negative class and 1 for the positive class).
205
+ alpha: (optional) Weighting factor in range (0,1) to balance
206
+ positive vs negative examples. Default = -1 (no weighting).
207
+ gamma: Exponent of the modulating factor (1 - p_t) to
208
+ balance easy vs hard examples.
209
+ Returns:
210
+ Loss tensor
211
+ """
212
+ prob = inputs.sigmoid()
213
+ ce_loss = F.binary_cross_entropy_with_logits(inputs, targets, reduction="none")
214
+ p_t = prob * targets + (1 - prob) * (1 - targets)
215
+ loss = ce_loss * ((1 - p_t) ** gamma)
216
+
217
+ if alpha >= 0:
218
+ alpha_t = alpha * targets + (1 - alpha) * (1 - targets)
219
+ loss = alpha_t * loss
220
+
221
+ return loss.mean(1).sum() / num_boxes
222
+
223
+
224
+ class PostProcessSegm(nn.Module):
225
+ def __init__(self, threshold=0.5):
226
+ super().__init__()
227
+ self.threshold = threshold
228
+
229
+ @torch.no_grad()
230
+ def forward(self, results, outputs, orig_target_sizes, max_target_sizes):
231
+ assert len(orig_target_sizes) == len(max_target_sizes)
232
+ max_h, max_w = max_target_sizes.max(0)[0].tolist()
233
+ outputs_masks = outputs["pred_masks"].squeeze(2)
234
+ outputs_masks = F.interpolate(outputs_masks, size=(max_h, max_w), mode="bilinear", align_corners=False)
235
+ outputs_masks = (outputs_masks.sigmoid() > self.threshold).cpu()
236
+
237
+ for i, (cur_mask, t, tt) in enumerate(zip(outputs_masks, max_target_sizes, orig_target_sizes)):
238
+ img_h, img_w = t[0], t[1]
239
+ results[i]["masks"] = cur_mask[:, :img_h, :img_w].unsqueeze(1)
240
+ results[i]["masks"] = F.interpolate(
241
+ results[i]["masks"].float(), size=tuple(tt.tolist()), mode="nearest"
242
+ ).byte()
243
+
244
+ return results
245
+
246
+
247
+ class PostProcessPanoptic(nn.Module):
248
+ """This class converts the output of the model to the final panoptic result, in the format expected by the
249
+ coco panoptic API """
250
+
251
+ def __init__(self, is_thing_map, threshold=0.85):
252
+ """
253
+ Parameters:
254
+ is_thing_map: This is a whose keys are the class ids, and the values a boolean indicating whether
255
+ the class is a thing (True) or a stuff (False) class
256
+ threshold: confidence threshold: segments with confidence lower than this will be deleted
257
+ """
258
+ super().__init__()
259
+ self.threshold = threshold
260
+ self.is_thing_map = is_thing_map
261
+
262
+ def forward(self, outputs, processed_sizes, target_sizes=None):
263
+ """ This function computes the panoptic prediction from the model's predictions.
264
+ Parameters:
265
+ outputs: This is a dict coming directly from the model. See the model doc for the content.
266
+ processed_sizes: This is a list of tuples (or torch tensors) of sizes of the images that were passed to the
267
+ model, ie the size after data augmentation but before batching.
268
+ target_sizes: This is a list of tuples (or torch tensors) corresponding to the requested final size
269
+ of each prediction. If left to None, it will default to the processed_sizes
270
+ """
271
+ if target_sizes is None:
272
+ target_sizes = processed_sizes
273
+ assert len(processed_sizes) == len(target_sizes)
274
+ out_logits, raw_masks, raw_boxes = outputs["pred_logits"], outputs["pred_masks"], outputs["pred_boxes"]
275
+ assert len(out_logits) == len(raw_masks) == len(target_sizes)
276
+ preds = []
277
+
278
+ def to_tuple(tup):
279
+ if isinstance(tup, tuple):
280
+ return tup
281
+ return tuple(tup.cpu().tolist())
282
+
283
+ for cur_logits, cur_masks, cur_boxes, size, target_size in zip(
284
+ out_logits, raw_masks, raw_boxes, processed_sizes, target_sizes
285
+ ):
286
+ # we filter empty queries and detection below threshold
287
+ scores, labels = cur_logits.softmax(-1).max(-1)
288
+ keep = labels.ne(outputs["pred_logits"].shape[-1] - 1) & (scores > self.threshold)
289
+ cur_scores, cur_classes = cur_logits.softmax(-1).max(-1)
290
+ cur_scores = cur_scores[keep]
291
+ cur_classes = cur_classes[keep]
292
+ cur_masks = cur_masks[keep]
293
+ cur_masks = interpolate(cur_masks[None], to_tuple(size), mode="bilinear").squeeze(0)
294
+ cur_boxes = box_ops.box_cxcywh_to_xyxy(cur_boxes[keep])
295
+
296
+ h, w = cur_masks.shape[-2:]
297
+ assert len(cur_boxes) == len(cur_classes)
298
+
299
+ # It may be that we have several predicted masks for the same stuff class.
300
+ # In the following, we track the list of masks ids for each stuff class (they are merged later on)
301
+ cur_masks = cur_masks.flatten(1)
302
+ stuff_equiv_classes = defaultdict(lambda: [])
303
+ for k, label in enumerate(cur_classes):
304
+ if not self.is_thing_map[label.item()]:
305
+ stuff_equiv_classes[label.item()].append(k)
306
+
307
+ def get_ids_area(masks, scores, dedup=False):
308
+ # This helper function creates the final panoptic segmentation image
309
+ # It also returns the area of the masks that appears on the image
310
+
311
+ m_id = masks.transpose(0, 1).softmax(-1)
312
+
313
+ if m_id.shape[-1] == 0:
314
+ # We didn't detect any mask :(
315
+ m_id = torch.zeros((h, w), dtype=torch.long, device=m_id.device)
316
+ else:
317
+ m_id = m_id.argmax(-1).view(h, w)
318
+
319
+ if dedup:
320
+ # Merge the masks corresponding to the same stuff class
321
+ for equiv in stuff_equiv_classes.values():
322
+ if len(equiv) > 1:
323
+ for eq_id in equiv:
324
+ m_id.masked_fill_(m_id.eq(eq_id), equiv[0])
325
+
326
+ final_h, final_w = to_tuple(target_size)
327
+
328
+ seg_img = Image.fromarray(id2rgb(m_id.view(h, w).cpu().numpy()))
329
+ seg_img = seg_img.resize(size=(final_w, final_h), resample=Image.NEAREST)
330
+
331
+ np_seg_img = (
332
+ torch.ByteTensor(torch.ByteStorage.from_buffer(seg_img.tobytes())).view(final_h, final_w, 3).numpy()
333
+ )
334
+ m_id = torch.from_numpy(rgb2id(np_seg_img))
335
+
336
+ area = []
337
+ for i in range(len(scores)):
338
+ area.append(m_id.eq(i).sum().item())
339
+ return area, seg_img
340
+
341
+ area, seg_img = get_ids_area(cur_masks, cur_scores, dedup=True)
342
+ if cur_classes.numel() > 0:
343
+ # We know filter empty masks as long as we find some
344
+ while True:
345
+ filtered_small = torch.as_tensor(
346
+ [area[i] <= 4 for i, c in enumerate(cur_classes)], dtype=torch.bool, device=keep.device
347
+ )
348
+ if filtered_small.any().item():
349
+ cur_scores = cur_scores[~filtered_small]
350
+ cur_classes = cur_classes[~filtered_small]
351
+ cur_masks = cur_masks[~filtered_small]
352
+ area, seg_img = get_ids_area(cur_masks, cur_scores)
353
+ else:
354
+ break
355
+
356
+ else:
357
+ cur_classes = torch.ones(1, dtype=torch.long, device=cur_classes.device)
358
+
359
+ segments_info = []
360
+ for i, a in enumerate(area):
361
+ cat = cur_classes[i].item()
362
+ segments_info.append({"id": i, "isthing": self.is_thing_map[cat], "category_id": cat, "area": a})
363
+ del cur_classes
364
+
365
+ with io.BytesIO() as out:
366
+ seg_img.save(out, format="PNG")
367
+ predictions = {"png_string": out.getvalue(), "segments_info": segments_info}
368
+ preds.append(predictions)
369
+ return preds
models/deformable_detr/swin.py ADDED
@@ -0,0 +1,727 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ # --------------------------------------------------------
2
+ # Swin Transformer
3
+ # Copyright (c) 2021 Microsoft
4
+ # Licensed under The MIT License [see LICENSE for details]
5
+ # Written by Ze Liu, Yutong Lin, Yixuan Wei
6
+ # --------------------------------------------------------
7
+
8
+ # Copyright (c) Facebook, Inc. and its affiliates.
9
+ # Modified by Bowen Cheng from https://github.com/SwinTransformer/Swin-Transformer-Semantic-Segmentation/blob/main/mmseg/models/backbones/swin_transformer.py
10
+ # Modified by Jeffrey Ouyang-Zhang
11
+
12
+ import numpy as np
13
+ import torch
14
+ import torch.nn as nn
15
+ import torch.nn.functional as F
16
+ import torch.utils.checkpoint as checkpoint
17
+ from timm.models.layers import DropPath, to_2tuple, trunc_normal_
18
+
19
+ swin_l_kwargs = {
20
+ 'pretrain_img_size': 384,
21
+ 'embed_dim': 192,
22
+ 'depths': [2, 2, 18, 2],
23
+ 'num_heads': [6, 12, 24, 48],
24
+ 'window_size': 12,
25
+ 'ape': False,
26
+ 'drop_path_rate': 0.3,
27
+ 'patch_norm': True,
28
+
29
+ 'out_indices': (1, 2, 3),
30
+ 'use_checkpoint': True,
31
+ }
32
+ swin_l_weights = 'weights/swin_large_patch4_window12_384_22k.pth'
33
+
34
+ swin_b_kwargs = {
35
+ 'pretrain_img_size': 384,
36
+ 'embed_dim': 128,
37
+ 'depths': [2, 2, 18, 2],
38
+ 'num_heads': [4, 8, 16, 32],
39
+ 'window_size': 12,
40
+ 'ape': False,
41
+ 'drop_path_rate': 0.3,
42
+ 'patch_norm': True,
43
+
44
+ 'out_indices': (1, 2, 3),
45
+ 'use_checkpoint': True,
46
+ }
47
+ swin_b_weights = 'weights/swin_base_patch4_window12_384_22k.pth'
48
+
49
+ def get_swinl(**add_kwargs):
50
+ model = SwinTransformer(**swin_l_kwargs, **add_kwargs)
51
+ state_dict = torch.load(swin_l_weights)
52
+ load_info = model.load_state_dict(state_dict['model'], strict=False)
53
+ print('Missing swin keys', load_info.missing_keys)
54
+ print('Unexpected swin keys', load_info.unexpected_keys)
55
+ return model
56
+
57
+ def get_swinb(**add_kwargs):
58
+ model = SwinTransformer(**swin_b_kwargs, **add_kwargs)
59
+ state_dict = torch.load(swin_b_weights)
60
+ load_info = model.load_state_dict(state_dict['model'], strict=False)
61
+ print('Missing swin keys', load_info.missing_keys)
62
+ print('Unexpected swin keys', load_info.unexpected_keys)
63
+ return model
64
+
65
+ class Mlp(nn.Module):
66
+ """Multilayer perceptron."""
67
+
68
+ def __init__(
69
+ self, in_features, hidden_features=None, out_features=None, act_layer=nn.GELU, drop=0.0
70
+ ):
71
+ super().__init__()
72
+ out_features = out_features or in_features
73
+ hidden_features = hidden_features or in_features
74
+ self.fc1 = nn.Linear(in_features, hidden_features)
75
+ self.act = act_layer()
76
+ self.fc2 = nn.Linear(hidden_features, out_features)
77
+ self.drop = nn.Dropout(drop)
78
+
79
+ def forward(self, x):
80
+ x = self.fc1(x)
81
+ x = self.act(x)
82
+ x = self.drop(x)
83
+ x = self.fc2(x)
84
+ x = self.drop(x)
85
+ return x
86
+
87
+
88
+ def window_partition(x, window_size):
89
+ """
90
+ Args:
91
+ x: (B, H, W, C)
92
+ window_size (int): window size
93
+ Returns:
94
+ windows: (num_windows*B, window_size, window_size, C)
95
+ """
96
+ B, H, W, C = x.shape
97
+ x = x.view(B, H // window_size, window_size, W // window_size, window_size, C)
98
+ windows = x.permute(0, 1, 3, 2, 4, 5).contiguous().view(-1, window_size, window_size, C)
99
+ return windows
100
+
101
+
102
+ def window_reverse(windows, window_size, H, W):
103
+ """
104
+ Args:
105
+ windows: (num_windows*B, window_size, window_size, C)
106
+ window_size (int): Window size
107
+ H (int): Height of image
108
+ W (int): Width of image
109
+ Returns:
110
+ x: (B, H, W, C)
111
+ """
112
+ B = int(windows.shape[0] / (H * W / window_size / window_size))
113
+ x = windows.view(B, H // window_size, W // window_size, window_size, window_size, -1)
114
+ x = x.permute(0, 1, 3, 2, 4, 5).contiguous().view(B, H, W, -1)
115
+ return x
116
+
117
+
118
+ class WindowAttention(nn.Module):
119
+ """Window based multi-head self attention (W-MSA) module with relative position bias.
120
+ It supports both of shifted and non-shifted window.
121
+ Args:
122
+ dim (int): Number of input channels.
123
+ window_size (tuple[int]): The height and width of the window.
124
+ num_heads (int): Number of attention heads.
125
+ qkv_bias (bool, optional): If True, add a learnable bias to query, key, value. Default: True
126
+ qk_scale (float | None, optional): Override default qk scale of head_dim ** -0.5 if set
127
+ attn_drop (float, optional): Dropout ratio of attention weight. Default: 0.0
128
+ proj_drop (float, optional): Dropout ratio of output. Default: 0.0
129
+ """
130
+
131
+ def __init__(
132
+ self,
133
+ dim,
134
+ window_size,
135
+ num_heads,
136
+ qkv_bias=True,
137
+ qk_scale=None,
138
+ attn_drop=0.0,
139
+ proj_drop=0.0,
140
+ ):
141
+
142
+ super().__init__()
143
+ self.dim = dim
144
+ self.window_size = window_size # Wh, Ww
145
+ self.num_heads = num_heads
146
+ head_dim = dim // num_heads
147
+ self.scale = qk_scale or head_dim ** -0.5
148
+
149
+ # define a parameter table of relative position bias
150
+ self.relative_position_bias_table = nn.Parameter(
151
+ torch.zeros((2 * window_size[0] - 1) * (2 * window_size[1] - 1), num_heads)
152
+ ) # 2*Wh-1 * 2*Ww-1, nH
153
+
154
+ # get pair-wise relative position index for each token inside the window
155
+ coords_h = torch.arange(self.window_size[0])
156
+ coords_w = torch.arange(self.window_size[1])
157
+ coords = torch.stack(torch.meshgrid([coords_h, coords_w])) # 2, Wh, Ww
158
+ coords_flatten = torch.flatten(coords, 1) # 2, Wh*Ww
159
+ relative_coords = coords_flatten[:, :, None] - coords_flatten[:, None, :] # 2, Wh*Ww, Wh*Ww
160
+ relative_coords = relative_coords.permute(1, 2, 0).contiguous() # Wh*Ww, Wh*Ww, 2
161
+ relative_coords[:, :, 0] += self.window_size[0] - 1 # shift to start from 0
162
+ relative_coords[:, :, 1] += self.window_size[1] - 1
163
+ relative_coords[:, :, 0] *= 2 * self.window_size[1] - 1
164
+ relative_position_index = relative_coords.sum(-1) # Wh*Ww, Wh*Ww
165
+ self.register_buffer("relative_position_index", relative_position_index)
166
+
167
+ self.qkv = nn.Linear(dim, dim * 3, bias=qkv_bias)
168
+ self.attn_drop = nn.Dropout(attn_drop)
169
+ self.proj = nn.Linear(dim, dim)
170
+ self.proj_drop = nn.Dropout(proj_drop)
171
+
172
+ trunc_normal_(self.relative_position_bias_table, std=0.02)
173
+ self.softmax = nn.Softmax(dim=-1)
174
+
175
+ def forward(self, x, mask=None):
176
+ """Forward function.
177
+ Args:
178
+ x: input features with shape of (num_windows*B, N, C)
179
+ mask: (0/-inf) mask with shape of (num_windows, Wh*Ww, Wh*Ww) or None
180
+ """
181
+ B_, N, C = x.shape
182
+ qkv = (
183
+ self.qkv(x)
184
+ .reshape(B_, N, 3, self.num_heads, C // self.num_heads)
185
+ .permute(2, 0, 3, 1, 4)
186
+ )
187
+ q, k, v = qkv[0], qkv[1], qkv[2] # make torchscript happy (cannot use tensor as tuple)
188
+
189
+ q = q * self.scale
190
+ attn = q @ k.transpose(-2, -1)
191
+
192
+ relative_position_bias = self.relative_position_bias_table[
193
+ self.relative_position_index.view(-1)
194
+ ].view(
195
+ self.window_size[0] * self.window_size[1], self.window_size[0] * self.window_size[1], -1
196
+ ) # Wh*Ww,Wh*Ww,nH
197
+ relative_position_bias = relative_position_bias.permute(
198
+ 2, 0, 1
199
+ ).contiguous() # nH, Wh*Ww, Wh*Ww
200
+ attn = attn + relative_position_bias.unsqueeze(0)
201
+
202
+ if mask is not None:
203
+ nW = mask.shape[0]
204
+ attn = attn.view(B_ // nW, nW, self.num_heads, N, N) + mask.unsqueeze(1).unsqueeze(0)
205
+ attn = attn.view(-1, self.num_heads, N, N)
206
+ attn = self.softmax(attn)
207
+ else:
208
+ attn = self.softmax(attn)
209
+
210
+ attn = self.attn_drop(attn)
211
+
212
+ x = (attn @ v).transpose(1, 2).reshape(B_, N, C)
213
+ x = self.proj(x)
214
+ x = self.proj_drop(x)
215
+ return x
216
+
217
+
218
+ class SwinTransformerBlock(nn.Module):
219
+ """Swin Transformer Block.
220
+ Args:
221
+ dim (int): Number of input channels.
222
+ num_heads (int): Number of attention heads.
223
+ window_size (int): Window size.
224
+ shift_size (int): Shift size for SW-MSA.
225
+ mlp_ratio (float): Ratio of mlp hidden dim to embedding dim.
226
+ qkv_bias (bool, optional): If True, add a learnable bias to query, key, value. Default: True
227
+ qk_scale (float | None, optional): Override default qk scale of head_dim ** -0.5 if set.
228
+ drop (float, optional): Dropout rate. Default: 0.0
229
+ attn_drop (float, optional): Attention dropout rate. Default: 0.0
230
+ drop_path (float, optional): Stochastic depth rate. Default: 0.0
231
+ act_layer (nn.Module, optional): Activation layer. Default: nn.GELU
232
+ norm_layer (nn.Module, optional): Normalization layer. Default: nn.LayerNorm
233
+ """
234
+
235
+ def __init__(
236
+ self,
237
+ dim,
238
+ num_heads,
239
+ window_size=7,
240
+ shift_size=0,
241
+ mlp_ratio=4.0,
242
+ qkv_bias=True,
243
+ qk_scale=None,
244
+ drop=0.0,
245
+ attn_drop=0.0,
246
+ drop_path=0.0,
247
+ act_layer=nn.GELU,
248
+ norm_layer=nn.LayerNorm,
249
+ ):
250
+ super().__init__()
251
+ self.dim = dim
252
+ self.num_heads = num_heads
253
+ self.window_size = window_size
254
+ self.shift_size = shift_size
255
+ self.mlp_ratio = mlp_ratio
256
+ assert 0 <= self.shift_size < self.window_size, "shift_size must in 0-window_size"
257
+
258
+ self.norm1 = norm_layer(dim)
259
+ self.attn = WindowAttention(
260
+ dim,
261
+ window_size=to_2tuple(self.window_size),
262
+ num_heads=num_heads,
263
+ qkv_bias=qkv_bias,
264
+ qk_scale=qk_scale,
265
+ attn_drop=attn_drop,
266
+ proj_drop=drop,
267
+ )
268
+
269
+ self.drop_path = DropPath(drop_path) if drop_path > 0.0 else nn.Identity()
270
+ self.norm2 = norm_layer(dim)
271
+ mlp_hidden_dim = int(dim * mlp_ratio)
272
+ self.mlp = Mlp(
273
+ in_features=dim, hidden_features=mlp_hidden_dim, act_layer=act_layer, drop=drop
274
+ )
275
+
276
+ self.H = None
277
+ self.W = None
278
+
279
+ def forward(self, x, mask_matrix):
280
+ """Forward function.
281
+ Args:
282
+ x: Input feature, tensor size (B, H*W, C).
283
+ H, W: Spatial resolution of the input feature.
284
+ mask_matrix: Attention mask for cyclic shift.
285
+ """
286
+ B, L, C = x.shape
287
+ H, W = self.H, self.W
288
+ assert L == H * W, "input feature has wrong size"
289
+
290
+ shortcut = x
291
+ x = self.norm1(x)
292
+ x = x.view(B, H, W, C)
293
+
294
+ # pad feature maps to multiples of window size
295
+ pad_l = pad_t = 0
296
+ pad_r = (self.window_size - W % self.window_size) % self.window_size
297
+ pad_b = (self.window_size - H % self.window_size) % self.window_size
298
+ x = F.pad(x, (0, 0, pad_l, pad_r, pad_t, pad_b))
299
+ _, Hp, Wp, _ = x.shape
300
+
301
+ # cyclic shift
302
+ if self.shift_size > 0:
303
+ shifted_x = torch.roll(x, shifts=(-self.shift_size, -self.shift_size), dims=(1, 2))
304
+ attn_mask = mask_matrix
305
+ else:
306
+ shifted_x = x
307
+ attn_mask = None
308
+
309
+ # partition windows
310
+ x_windows = window_partition(
311
+ shifted_x, self.window_size
312
+ ) # nW*B, window_size, window_size, C
313
+ x_windows = x_windows.view(
314
+ -1, self.window_size * self.window_size, C
315
+ ) # nW*B, window_size*window_size, C
316
+
317
+ # W-MSA/SW-MSA
318
+ attn_windows = self.attn(x_windows, mask=attn_mask) # nW*B, window_size*window_size, C
319
+
320
+ # merge windows
321
+ attn_windows = attn_windows.view(-1, self.window_size, self.window_size, C)
322
+ shifted_x = window_reverse(attn_windows, self.window_size, Hp, Wp) # B H' W' C
323
+
324
+ # reverse cyclic shift
325
+ if self.shift_size > 0:
326
+ x = torch.roll(shifted_x, shifts=(self.shift_size, self.shift_size), dims=(1, 2))
327
+ else:
328
+ x = shifted_x
329
+
330
+ if pad_r > 0 or pad_b > 0:
331
+ x = x[:, :H, :W, :].contiguous()
332
+
333
+ x = x.view(B, H * W, C)
334
+
335
+ # FFN
336
+ x = shortcut + self.drop_path(x)
337
+ x = x + self.drop_path(self.mlp(self.norm2(x)))
338
+
339
+ return x
340
+
341
+
342
+ class PatchMerging(nn.Module):
343
+ """Patch Merging Layer
344
+ Args:
345
+ dim (int): Number of input channels.
346
+ norm_layer (nn.Module, optional): Normalization layer. Default: nn.LayerNorm
347
+ """
348
+
349
+ def __init__(self, dim, norm_layer=nn.LayerNorm):
350
+ super().__init__()
351
+ self.dim = dim
352
+ self.reduction = nn.Linear(4 * dim, 2 * dim, bias=False)
353
+ self.norm = norm_layer(4 * dim)
354
+
355
+ def forward(self, x, H, W):
356
+ """Forward function.
357
+ Args:
358
+ x: Input feature, tensor size (B, H*W, C).
359
+ H, W: Spatial resolution of the input feature.
360
+ """
361
+ B, L, C = x.shape
362
+ assert L == H * W, "input feature has wrong size"
363
+
364
+ x = x.view(B, H, W, C)
365
+
366
+ # padding
367
+ pad_input = (H % 2 == 1) or (W % 2 == 1)
368
+ if pad_input:
369
+ x = F.pad(x, (0, 0, 0, W % 2, 0, H % 2))
370
+
371
+ x0 = x[:, 0::2, 0::2, :] # B H/2 W/2 C
372
+ x1 = x[:, 1::2, 0::2, :] # B H/2 W/2 C
373
+ x2 = x[:, 0::2, 1::2, :] # B H/2 W/2 C
374
+ x3 = x[:, 1::2, 1::2, :] # B H/2 W/2 C
375
+ x = torch.cat([x0, x1, x2, x3], -1) # B H/2 W/2 4*C
376
+ x = x.view(B, -1, 4 * C) # B H/2*W/2 4*C
377
+
378
+ x = self.norm(x)
379
+ x = self.reduction(x)
380
+
381
+ return x
382
+
383
+
384
+ class BasicLayer(nn.Module):
385
+ """A basic Swin Transformer layer for one stage.
386
+ Args:
387
+ dim (int): Number of feature channels
388
+ depth (int): Depths of this stage.
389
+ num_heads (int): Number of attention head.
390
+ window_size (int): Local window size. Default: 7.
391
+ mlp_ratio (float): Ratio of mlp hidden dim to embedding dim. Default: 4.
392
+ qkv_bias (bool, optional): If True, add a learnable bias to query, key, value. Default: True
393
+ qk_scale (float | None, optional): Override default qk scale of head_dim ** -0.5 if set.
394
+ drop (float, optional): Dropout rate. Default: 0.0
395
+ attn_drop (float, optional): Attention dropout rate. Default: 0.0
396
+ drop_path (float | tuple[float], optional): Stochastic depth rate. Default: 0.0
397
+ norm_layer (nn.Module, optional): Normalization layer. Default: nn.LayerNorm
398
+ downsample (nn.Module | None, optional): Downsample layer at the end of the layer. Default: None
399
+ use_checkpoint (bool): Whether to use checkpointing to save memory. Default: False.
400
+ """
401
+
402
+ def __init__(
403
+ self,
404
+ dim,
405
+ depth,
406
+ num_heads,
407
+ window_size=7,
408
+ mlp_ratio=4.0,
409
+ qkv_bias=True,
410
+ qk_scale=None,
411
+ drop=0.0,
412
+ attn_drop=0.0,
413
+ drop_path=0.0,
414
+ norm_layer=nn.LayerNorm,
415
+ downsample=None,
416
+ use_checkpoint=False,
417
+ ):
418
+ super().__init__()
419
+ self.window_size = window_size
420
+ self.shift_size = window_size // 2
421
+ self.depth = depth
422
+ self.use_checkpoint = use_checkpoint
423
+
424
+ # build blocks
425
+ self.blocks = nn.ModuleList(
426
+ [
427
+ SwinTransformerBlock(
428
+ dim=dim,
429
+ num_heads=num_heads,
430
+ window_size=window_size,
431
+ shift_size=0 if (i % 2 == 0) else window_size // 2,
432
+ mlp_ratio=mlp_ratio,
433
+ qkv_bias=qkv_bias,
434
+ qk_scale=qk_scale,
435
+ drop=drop,
436
+ attn_drop=attn_drop,
437
+ drop_path=drop_path[i] if isinstance(drop_path, list) else drop_path,
438
+ norm_layer=norm_layer,
439
+ )
440
+ for i in range(depth)
441
+ ]
442
+ )
443
+
444
+ # patch merging layer
445
+ if downsample is not None:
446
+ self.downsample = downsample(dim=dim, norm_layer=norm_layer)
447
+ else:
448
+ self.downsample = None
449
+
450
+ def forward(self, x, H, W):
451
+ """Forward function.
452
+ Args:
453
+ x: Input feature, tensor size (B, H*W, C).
454
+ H, W: Spatial resolution of the input feature.
455
+ """
456
+
457
+ # calculate attention mask for SW-MSA
458
+ Hp = int(np.ceil(H / self.window_size)) * self.window_size
459
+ Wp = int(np.ceil(W / self.window_size)) * self.window_size
460
+ img_mask = torch.zeros((1, Hp, Wp, 1), device=x.device) # 1 Hp Wp 1
461
+ h_slices = (
462
+ slice(0, -self.window_size),
463
+ slice(-self.window_size, -self.shift_size),
464
+ slice(-self.shift_size, None),
465
+ )
466
+ w_slices = (
467
+ slice(0, -self.window_size),
468
+ slice(-self.window_size, -self.shift_size),
469
+ slice(-self.shift_size, None),
470
+ )
471
+ cnt = 0
472
+ for h in h_slices:
473
+ for w in w_slices:
474
+ img_mask[:, h, w, :] = cnt
475
+ cnt += 1
476
+
477
+ mask_windows = window_partition(
478
+ img_mask, self.window_size
479
+ ) # nW, window_size, window_size, 1
480
+ mask_windows = mask_windows.view(-1, self.window_size * self.window_size)
481
+ attn_mask = mask_windows.unsqueeze(1) - mask_windows.unsqueeze(2)
482
+ attn_mask = attn_mask.masked_fill(attn_mask != 0, float(-100.0)).masked_fill(
483
+ attn_mask == 0, float(0.0)
484
+ )
485
+
486
+ for blk in self.blocks:
487
+ blk.H, blk.W = H, W
488
+ if self.use_checkpoint:
489
+ x = checkpoint.checkpoint(blk, x, attn_mask)
490
+ else:
491
+ x = blk(x, attn_mask)
492
+ if self.downsample is not None:
493
+ x_down = self.downsample(x, H, W)
494
+ Wh, Ww = (H + 1) // 2, (W + 1) // 2
495
+ return x, H, W, x_down, Wh, Ww
496
+ else:
497
+ return x, H, W, x, H, W
498
+
499
+
500
+ class PatchEmbed(nn.Module):
501
+ """Image to Patch Embedding
502
+ Args:
503
+ patch_size (int): Patch token size. Default: 4.
504
+ in_chans (int): Number of input image channels. Default: 3.
505
+ embed_dim (int): Number of linear projection output channels. Default: 96.
506
+ norm_layer (nn.Module, optional): Normalization layer. Default: None
507
+ """
508
+
509
+ def __init__(self, patch_size=4, in_chans=3, embed_dim=96, norm_layer=None):
510
+ super().__init__()
511
+ patch_size = to_2tuple(patch_size)
512
+ self.patch_size = patch_size
513
+
514
+ self.in_chans = in_chans
515
+ self.embed_dim = embed_dim
516
+
517
+ self.proj = nn.Conv2d(in_chans, embed_dim, kernel_size=patch_size, stride=patch_size)
518
+ if norm_layer is not None:
519
+ self.norm = norm_layer(embed_dim)
520
+ else:
521
+ self.norm = None
522
+
523
+ def forward(self, x):
524
+ """Forward function."""
525
+ # padding
526
+ _, _, H, W = x.size()
527
+ if W % self.patch_size[1] != 0:
528
+ x = F.pad(x, (0, self.patch_size[1] - W % self.patch_size[1]))
529
+ if H % self.patch_size[0] != 0:
530
+ x = F.pad(x, (0, 0, 0, self.patch_size[0] - H % self.patch_size[0]))
531
+
532
+ x = self.proj(x) # B C Wh Ww
533
+ if self.norm is not None:
534
+ Wh, Ww = x.size(2), x.size(3)
535
+ x = x.flatten(2).transpose(1, 2)
536
+ x = self.norm(x)
537
+ x = x.transpose(1, 2).view(-1, self.embed_dim, Wh, Ww)
538
+
539
+ return x
540
+
541
+
542
+ class SwinTransformer(nn.Module):
543
+ """Swin Transformer backbone.
544
+ A PyTorch impl of : `Swin Transformer: Hierarchical Vision Transformer using Shifted Windows` -
545
+ https://arxiv.org/pdf/2103.14030
546
+ Args:
547
+ pretrain_img_size (int): Input image size for training the pretrained model,
548
+ used in absolute postion embedding. Default 224.
549
+ patch_size (int | tuple(int)): Patch size. Default: 4.
550
+ in_chans (int): Number of input image channels. Default: 3.
551
+ embed_dim (int): Number of linear projection output channels. Default: 96.
552
+ depths (tuple[int]): Depths of each Swin Transformer stage.
553
+ num_heads (tuple[int]): Number of attention head of each stage.
554
+ window_size (int): Window size. Default: 7.
555
+ mlp_ratio (float): Ratio of mlp hidden dim to embedding dim. Default: 4.
556
+ qkv_bias (bool): If True, add a learnable bias to query, key, value. Default: True
557
+ qk_scale (float): Override default qk scale of head_dim ** -0.5 if set.
558
+ drop_rate (float): Dropout rate.
559
+ attn_drop_rate (float): Attention dropout rate. Default: 0.
560
+ drop_path_rate (float): Stochastic depth rate. Default: 0.2.
561
+ norm_layer (nn.Module): Normalization layer. Default: nn.LayerNorm.
562
+ ape (bool): If True, add absolute position embedding to the patch embedding. Default: False.
563
+ patch_norm (bool): If True, add normalization after patch embedding. Default: True.
564
+ out_indices (Sequence[int]): Output from which stages.
565
+ frozen_stages (int): Stages to be frozen (stop grad and set eval mode).
566
+ -1 means not freezing any parameters.
567
+ use_checkpoint (bool): Whether to use checkpointing to save memory. Default: False.
568
+ """
569
+
570
+ def __init__(
571
+ self,
572
+ pretrain_img_size=224,
573
+ patch_size=4,
574
+ in_chans=3,
575
+ embed_dim=96,
576
+ depths=[2, 2, 6, 2],
577
+ num_heads=[3, 6, 12, 24],
578
+ window_size=7,
579
+ mlp_ratio=4.0,
580
+ qkv_bias=True,
581
+ qk_scale=None,
582
+ drop_rate=0.0,
583
+ attn_drop_rate=0.0,
584
+ drop_path_rate=0.2,
585
+ norm_layer=nn.LayerNorm,
586
+ ape=False,
587
+ patch_norm=True,
588
+ out_indices=(0, 1, 2, 3),
589
+ frozen_stages=-1,
590
+ use_checkpoint=False,
591
+ ):
592
+ super().__init__()
593
+
594
+ self.pretrain_img_size = pretrain_img_size
595
+ self.num_layers = len(depths)
596
+ self.embed_dim = embed_dim
597
+ self.ape = ape
598
+ self.patch_norm = patch_norm
599
+ self.out_indices = out_indices
600
+ self.frozen_stages = frozen_stages
601
+
602
+ # split image into non-overlapping patches
603
+ self.patch_embed = PatchEmbed(
604
+ patch_size=patch_size,
605
+ in_chans=in_chans,
606
+ embed_dim=embed_dim,
607
+ norm_layer=norm_layer if self.patch_norm else None,
608
+ )
609
+
610
+ # absolute position embedding
611
+ if self.ape:
612
+ pretrain_img_size = to_2tuple(pretrain_img_size)
613
+ patch_size = to_2tuple(patch_size)
614
+ patches_resolution = [
615
+ pretrain_img_size[0] // patch_size[0],
616
+ pretrain_img_size[1] // patch_size[1],
617
+ ]
618
+
619
+ self.absolute_pos_embed = nn.Parameter(
620
+ torch.zeros(1, embed_dim, patches_resolution[0], patches_resolution[1])
621
+ )
622
+ trunc_normal_(self.absolute_pos_embed, std=0.02)
623
+
624
+ self.pos_drop = nn.Dropout(p=drop_rate)
625
+
626
+ # stochastic depth
627
+ dpr = [
628
+ x.item() for x in torch.linspace(0, drop_path_rate, sum(depths))
629
+ ] # stochastic depth decay rule
630
+
631
+ # build layers
632
+ self.layers = nn.ModuleList()
633
+ for i_layer in range(self.num_layers):
634
+ layer = BasicLayer(
635
+ dim=int(embed_dim * 2 ** i_layer),
636
+ depth=depths[i_layer],
637
+ num_heads=num_heads[i_layer],
638
+ window_size=window_size,
639
+ mlp_ratio=mlp_ratio,
640
+ qkv_bias=qkv_bias,
641
+ qk_scale=qk_scale,
642
+ drop=drop_rate,
643
+ attn_drop=attn_drop_rate,
644
+ drop_path=dpr[sum(depths[:i_layer]) : sum(depths[: i_layer + 1])],
645
+ norm_layer=norm_layer,
646
+ downsample=PatchMerging if (i_layer < self.num_layers - 1) else None,
647
+ use_checkpoint=use_checkpoint,
648
+ )
649
+ self.layers.append(layer)
650
+
651
+ num_features = [int(embed_dim * 2 ** i) for i in range(self.num_layers)]
652
+ self.num_features = num_features
653
+
654
+ # add a norm layer for each output
655
+ for i_layer in out_indices:
656
+ layer = norm_layer(num_features[i_layer])
657
+ layer_name = f"norm{i_layer}"
658
+ self.add_module(layer_name, layer)
659
+
660
+ self._freeze_stages()
661
+
662
+ def _freeze_stages(self):
663
+ if self.frozen_stages >= 0:
664
+ self.patch_embed.eval()
665
+ for param in self.patch_embed.parameters():
666
+ param.requires_grad = False
667
+
668
+ if self.frozen_stages >= 1 and self.ape:
669
+ self.absolute_pos_embed.requires_grad = False
670
+
671
+ if self.frozen_stages >= 2:
672
+ self.pos_drop.eval()
673
+ for i in range(0, self.frozen_stages - 1):
674
+ m = self.layers[i]
675
+ m.eval()
676
+ for param in m.parameters():
677
+ param.requires_grad = False
678
+
679
+ def init_weights(self, pretrained=None):
680
+ """Initialize the weights in backbone.
681
+ Args:
682
+ pretrained (str, optional): Path to pre-trained weights.
683
+ Defaults to None.
684
+ """
685
+
686
+ def _init_weights(m):
687
+ if isinstance(m, nn.Linear):
688
+ trunc_normal_(m.weight, std=0.02)
689
+ if isinstance(m, nn.Linear) and m.bias is not None:
690
+ nn.init.constant_(m.bias, 0)
691
+ elif isinstance(m, nn.LayerNorm):
692
+ nn.init.constant_(m.bias, 0)
693
+ nn.init.constant_(m.weight, 1.0)
694
+
695
+ def forward(self, x):
696
+ """Forward function."""
697
+ x = self.patch_embed(x)
698
+
699
+ Wh, Ww = x.size(2), x.size(3)
700
+ if self.ape:
701
+ # interpolate the position embedding to the corresponding size
702
+ absolute_pos_embed = F.interpolate(
703
+ self.absolute_pos_embed, size=(Wh, Ww), mode="bicubic"
704
+ )
705
+ x = (x + absolute_pos_embed).flatten(2).transpose(1, 2) # B Wh*Ww C
706
+ else:
707
+ x = x.flatten(2).transpose(1, 2)
708
+ x = self.pos_drop(x)
709
+
710
+ outs = {}
711
+ for i in range(self.num_layers):
712
+ layer = self.layers[i]
713
+ x_out, H, W, x, Wh, Ww = layer(x, Wh, Ww)
714
+
715
+ if i in self.out_indices:
716
+ norm_layer = getattr(self, f"norm{i}")
717
+ x_out = norm_layer(x_out)
718
+
719
+ out = x_out.view(-1, H, W, self.num_features[i]).permute(0, 3, 1, 2).contiguous()
720
+ outs["res{}".format(i + 2)] = out
721
+
722
+ return outs
723
+
724
+ def train(self, mode=True):
725
+ """Convert the model into training mode while keep layers freezed."""
726
+ super(SwinTransformer, self).train(mode)
727
+ self._freeze_stages()
models/post_process.py ADDED
@@ -0,0 +1,56 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ import torch
2
+ import torch.nn as nn
3
+ from torchvision.ops.boxes import batched_nms
4
+
5
+ from util import box_ops
6
+
7
+
8
+ class CondNMSPostProcess(nn.Module):
9
+ def __init__(self, num_queries):
10
+ super(CondNMSPostProcess, self).__init__()
11
+ self.num_queries = num_queries
12
+
13
+ @torch.no_grad()
14
+ def forward(self, outputs, target_sizes, pred_names, mask_infos):
15
+ out_logits, out_bbox = outputs['pred_logits'], outputs['pred_boxes']
16
+ bs = len(out_logits)
17
+ results = []
18
+
19
+ for b in range(bs):
20
+ b_scores, b_boxes, b_names = [], [], []
21
+ b_start_id, b_end_id = [], []
22
+ name = []
23
+ for name_i in pred_names[b]:
24
+ name.append([name_i] * self.num_queries)
25
+ start_id, end_id = [], []
26
+ for (start, end) in mask_infos[b].keys():
27
+ start_id.append([start] * self.num_queries)
28
+ end_id.append([end] * self.num_queries)
29
+ prob = out_logits[b][0][:, -1:].sigmoid()
30
+ if len(prob) == 0:
31
+ continue
32
+ boxes = box_ops.box_cxcywh_to_xyxy(out_bbox[b][0])
33
+ img_h, img_w = target_sizes[b]
34
+ scale_fct = torch.stack([img_w, img_h, img_w, img_h], dim=0)
35
+ boxes = boxes * scale_fct[None, :]
36
+ num_patch = len(prob) // self.num_queries
37
+ prob = prob.view(num_patch, self.num_queries, -1)
38
+ boxes = boxes.view(num_patch, self.num_queries, -1)
39
+ for t in range(num_patch):
40
+ ind = prob[t].squeeze(1).topk(100).indices
41
+ prob_prenms = prob[t][ind]
42
+ box_prenms = boxes[t][ind]
43
+ lbl_prenms = torch.zeros_like(prob_prenms)
44
+ nms_ind = batched_nms(box_prenms, prob_prenms[:, 0], lbl_prenms[:, 0], 0.7)[:20]
45
+ b_scores.append(prob_prenms[nms_ind])
46
+ b_boxes.append(box_prenms[nms_ind])
47
+
48
+ b_names += [name[t][int(i)] for i in nms_ind]
49
+ b_start_id += [start_id[t][int(i)] for i in nms_ind]
50
+ b_end_id += [end_id[t][int(i)] for i in nms_ind]
51
+ b_scores = torch.cat(b_scores).cpu().squeeze(1)
52
+ b_boxes = torch.cat(b_boxes).cpu()
53
+ out = {'scores': b_scores, 'boxes': b_boxes, 'names': b_names,
54
+ 'start_id': b_start_id, 'end_id': b_end_id}
55
+ results.append(out)
56
+ return results
models/transformer.py ADDED
@@ -0,0 +1,179 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ import torch
2
+ from torchvision.ops.boxes import batched_nms
3
+
4
+ from util.box_ops import box_cxcywh_to_xyxy
5
+
6
+ from .deformable_detr.deformable_transformer import DeformableTransformer
7
+
8
+
9
+ class OVTransformer(DeformableTransformer):
10
+ def __init__(self, d_model=256, nhead=8,
11
+ num_encoder_layers=6, num_decoder_layers=6, dim_feedforward=1024, dropout=0.1,
12
+ activation="relu", return_intermediate_dec=False,
13
+ num_feature_levels=4, dec_n_points=4, enc_n_points=4,
14
+ two_stage=False, two_stage_num_proposals=300,
15
+ assign_first_stage=False):
16
+ super().__init__(d_model, nhead, num_encoder_layers, num_decoder_layers, dim_feedforward, dropout,
17
+ activation, return_intermediate_dec, num_feature_levels, dec_n_points, enc_n_points,
18
+ two_stage, two_stage_num_proposals, assign_first_stage)
19
+
20
+ def forward(self, srcs, masks, pos_embeds, query_embed=None, llm_feat=None, num_patch=1):
21
+ assert self.two_stage or query_embed is not None
22
+
23
+ # prepare input for encoder
24
+ src_flatten = []
25
+ mask_flatten = []
26
+ lvl_pos_embed_flatten = []
27
+ spatial_shapes = []
28
+ for lvl, (src, mask, pos_embed) in enumerate(zip(srcs, masks, pos_embeds)):
29
+ bs, c, h, w = src.shape
30
+ spatial_shape = (h, w)
31
+ spatial_shapes.append(spatial_shape)
32
+ src = src.flatten(2).transpose(1, 2)
33
+ mask = mask.flatten(1)
34
+ pos_embed = pos_embed.flatten(2).transpose(1, 2)
35
+ lvl_pos_embed = pos_embed + self.level_embed[lvl].view(1, 1, -1)
36
+ lvl_pos_embed_flatten.append(lvl_pos_embed)
37
+ src_flatten.append(src)
38
+ mask_flatten.append(mask)
39
+ src_flatten = torch.cat(src_flatten, 1)
40
+ mask_flatten = torch.cat(mask_flatten, 1)
41
+ lvl_pos_embed_flatten = torch.cat(lvl_pos_embed_flatten, 1)
42
+ spatial_shapes = torch.as_tensor(spatial_shapes, dtype=torch.long, device=src_flatten.device)
43
+ level_start_index = torch.cat((spatial_shapes.new_zeros((1, )), spatial_shapes.prod(1).cumsum(0)[:-1]))
44
+ valid_ratios = torch.stack([self.get_valid_ratio(m) for m in masks], 1)
45
+
46
+ # encoder
47
+ memory = self.encoder(src_flatten, spatial_shapes, level_start_index, valid_ratios,
48
+ lvl_pos_embed_flatten, mask_flatten)
49
+
50
+ # prepare input for decoder
51
+ bs, _, c = memory.shape
52
+ if self.two_stage:
53
+ output_memory, output_proposals, level_ids = \
54
+ self.gen_encoder_output_proposals(memory, mask_flatten, spatial_shapes)
55
+
56
+ # hack implementation for two-stage Deformable DETR
57
+ enc_outputs_class = self.decoder.class_embed[self.decoder.num_layers](output_memory)
58
+ enc_outputs_coord_unact = self.decoder.bbox_embed[self.decoder.num_layers](output_memory) + output_proposals
59
+
60
+ topk = self.two_stage_num_proposals
61
+ proposal_logit = enc_outputs_class[..., 0]
62
+
63
+ if self.assign_first_stage:
64
+ proposal_boxes = box_cxcywh_to_xyxy(enc_outputs_coord_unact.sigmoid().float()).clamp(0, 1)
65
+ topk_proposals = []
66
+ for b in range(bs):
67
+ prop_boxes_b = proposal_boxes[b]
68
+ prop_logits_b = proposal_logit[b]
69
+
70
+ # pre-nms per-level topk
71
+ pre_nms_topk = 1000
72
+ pre_nms_inds = []
73
+ for lvl in range(len(spatial_shapes)):
74
+ lvl_mask = level_ids == lvl
75
+ pre_nms_inds.append(torch.topk(prop_logits_b.sigmoid() * lvl_mask, pre_nms_topk)[1])
76
+ pre_nms_inds = torch.cat(pre_nms_inds)
77
+
78
+ # nms on topk indices
79
+ post_nms_inds = batched_nms(prop_boxes_b[pre_nms_inds],
80
+ prop_logits_b[pre_nms_inds],
81
+ level_ids[pre_nms_inds], 0.9)
82
+ keep_inds = pre_nms_inds[post_nms_inds]
83
+
84
+ if len(keep_inds) < self.two_stage_num_proposals:
85
+ print(f'[WARNING] nms proposals ({len(keep_inds)}) < {self.two_stage_num_proposals}')
86
+ keep_inds = torch.topk(proposal_logit[b], topk)[1]
87
+
88
+ # keep top Q/L indices for L levels
89
+ q_per_l = topk // len(spatial_shapes)
90
+ level_shapes = torch.arange(len(spatial_shapes), device=level_ids.device)[:, None]
91
+ is_level_ordered = level_ids[keep_inds][None] == level_shapes
92
+ keep_inds_mask = is_level_ordered & (is_level_ordered.cumsum(1) <= q_per_l) # LS
93
+ keep_inds_mask = keep_inds_mask.any(0) # S
94
+
95
+ # pad to Q indices (might let ones filtered from pre-nms sneak by...
96
+ # unlikely because we pick high conf anyways)
97
+ if keep_inds_mask.sum() < topk:
98
+ num_to_add = topk - keep_inds_mask.sum()
99
+ pad_inds = (~keep_inds_mask).nonzero()[:num_to_add]
100
+ keep_inds_mask[pad_inds] = True
101
+
102
+ # index
103
+ keep_inds_topk = keep_inds[keep_inds_mask]
104
+ topk_proposals.append(keep_inds_topk)
105
+ topk_proposals = torch.stack(topk_proposals)
106
+ else:
107
+ topk_proposals = torch.topk(proposal_logit, topk, dim=1)[1]
108
+
109
+ topk_coords_unact = torch.gather(enc_outputs_coord_unact, 1, topk_proposals.unsqueeze(-1).repeat(1, 1, 4))
110
+ topk_coords_unact = topk_coords_unact.detach()
111
+ reference_points = topk_coords_unact.sigmoid()
112
+ init_reference_out = reference_points
113
+ pos_trans_out = self.pos_trans_norm(self.pos_trans(self.get_proposal_pos_embed(topk_coords_unact)))
114
+ query_embed, tgt = torch.split(pos_trans_out, c, dim=2)
115
+
116
+ num_queries = query_embed.shape[1]
117
+ query_embed = query_embed.repeat(1, num_patch, 1)
118
+ tgt = tgt.repeat(1, num_patch, 1)
119
+ topk_feats = torch.stack([output_memory[b][topk_proposals[b]] for b in range(bs)]).detach()
120
+ topk_feats = topk_feats.repeat(1, num_patch, 1)
121
+ tgt = tgt + self.pix_trans_norm(self.pix_trans(topk_feats))
122
+ reference_points = reference_points.repeat(1, num_patch, 1)
123
+ init_reference_out = init_reference_out.repeat(1, num_patch, 1)
124
+
125
+ llm_feat = llm_feat.repeat_interleave(num_queries, 1)
126
+ tgt = tgt + llm_feat
127
+ else:
128
+ raise NotImplementedError
129
+ query_embed, tgt = torch.split(query_embed, c, dim=1)
130
+ query_embed = query_embed.unsqueeze(0).expand(bs, -1, -1)
131
+ tgt = tgt.unsqueeze(0).expand(bs, -1, -1)
132
+ reference_points = self.reference_points(query_embed).sigmoid()
133
+ init_reference_out = reference_points
134
+ # decoder mask
135
+ decoder_mask = (
136
+ torch.ones(
137
+ num_queries * num_patch,
138
+ num_queries * num_patch,
139
+ device=query_embed.device,
140
+ ) * float("-inf")
141
+ )
142
+ for i in range(num_patch):
143
+ decoder_mask[
144
+ i * num_queries : (i + 1) * num_queries,
145
+ i * num_queries : (i + 1) * num_queries,
146
+ ] = 0
147
+
148
+ # decoder
149
+ hs, inter_references = self.decoder(tgt, reference_points, memory,
150
+ spatial_shapes, level_start_index, valid_ratios,
151
+ query_embed, mask_flatten, tgt_mask=decoder_mask)
152
+
153
+ inter_references_out = inter_references
154
+ if self.two_stage:
155
+ return (hs,
156
+ init_reference_out,
157
+ inter_references_out,
158
+ enc_outputs_class,
159
+ enc_outputs_coord_unact,
160
+ output_proposals.sigmoid())
161
+ return hs, init_reference_out, inter_references_out, None, None, None
162
+
163
+
164
+ def build_ov_transformer(args):
165
+ return OVTransformer(
166
+ d_model=args.hidden_dim,
167
+ nhead=args.nheads,
168
+ num_encoder_layers=args.enc_layers,
169
+ num_decoder_layers=args.dec_layers,
170
+ dim_feedforward=args.dim_feedforward,
171
+ dropout=args.dropout,
172
+ activation="relu",
173
+ return_intermediate_dec=True,
174
+ num_feature_levels=args.num_feature_levels,
175
+ dec_n_points=args.dec_n_points,
176
+ enc_n_points=args.enc_n_points,
177
+ two_stage=args.two_stage,
178
+ two_stage_num_proposals=args.num_queries,
179
+ assign_first_stage=args.assign_first_stage)
requirements.txt ADDED
@@ -0,0 +1,6 @@
 
 
 
 
 
 
 
1
+ Pillow
2
+ timm==0.4.12
3
+ torch
4
+ torchvision
5
+ salesforce-lavis
6
+ transformers
setup.py ADDED
@@ -0,0 +1,164 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ import glob
2
+ import os
3
+ import subprocess
4
+
5
+ import torch
6
+ from setuptools import find_packages, setup
7
+ from torch.utils.cpp_extension import CUDA_HOME, CppExtension, CUDAExtension
8
+
9
+ cwd = os.path.dirname(os.path.abspath(__file__))
10
+
11
+
12
+ sha = "Unknown"
13
+ try:
14
+ sha = subprocess.check_output(["git", "rev-parse", "HEAD"], cwd=cwd).decode("ascii").strip()
15
+ except Exception:
16
+ pass
17
+
18
+
19
+ requirements = ["torch", "torchvision"]
20
+
21
+ torch_ver = [int(x) for x in torch.__version__.split(".")[:2]]
22
+
23
+
24
+ def get_extensions():
25
+ this_dir = os.path.dirname(os.path.abspath(__file__))
26
+ extensions_dir = os.path.join(this_dir, "csrc")
27
+
28
+ main_source = os.path.join(extensions_dir, "vision.cpp")
29
+ sources = glob.glob(os.path.join(extensions_dir, "**", "*.cpp"))
30
+ source_cuda = glob.glob(os.path.join(extensions_dir, "**", "*.cu")) + glob.glob(
31
+ os.path.join(extensions_dir, "*.cu")
32
+ )
33
+
34
+ sources = [main_source] + sources
35
+
36
+ extension = CppExtension
37
+
38
+ extra_compile_args = {"cxx": []}
39
+ define_macros = []
40
+
41
+ if torch.cuda.is_available() and CUDA_HOME is not None:
42
+ print("Compiling with CUDA")
43
+ extension = CUDAExtension
44
+ sources += source_cuda
45
+ define_macros += [("WITH_CUDA", None)]
46
+ extra_compile_args["nvcc"] = [
47
+ "-DCUDA_HAS_FP16=1",
48
+ "-D__CUDA_NO_HALF_OPERATORS__",
49
+ "-D__CUDA_NO_HALF_CONVERSIONS__",
50
+ "-D__CUDA_NO_HALF2_OPERATORS__",
51
+ ]
52
+ else:
53
+ print("Compiling without CUDA")
54
+ define_macros += [("WITH_HIP", None)]
55
+ extra_compile_args["nvcc"] = []
56
+ return None
57
+
58
+ sources = [os.path.join(extensions_dir, s) for s in sources]
59
+ include_dirs = [extensions_dir]
60
+
61
+ ext_modules = [
62
+ extension(
63
+ "csrc._C",
64
+ sources,
65
+ include_dirs=include_dirs,
66
+ define_macros=define_macros,
67
+ extra_compile_args=extra_compile_args,
68
+ )
69
+ ]
70
+
71
+ return ext_modules
72
+
73
+
74
+ def parse_requirements(fname="requirements.txt", with_version=False):
75
+ """Parse the package dependencies listed in a requirements file but strips
76
+ specific versioning information.
77
+
78
+ Args:
79
+ fname (str): path to requirements file
80
+ with_version (bool, default=False): if True include version specs
81
+
82
+ Returns:
83
+ List[str]: list of requirements items
84
+
85
+ CommandLine:
86
+ python -c "import setup; print(setup.parse_requirements())"
87
+ """
88
+ import re
89
+ import sys
90
+ from os.path import exists
91
+
92
+ require_fpath = fname
93
+
94
+ def parse_line(line):
95
+ """Parse information from a line in a requirements text file."""
96
+ if line.startswith("-r "):
97
+ # Allow specifying requirements in other files
98
+ target = line.split(" ")[1]
99
+ for info in parse_require_file(target):
100
+ yield info
101
+ else:
102
+ info = {"line": line}
103
+ if line.startswith("-e "):
104
+ info["package"] = line.split("#egg=")[1]
105
+ elif "@git+" in line:
106
+ info["package"] = line
107
+ else:
108
+ # Remove versioning from the package
109
+ pat = "(" + "|".join([">=", "==", ">"]) + ")"
110
+ parts = re.split(pat, line, maxsplit=1)
111
+ parts = [p.strip() for p in parts]
112
+
113
+ info["package"] = parts[0]
114
+ if len(parts) > 1:
115
+ op, rest = parts[1:]
116
+ if ";" in rest:
117
+ # Handle platform specific dependencies
118
+ # http://setuptools.readthedocs.io/en/latest/setuptools.html#declaring-platform-specific-dependencies
119
+ version, platform_deps = map(str.strip, rest.split(";"))
120
+ info["platform_deps"] = platform_deps
121
+ else:
122
+ version = rest # NOQA
123
+ info["version"] = (op, version)
124
+ yield info
125
+
126
+ def parse_require_file(fpath):
127
+ with open(fpath, "r") as f:
128
+ for line in f.readlines():
129
+ line = line.strip()
130
+ if line and not line.startswith("#"):
131
+ for info in parse_line(line):
132
+ yield info
133
+
134
+ def gen_packages_items():
135
+ if exists(require_fpath):
136
+ for info in parse_require_file(require_fpath):
137
+ parts = [info["package"]]
138
+ if with_version and "version" in info:
139
+ parts.extend(info["version"])
140
+ if not sys.version.startswith("3.4"):
141
+ # apparently package_deps are broken in 3.4
142
+ platform_deps = info.get("platform_deps")
143
+ if platform_deps is not None:
144
+ parts.append(";" + platform_deps)
145
+ item = "".join(parts)
146
+ yield item
147
+
148
+ packages = list(gen_packages_items())
149
+ return packages
150
+
151
+
152
+ if __name__ == "__main__":
153
+ setup(
154
+ name="csrc",
155
+ version="0.0.1",
156
+ author="",
157
+ url="",
158
+ description="",
159
+ license="",
160
+ install_requires=parse_requirements("requirements.txt"),
161
+ packages=find_packages(),
162
+ ext_modules=get_extensions(),
163
+ cmdclass={"build_ext": torch.utils.cpp_extension.BuildExtension},
164
+ )
util/__init__.py ADDED
@@ -0,0 +1,8 @@
 
 
 
 
 
 
 
 
 
1
+ # ------------------------------------------------------------------------
2
+ # Deformable DETR
3
+ # Copyright (c) 2020 SenseTime. All Rights Reserved.
4
+ # Licensed under the Apache License, Version 2.0 [see LICENSE for details]
5
+ # ------------------------------------------------------------------------
6
+ # Modified from DETR (https://github.com/facebookresearch/detr)
7
+ # Copyright (c) Facebook, Inc. and its affiliates. All Rights Reserved
8
+ # ------------------------------------------------------------------------
util/box_ops.py ADDED
@@ -0,0 +1,96 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ # ------------------------------------------------------------------------
2
+ # Deformable DETR
3
+ # Copyright (c) 2020 SenseTime. All Rights Reserved.
4
+ # Licensed under the Apache License, Version 2.0 [see LICENSE for details]
5
+ # ------------------------------------------------------------------------
6
+ # Modified from DETR (https://github.com/facebookresearch/detr)
7
+ # Copyright (c) Facebook, Inc. and its affiliates. All Rights Reserved
8
+ # ------------------------------------------------------------------------
9
+
10
+ """
11
+ Utilities for bounding box manipulation and GIoU.
12
+ """
13
+ import torch
14
+ from torchvision.ops.boxes import box_area
15
+
16
+
17
+ def box_cxcywh_to_xyxy(x):
18
+ x_c, y_c, w, h = x.unbind(-1)
19
+ b = [(x_c - 0.5 * w), (y_c - 0.5 * h),
20
+ (x_c + 0.5 * w), (y_c + 0.5 * h)]
21
+ return torch.stack(b, dim=-1)
22
+
23
+
24
+ def box_xyxy_to_cxcywh(x):
25
+ x0, y0, x1, y1 = x.unbind(-1)
26
+ b = [(x0 + x1) / 2, (y0 + y1) / 2,
27
+ (x1 - x0), (y1 - y0)]
28
+ return torch.stack(b, dim=-1)
29
+
30
+
31
+ # modified from torchvision to also return the union
32
+ def box_iou(boxes1, boxes2):
33
+ area1 = box_area(boxes1)
34
+ area2 = box_area(boxes2)
35
+
36
+ lt = torch.max(boxes1[:, None, :2], boxes2[:, :2]) # [N,M,2]
37
+ rb = torch.min(boxes1[:, None, 2:], boxes2[:, 2:]) # [N,M,2]
38
+
39
+ wh = (rb - lt).clamp(min=0) # [N,M,2]
40
+ inter = wh[:, :, 0] * wh[:, :, 1] # [N,M]
41
+
42
+ union = area1[:, None] + area2 - inter
43
+
44
+ iou = inter / union
45
+ return iou, union
46
+
47
+
48
+ def generalized_box_iou(boxes1, boxes2):
49
+ """
50
+ Generalized IoU from https://giou.stanford.edu/
51
+
52
+ The boxes should be in [x0, y0, x1, y1] format
53
+
54
+ Returns a [N, M] pairwise matrix, where N = len(boxes1)
55
+ and M = len(boxes2)
56
+ """
57
+ # degenerate boxes gives inf / nan results
58
+ # so do an early check
59
+ assert (boxes1[:, 2:] >= boxes1[:, :2]).all()
60
+ assert (boxes2[:, 2:] >= boxes2[:, :2]).all()
61
+ iou, union = box_iou(boxes1, boxes2)
62
+
63
+ lt = torch.min(boxes1[:, None, :2], boxes2[:, :2])
64
+ rb = torch.max(boxes1[:, None, 2:], boxes2[:, 2:])
65
+
66
+ wh = (rb - lt).clamp(min=0) # [N,M,2]
67
+ area = wh[:, :, 0] * wh[:, :, 1]
68
+
69
+ return iou - (area - union) / area
70
+
71
+
72
+ def masks_to_boxes(masks):
73
+ """Compute the bounding boxes around the provided masks
74
+
75
+ The masks should be in format [N, H, W] where N is the number of masks, (H, W) are the spatial dimensions.
76
+
77
+ Returns a [N, 4] tensors, with the boxes in xyxy format
78
+ """
79
+ if masks.numel() == 0:
80
+ return torch.zeros((0, 4), device=masks.device)
81
+
82
+ h, w = masks.shape[-2:]
83
+
84
+ y = torch.arange(0, h, dtype=torch.float)
85
+ x = torch.arange(0, w, dtype=torch.float)
86
+ y, x = torch.meshgrid(y, x)
87
+
88
+ x_mask = (masks * x.unsqueeze(0))
89
+ x_max = x_mask.flatten(1).max(-1)[0]
90
+ x_min = x_mask.masked_fill(~(masks.bool()), 1e8).flatten(1).min(-1)[0]
91
+
92
+ y_mask = (masks * y.unsqueeze(0))
93
+ y_max = y_mask.flatten(1).max(-1)[0]
94
+ y_min = y_mask.masked_fill(~(masks.bool()), 1e8).flatten(1).min(-1)[0]
95
+
96
+ return torch.stack([x_min, y_min, x_max, y_max], 1)
util/misc.py ADDED
@@ -0,0 +1,520 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ # ------------------------------------------------------------------------
2
+ # Deformable DETR
3
+ # Copyright (c) 2020 SenseTime. All Rights Reserved.
4
+ # Licensed under the Apache License, Version 2.0 [see LICENSE for details]
5
+ # ------------------------------------------------------------------------
6
+ # Modified from DETR (https://github.com/facebookresearch/detr)
7
+ # Copyright (c) Facebook, Inc. and its affiliates. All Rights Reserved
8
+ # ------------------------------------------------------------------------
9
+
10
+ """
11
+ Misc functions, including distributed helpers.
12
+
13
+ Mostly copy-paste from torchvision references.
14
+ """
15
+ import os
16
+ import subprocess
17
+ import time
18
+ from collections import defaultdict, deque
19
+ import datetime
20
+ import pickle
21
+ from typing import Optional, List
22
+
23
+ import torch
24
+ import torch.nn as nn
25
+ import torch.distributed as dist
26
+ from torch import Tensor
27
+
28
+ # needed due to empty tensor bug in pytorch and torchvision 0.5
29
+ import torchvision
30
+ if float(torchvision.__version__.split('.')[0]) == 0 and\
31
+ float(torchvision.__version__.split('.')[1]) < 5:
32
+ import math
33
+ from torchvision.ops.misc import _NewEmptyTensorOp
34
+ def _check_size_scale_factor(dim, size, scale_factor):
35
+ # type: (int, Optional[List[int]], Optional[float]) -> None
36
+ if size is None and scale_factor is None:
37
+ raise ValueError("either size or scale_factor should be defined")
38
+ if size is not None and scale_factor is not None:
39
+ raise ValueError("only one of size or scale_factor should be defined")
40
+ if not (scale_factor is not None and len(scale_factor) != dim):
41
+ raise ValueError(
42
+ "scale_factor shape must match input shape. "
43
+ "Input is {}D, scale_factor size is {}".format(dim, len(scale_factor))
44
+ )
45
+ def _output_size(dim, input, size, scale_factor):
46
+ # type: (int, Tensor, Optional[List[int]], Optional[float]) -> List[int]
47
+ assert dim == 2
48
+ _check_size_scale_factor(dim, size, scale_factor)
49
+ if size is not None:
50
+ return size
51
+ # if dim is not 2 or scale_factor is iterable use _ntuple instead of concat
52
+ assert scale_factor is not None and isinstance(scale_factor, (int, float))
53
+ scale_factors = [scale_factor, scale_factor]
54
+ # math.floor might return float in py2.7
55
+ return [
56
+ int(math.floor(input.size(i + 2) * scale_factors[i])) for i in range(dim)
57
+ ]
58
+ elif float(torchvision.__version__.split('.')[0]) == 0 and\
59
+ float(torchvision.__version__.split('.')[1]) < 7:
60
+ from torchvision.ops import _new_empty_tensor
61
+ from torchvision.ops.misc import _output_size
62
+
63
+
64
+ class SmoothedValue(object):
65
+ """Track a series of values and provide access to smoothed values over a
66
+ window or the global series average.
67
+ """
68
+
69
+ def __init__(self, window_size=20, fmt=None):
70
+ if fmt is None:
71
+ fmt = "{median:.4f} ({global_avg:.4f})"
72
+ self.deque = deque(maxlen=window_size)
73
+ self.total = 0.0
74
+ self.count = 0
75
+ self.fmt = fmt
76
+
77
+ def update(self, value, n=1):
78
+ self.deque.append(value)
79
+ self.count += n
80
+ self.total += value * n
81
+
82
+ def synchronize_between_processes(self):
83
+ """
84
+ Warning: does not synchronize the deque!
85
+ """
86
+ if not is_dist_avail_and_initialized():
87
+ return
88
+ t = torch.tensor([self.count, self.total], dtype=torch.float64, device='cuda')
89
+ dist.barrier()
90
+ dist.all_reduce(t)
91
+ t = t.tolist()
92
+ self.count = int(t[0])
93
+ self.total = t[1]
94
+
95
+ @property
96
+ def median(self):
97
+ d = torch.tensor(list(self.deque))
98
+ return d.median().item()
99
+
100
+ @property
101
+ def avg(self):
102
+ d = torch.tensor(list(self.deque), dtype=torch.float32)
103
+ return d.mean().item()
104
+
105
+ @property
106
+ def global_avg(self):
107
+ return self.total / self.count
108
+
109
+ @property
110
+ def max(self):
111
+ return max(self.deque)
112
+
113
+ @property
114
+ def value(self):
115
+ return self.deque[-1]
116
+
117
+ def __str__(self):
118
+ return self.fmt.format(
119
+ median=self.median,
120
+ avg=self.avg,
121
+ global_avg=self.global_avg,
122
+ max=self.max,
123
+ value=self.value)
124
+
125
+
126
+ def all_gather(data):
127
+ """
128
+ Run all_gather on arbitrary picklable data (not necessarily tensors)
129
+ Args:
130
+ data: any picklable object
131
+ Returns:
132
+ list[data]: list of data gathered from each rank
133
+ """
134
+ world_size = get_world_size()
135
+ if world_size == 1:
136
+ return [data]
137
+
138
+ # serialized to a Tensor
139
+ buffer = pickle.dumps(data)
140
+ storage = torch.ByteStorage.from_buffer(buffer)
141
+ tensor = torch.ByteTensor(storage).to("cuda")
142
+
143
+ # obtain Tensor size of each rank
144
+ local_size = torch.tensor([tensor.numel()], device="cuda")
145
+ size_list = [torch.tensor([0], device="cuda") for _ in range(world_size)]
146
+ dist.all_gather(size_list, local_size)
147
+ size_list = [int(size.item()) for size in size_list]
148
+ max_size = max(size_list)
149
+
150
+ # receiving Tensor from all ranks
151
+ # we pad the tensor because torch all_gather does not support
152
+ # gathering tensors of different shapes
153
+ tensor_list = []
154
+ for _ in size_list:
155
+ tensor_list.append(torch.empty((max_size,), dtype=torch.uint8, device="cuda"))
156
+ if local_size != max_size:
157
+ padding = torch.empty(size=(max_size - local_size,), dtype=torch.uint8, device="cuda")
158
+ tensor = torch.cat((tensor, padding), dim=0)
159
+ dist.all_gather(tensor_list, tensor)
160
+
161
+ data_list = []
162
+ for size, tensor in zip(size_list, tensor_list):
163
+ buffer = tensor.cpu().numpy().tobytes()[:size]
164
+ data_list.append(pickle.loads(buffer))
165
+
166
+ return data_list
167
+
168
+
169
+ def reduce_dict(input_dict, average=True):
170
+ """
171
+ Args:
172
+ input_dict (dict): all the values will be reduced
173
+ average (bool): whether to do average or sum
174
+ Reduce the values in the dictionary from all processes so that all processes
175
+ have the averaged results. Returns a dict with the same fields as
176
+ input_dict, after reduction.
177
+ """
178
+ world_size = get_world_size()
179
+ if world_size < 2:
180
+ return input_dict
181
+ with torch.no_grad():
182
+ names = []
183
+ values = []
184
+ # sort the keys so that they are consistent across processes
185
+ for k in sorted(input_dict.keys()):
186
+ names.append(k)
187
+ values.append(input_dict[k])
188
+ values = torch.stack(values, dim=0)
189
+ dist.all_reduce(values)
190
+ if average:
191
+ values /= world_size
192
+ reduced_dict = {k: v for k, v in zip(names, values)}
193
+ return reduced_dict
194
+
195
+
196
+ class MetricLogger(object):
197
+ def __init__(self, delimiter="\t"):
198
+ self.meters = defaultdict(SmoothedValue)
199
+ self.delimiter = delimiter
200
+
201
+ def update(self, **kwargs):
202
+ for k, v in kwargs.items():
203
+ if isinstance(v, torch.Tensor):
204
+ v = v.item()
205
+ assert isinstance(v, (float, int))
206
+ self.meters[k].update(v)
207
+
208
+ def __getattr__(self, attr):
209
+ if attr in self.meters:
210
+ return self.meters[attr]
211
+ if attr in self.__dict__:
212
+ return self.__dict__[attr]
213
+ raise AttributeError("'{}' object has no attribute '{}'".format(
214
+ type(self).__name__, attr))
215
+
216
+ def __str__(self):
217
+ loss_str = []
218
+ for name, meter in self.meters.items():
219
+ loss_str.append(
220
+ "{}: {}".format(name, str(meter))
221
+ )
222
+ return self.delimiter.join(loss_str)
223
+
224
+ def synchronize_between_processes(self):
225
+ for meter in self.meters.values():
226
+ meter.synchronize_between_processes()
227
+
228
+ def add_meter(self, name, meter):
229
+ self.meters[name] = meter
230
+
231
+ def log_every(self, iterable, print_freq, header=None):
232
+ i = 0
233
+ if not header:
234
+ header = ''
235
+ start_time = time.time()
236
+ end = time.time()
237
+ iter_time = SmoothedValue(fmt='{avg:.4f}')
238
+ data_time = SmoothedValue(fmt='{avg:.4f}')
239
+ space_fmt = ':' + str(len(str(len(iterable)))) + 'd'
240
+ if torch.cuda.is_available():
241
+ log_msg = self.delimiter.join([
242
+ header,
243
+ '[{0' + space_fmt + '}/{1}]',
244
+ 'eta: {eta}',
245
+ '{meters}',
246
+ 'time: {time}',
247
+ 'data: {data}',
248
+ 'max mem: {memory:.0f}'
249
+ ])
250
+ else:
251
+ log_msg = self.delimiter.join([
252
+ header,
253
+ '[{0' + space_fmt + '}/{1}]',
254
+ 'eta: {eta}',
255
+ '{meters}',
256
+ 'time: {time}',
257
+ 'data: {data}'
258
+ ])
259
+ MB = 1024.0 * 1024.0
260
+ for obj in iterable:
261
+ data_time.update(time.time() - end)
262
+ yield obj
263
+ iter_time.update(time.time() - end)
264
+ if i % print_freq == 0 or i == len(iterable) - 1:
265
+ eta_seconds = iter_time.global_avg * (len(iterable) - i)
266
+ eta_string = str(datetime.timedelta(seconds=int(eta_seconds)))
267
+ if torch.cuda.is_available():
268
+ print(log_msg.format(
269
+ i, len(iterable), eta=eta_string,
270
+ meters=str(self),
271
+ time=str(iter_time), data=str(data_time),
272
+ memory=torch.cuda.max_memory_allocated() / MB))
273
+ else:
274
+ print(log_msg.format(
275
+ i, len(iterable), eta=eta_string,
276
+ meters=str(self),
277
+ time=str(iter_time), data=str(data_time)))
278
+ i += 1
279
+ end = time.time()
280
+ total_time = time.time() - start_time
281
+ total_time_str = str(datetime.timedelta(seconds=int(total_time)))
282
+ print('{} Total time: {} ({:.4f} s / it)'.format(
283
+ header, total_time_str, total_time / len(iterable)))
284
+
285
+
286
+ def get_sha():
287
+ cwd = os.path.dirname(os.path.abspath(__file__))
288
+
289
+ def _run(command):
290
+ return subprocess.check_output(command, cwd=cwd).decode('ascii').strip()
291
+ sha = 'N/A'
292
+ diff = "clean"
293
+ branch = 'N/A'
294
+ try:
295
+ sha = _run(['git', 'rev-parse', 'HEAD'])
296
+ subprocess.check_output(['git', 'diff'], cwd=cwd)
297
+ diff = _run(['git', 'diff-index', 'HEAD'])
298
+ diff = "has uncommited changes" if diff else "clean"
299
+ branch = _run(['git', 'rev-parse', '--abbrev-ref', 'HEAD'])
300
+ except Exception:
301
+ pass
302
+ message = f"sha: {sha}, status: {diff}, branch: {branch}"
303
+ return message
304
+
305
+
306
+ def collate_fn(batch):
307
+ batch = list(zip(*batch))
308
+ batch[0] = nested_tensor_from_tensor_list(batch[0])
309
+ return tuple(batch)
310
+
311
+
312
+ def _max_by_axis(the_list):
313
+ # type: (List[List[int]]) -> List[int]
314
+ maxes = the_list[0]
315
+ for sublist in the_list[1:]:
316
+ for index, item in enumerate(sublist):
317
+ maxes[index] = max(maxes[index], item)
318
+ return maxes
319
+
320
+
321
+ def nested_tensor_from_tensor_list(tensor_list: List[Tensor]):
322
+ # TODO make this more general
323
+ if tensor_list[0].ndim == 3:
324
+ # TODO make it support different-sized images
325
+ max_size = _max_by_axis([list(img.shape) for img in tensor_list])
326
+ # min_size = tuple(min(s) for s in zip(*[img.shape for img in tensor_list]))
327
+ batch_shape = [len(tensor_list)] + max_size
328
+ b, c, h, w = batch_shape
329
+ dtype = tensor_list[0].dtype
330
+ device = tensor_list[0].device
331
+ tensor = torch.zeros(batch_shape, dtype=dtype, device=device)
332
+ mask = torch.ones((b, h, w), dtype=torch.bool, device=device)
333
+ for img, pad_img, m in zip(tensor_list, tensor, mask):
334
+ pad_img[: img.shape[0], : img.shape[1], : img.shape[2]].copy_(img)
335
+ m[: img.shape[1], :img.shape[2]] = False
336
+ else:
337
+ raise ValueError('not supported')
338
+ return NestedTensor(tensor, mask)
339
+
340
+
341
+ class NestedTensor(object):
342
+ def __init__(self, tensors, mask: Optional[Tensor]):
343
+ self.tensors = tensors
344
+ self.mask = mask
345
+
346
+ def to(self, device, non_blocking=False):
347
+ # type: (Device) -> NestedTensor # noqa
348
+ cast_tensor = self.tensors.to(device, non_blocking=non_blocking)
349
+ mask = self.mask
350
+ if mask is not None:
351
+ assert mask is not None
352
+ cast_mask = mask.to(device, non_blocking=non_blocking)
353
+ else:
354
+ cast_mask = None
355
+ return NestedTensor(cast_tensor, cast_mask)
356
+
357
+ def record_stream(self, *args, **kwargs):
358
+ self.tensors.record_stream(*args, **kwargs)
359
+ if self.mask is not None:
360
+ self.mask.record_stream(*args, **kwargs)
361
+
362
+ def decompose(self):
363
+ return self.tensors, self.mask
364
+
365
+ def __repr__(self):
366
+ return str(self.tensors)
367
+
368
+
369
+ def setup_for_distributed(is_master):
370
+ """
371
+ This function disables printing when not in master process
372
+ """
373
+ import builtins as __builtin__
374
+ builtin_print = __builtin__.print
375
+
376
+ def print(*args, **kwargs):
377
+ force = kwargs.pop('force', False)
378
+ if is_master or force:
379
+ builtin_print(*args, **kwargs)
380
+
381
+ __builtin__.print = print
382
+
383
+
384
+ def is_dist_avail_and_initialized():
385
+ if not dist.is_available():
386
+ return False
387
+ if not dist.is_initialized():
388
+ return False
389
+ return True
390
+
391
+
392
+ def get_world_size():
393
+ if not is_dist_avail_and_initialized():
394
+ return 1
395
+ return dist.get_world_size()
396
+
397
+
398
+ def get_rank():
399
+ if not is_dist_avail_and_initialized():
400
+ return 0
401
+ return dist.get_rank()
402
+
403
+
404
+ def get_local_size():
405
+ if not is_dist_avail_and_initialized():
406
+ return 1
407
+ return int(os.environ['LOCAL_SIZE'])
408
+
409
+
410
+ def get_local_rank():
411
+ if not is_dist_avail_and_initialized():
412
+ return 0
413
+ return int(os.environ['LOCAL_RANK'])
414
+
415
+
416
+ def is_main_process():
417
+ return get_rank() == 0
418
+
419
+
420
+ def save_on_master(*args, **kwargs):
421
+ if is_main_process():
422
+ torch.save(*args, **kwargs)
423
+
424
+
425
+ def init_distributed_mode(args):
426
+ if 'RANK' in os.environ and 'WORLD_SIZE' in os.environ:
427
+ args.rank = int(os.environ["RANK"])
428
+ args.world_size = int(os.environ['WORLD_SIZE'])
429
+ args.gpu = int(os.environ['LOCAL_RANK'])
430
+ args.dist_url = 'env://'
431
+ os.environ['LOCAL_SIZE'] = str(torch.cuda.device_count())
432
+ elif 'SLURM_PROCID' in os.environ:
433
+ proc_id = int(os.environ['SLURM_PROCID'])
434
+ ntasks = int(os.environ['SLURM_NTASKS'])
435
+ node_list = os.environ['SLURM_NODELIST']
436
+ num_gpus = torch.cuda.device_count()
437
+ addr = subprocess.getoutput(
438
+ 'scontrol show hostname {} | head -n1'.format(node_list))
439
+ os.environ['MASTER_PORT'] = os.environ.get('MASTER_PORT', '29500')
440
+ os.environ['MASTER_ADDR'] = addr
441
+ os.environ['WORLD_SIZE'] = str(ntasks)
442
+ os.environ['RANK'] = str(proc_id)
443
+ os.environ['LOCAL_RANK'] = str(proc_id % num_gpus)
444
+ os.environ['LOCAL_SIZE'] = str(num_gpus)
445
+ args.dist_url = 'env://'
446
+ args.world_size = ntasks
447
+ args.rank = proc_id
448
+ args.gpu = proc_id % num_gpus
449
+ else:
450
+ print('Not using distributed mode')
451
+ args.distributed = False
452
+ return
453
+
454
+ args.distributed = True
455
+
456
+ torch.cuda.set_device(args.gpu)
457
+ args.dist_backend = 'nccl'
458
+ print('| distributed init (rank {}): {}'.format(
459
+ args.rank, args.dist_url), flush=True)
460
+ torch.distributed.init_process_group(backend=args.dist_backend, init_method=args.dist_url,
461
+ world_size=args.world_size, rank=args.rank)
462
+ torch.distributed.barrier()
463
+ setup_for_distributed(args.rank == 0)
464
+
465
+
466
+ @torch.no_grad()
467
+ def accuracy(output, target, topk=(1,)):
468
+ """Computes the precision@k for the specified values of k"""
469
+ if target.numel() == 0:
470
+ return [torch.zeros([], device=output.device)]
471
+ maxk = max(topk)
472
+ batch_size = target.size(0)
473
+
474
+ _, pred = output.topk(maxk, 1, True, True)
475
+ pred = pred.t()
476
+ correct = pred.eq(target.view(1, -1).expand_as(pred))
477
+
478
+ res = []
479
+ for k in topk:
480
+ correct_k = correct[:k].view(-1).float().sum(0)
481
+ res.append(correct_k.mul_(100.0 / batch_size))
482
+ return res
483
+
484
+
485
+ def interpolate(input, size=None, scale_factor=None, mode="nearest", align_corners=None):
486
+ # type: (Tensor, Optional[List[int]], Optional[float], str, Optional[bool]) -> Tensor
487
+ """
488
+ Equivalent to nn.functional.interpolate, but with support for empty batch sizes.
489
+ This will eventually be supported natively by PyTorch, and this
490
+ class can go away.
491
+ """
492
+ if float(torchvision.__version__[:3]) < 0.7:
493
+ if input.numel() > 0:
494
+ return torch.nn.functional.interpolate(
495
+ input, size, scale_factor, mode, align_corners
496
+ )
497
+
498
+ output_shape = _output_size(2, input, size, scale_factor)
499
+ output_shape = list(input.shape[:-2]) + list(output_shape)
500
+ if float(torchvision.__version__[:3]) < 0.5:
501
+ return _NewEmptyTensorOp.apply(input, output_shape)
502
+ return _new_empty_tensor(input, output_shape)
503
+ else:
504
+ return torchvision.ops.misc.interpolate(input, size, scale_factor, mode, align_corners)
505
+
506
+
507
+ def get_total_grad_norm(parameters, norm_type=2):
508
+ parameters = list(filter(lambda p: p.grad is not None, parameters))
509
+ norm_type = float(norm_type)
510
+ device = parameters[0].grad.device
511
+ total_norm = torch.norm(torch.stack([torch.norm(p.grad.detach(), norm_type).to(device) for p in parameters]),
512
+ norm_type)
513
+ return total_norm
514
+
515
+ def inverse_sigmoid(x, eps=1e-5):
516
+ x = x.clamp(min=0, max=1)
517
+ x1 = x.clamp(min=eps)
518
+ x2 = (1 - x).clamp(min=eps)
519
+ return torch.log(x1/x2)
520
+