Upload model
Browse files- README.md +199 -0
- config.json +41 -0
- configuration_rf_detr.py +112 -0
- model.safetensors +3 -0
- modeling_rf_detr.py +249 -0
README.md
ADDED
@@ -0,0 +1,199 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
1 |
+
---
|
2 |
+
library_name: transformers
|
3 |
+
tags: []
|
4 |
+
---
|
5 |
+
|
6 |
+
# Model Card for Model ID
|
7 |
+
|
8 |
+
<!-- Provide a quick summary of what the model is/does. -->
|
9 |
+
|
10 |
+
|
11 |
+
|
12 |
+
## Model Details
|
13 |
+
|
14 |
+
### Model Description
|
15 |
+
|
16 |
+
<!-- Provide a longer summary of what this model is. -->
|
17 |
+
|
18 |
+
This is the model card of a 🤗 transformers model that has been pushed on the Hub. This model card has been automatically generated.
|
19 |
+
|
20 |
+
- **Developed by:** [More Information Needed]
|
21 |
+
- **Funded by [optional]:** [More Information Needed]
|
22 |
+
- **Shared by [optional]:** [More Information Needed]
|
23 |
+
- **Model type:** [More Information Needed]
|
24 |
+
- **Language(s) (NLP):** [More Information Needed]
|
25 |
+
- **License:** [More Information Needed]
|
26 |
+
- **Finetuned from model [optional]:** [More Information Needed]
|
27 |
+
|
28 |
+
### Model Sources [optional]
|
29 |
+
|
30 |
+
<!-- Provide the basic links for the model. -->
|
31 |
+
|
32 |
+
- **Repository:** [More Information Needed]
|
33 |
+
- **Paper [optional]:** [More Information Needed]
|
34 |
+
- **Demo [optional]:** [More Information Needed]
|
35 |
+
|
36 |
+
## Uses
|
37 |
+
|
38 |
+
<!-- Address questions around how the model is intended to be used, including the foreseeable users of the model and those affected by the model. -->
|
39 |
+
|
40 |
+
### Direct Use
|
41 |
+
|
42 |
+
<!-- This section is for the model use without fine-tuning or plugging into a larger ecosystem/app. -->
|
43 |
+
|
44 |
+
[More Information Needed]
|
45 |
+
|
46 |
+
### Downstream Use [optional]
|
47 |
+
|
48 |
+
<!-- This section is for the model use when fine-tuned for a task, or when plugged into a larger ecosystem/app -->
|
49 |
+
|
50 |
+
[More Information Needed]
|
51 |
+
|
52 |
+
### Out-of-Scope Use
|
53 |
+
|
54 |
+
<!-- This section addresses misuse, malicious use, and uses that the model will not work well for. -->
|
55 |
+
|
56 |
+
[More Information Needed]
|
57 |
+
|
58 |
+
## Bias, Risks, and Limitations
|
59 |
+
|
60 |
+
<!-- This section is meant to convey both technical and sociotechnical limitations. -->
|
61 |
+
|
62 |
+
[More Information Needed]
|
63 |
+
|
64 |
+
### Recommendations
|
65 |
+
|
66 |
+
<!-- This section is meant to convey recommendations with respect to the bias, risk, and technical limitations. -->
|
67 |
+
|
68 |
+
Users (both direct and downstream) should be made aware of the risks, biases and limitations of the model. More information needed for further recommendations.
|
69 |
+
|
70 |
+
## How to Get Started with the Model
|
71 |
+
|
72 |
+
Use the code below to get started with the model.
|
73 |
+
|
74 |
+
[More Information Needed]
|
75 |
+
|
76 |
+
## Training Details
|
77 |
+
|
78 |
+
### Training Data
|
79 |
+
|
80 |
+
<!-- This should link to a Dataset Card, perhaps with a short stub of information on what the training data is all about as well as documentation related to data pre-processing or additional filtering. -->
|
81 |
+
|
82 |
+
[More Information Needed]
|
83 |
+
|
84 |
+
### Training Procedure
|
85 |
+
|
86 |
+
<!-- This relates heavily to the Technical Specifications. Content here should link to that section when it is relevant to the training procedure. -->
|
87 |
+
|
88 |
+
#### Preprocessing [optional]
|
89 |
+
|
90 |
+
[More Information Needed]
|
91 |
+
|
92 |
+
|
93 |
+
#### Training Hyperparameters
|
94 |
+
|
95 |
+
- **Training regime:** [More Information Needed] <!--fp32, fp16 mixed precision, bf16 mixed precision, bf16 non-mixed precision, fp16 non-mixed precision, fp8 mixed precision -->
|
96 |
+
|
97 |
+
#### Speeds, Sizes, Times [optional]
|
98 |
+
|
99 |
+
<!-- This section provides information about throughput, start/end time, checkpoint size if relevant, etc. -->
|
100 |
+
|
101 |
+
[More Information Needed]
|
102 |
+
|
103 |
+
## Evaluation
|
104 |
+
|
105 |
+
<!-- This section describes the evaluation protocols and provides the results. -->
|
106 |
+
|
107 |
+
### Testing Data, Factors & Metrics
|
108 |
+
|
109 |
+
#### Testing Data
|
110 |
+
|
111 |
+
<!-- This should link to a Dataset Card if possible. -->
|
112 |
+
|
113 |
+
[More Information Needed]
|
114 |
+
|
115 |
+
#### Factors
|
116 |
+
|
117 |
+
<!-- These are the things the evaluation is disaggregating by, e.g., subpopulations or domains. -->
|
118 |
+
|
119 |
+
[More Information Needed]
|
120 |
+
|
121 |
+
#### Metrics
|
122 |
+
|
123 |
+
<!-- These are the evaluation metrics being used, ideally with a description of why. -->
|
124 |
+
|
125 |
+
[More Information Needed]
|
126 |
+
|
127 |
+
### Results
|
128 |
+
|
129 |
+
[More Information Needed]
|
130 |
+
|
131 |
+
#### Summary
|
132 |
+
|
133 |
+
|
134 |
+
|
135 |
+
## Model Examination [optional]
|
136 |
+
|
137 |
+
<!-- Relevant interpretability work for the model goes here -->
|
138 |
+
|
139 |
+
[More Information Needed]
|
140 |
+
|
141 |
+
## Environmental Impact
|
142 |
+
|
143 |
+
<!-- Total emissions (in grams of CO2eq) and additional considerations, such as electricity usage, go here. Edit the suggested text below accordingly -->
|
144 |
+
|
145 |
+
Carbon emissions can be estimated using the [Machine Learning Impact calculator](https://mlco2.github.io/impact#compute) presented in [Lacoste et al. (2019)](https://arxiv.org/abs/1910.09700).
|
146 |
+
|
147 |
+
- **Hardware Type:** [More Information Needed]
|
148 |
+
- **Hours used:** [More Information Needed]
|
149 |
+
- **Cloud Provider:** [More Information Needed]
|
150 |
+
- **Compute Region:** [More Information Needed]
|
151 |
+
- **Carbon Emitted:** [More Information Needed]
|
152 |
+
|
153 |
+
## Technical Specifications [optional]
|
154 |
+
|
155 |
+
### Model Architecture and Objective
|
156 |
+
|
157 |
+
[More Information Needed]
|
158 |
+
|
159 |
+
### Compute Infrastructure
|
160 |
+
|
161 |
+
[More Information Needed]
|
162 |
+
|
163 |
+
#### Hardware
|
164 |
+
|
165 |
+
[More Information Needed]
|
166 |
+
|
167 |
+
#### Software
|
168 |
+
|
169 |
+
[More Information Needed]
|
170 |
+
|
171 |
+
## Citation [optional]
|
172 |
+
|
173 |
+
<!-- If there is a paper or blog post introducing the model, the APA and Bibtex information for that should go in this section. -->
|
174 |
+
|
175 |
+
**BibTeX:**
|
176 |
+
|
177 |
+
[More Information Needed]
|
178 |
+
|
179 |
+
**APA:**
|
180 |
+
|
181 |
+
[More Information Needed]
|
182 |
+
|
183 |
+
## Glossary [optional]
|
184 |
+
|
185 |
+
<!-- If relevant, include terms and calculations in this section that can help readers understand the model or model card. -->
|
186 |
+
|
187 |
+
[More Information Needed]
|
188 |
+
|
189 |
+
## More Information [optional]
|
190 |
+
|
191 |
+
[More Information Needed]
|
192 |
+
|
193 |
+
## Model Card Authors [optional]
|
194 |
+
|
195 |
+
[More Information Needed]
|
196 |
+
|
197 |
+
## Model Card Contact
|
198 |
+
|
199 |
+
[More Information Needed]
|
config.json
ADDED
@@ -0,0 +1,41 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
1 |
+
{
|
2 |
+
"amp": true,
|
3 |
+
"architectures": [
|
4 |
+
"RFDetrModelForObjectDetection"
|
5 |
+
],
|
6 |
+
"auto_map": {
|
7 |
+
"AutoConfig": "configuration_rf_detr.RFDetrConfig",
|
8 |
+
"AutoModelForObjectDetection": "modeling_rf_detr.RFDetrModelForObjectDetection"
|
9 |
+
},
|
10 |
+
"bbox_reparam": true,
|
11 |
+
"ca_nheads": 16,
|
12 |
+
"dec_layers": 3,
|
13 |
+
"dec_n_points": 2,
|
14 |
+
"device": "cpu",
|
15 |
+
"encoder": "dinov2_windowed_small",
|
16 |
+
"gradient_checkpointing": false,
|
17 |
+
"group_detr": 13,
|
18 |
+
"hidden_dim": 256,
|
19 |
+
"layer_norm": true,
|
20 |
+
"lite_refpoint_refine": true,
|
21 |
+
"model_name": "RFDETRBase",
|
22 |
+
"model_type": "rf-detr",
|
23 |
+
"num_classes": 90,
|
24 |
+
"num_queries": 300,
|
25 |
+
"out_feature_indexes": [
|
26 |
+
2,
|
27 |
+
5,
|
28 |
+
8,
|
29 |
+
11
|
30 |
+
],
|
31 |
+
"pretrain_weights": "rf-detr-base.pth",
|
32 |
+
"pretrained": true,
|
33 |
+
"projector_scale": [
|
34 |
+
"P4"
|
35 |
+
],
|
36 |
+
"resolution": 560,
|
37 |
+
"sa_nheads": 8,
|
38 |
+
"torch_dtype": "float32",
|
39 |
+
"transformers_version": "4.50.3",
|
40 |
+
"two_stage": true
|
41 |
+
}
|
configuration_rf_detr.py
ADDED
@@ -0,0 +1,112 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
1 |
+
from typing import Dict, Literal, List, OrderedDict
|
2 |
+
|
3 |
+
import torch
|
4 |
+
from transformers.configuration_utils import PretrainedConfig
|
5 |
+
from optimum.exporters.onnx.model_configs import ViTOnnxConfig
|
6 |
+
from optimum.utils import DummyVisionInputGenerator
|
7 |
+
|
8 |
+
### modified from https://github.com/roboflow/rf-detr/blob/main/rfdetr/config.py
|
9 |
+
|
10 |
+
DEVICE = "cuda" if torch.cuda.is_available() else "mps" if torch.backends.mps.is_available() else "cpu"
|
11 |
+
|
12 |
+
class RFDetrConfig(PretrainedConfig):
|
13 |
+
model_type = 'rf-detr'
|
14 |
+
|
15 |
+
def __init__(
|
16 |
+
self,
|
17 |
+
model_name: Literal['RFDETRBase, RFDETRLarge'] = 'RFDETRBase',
|
18 |
+
pretrained: bool = False,
|
19 |
+
out_feature_indexes: List[int] = [2, 5, 8, 11],
|
20 |
+
dec_layers: int = 3,
|
21 |
+
two_stage: bool = True,
|
22 |
+
bbox_reparam: bool = True,
|
23 |
+
lite_refpoint_refine: bool = True,
|
24 |
+
layer_norm: bool = True,
|
25 |
+
amp: bool = True,
|
26 |
+
num_classes: int = 90,
|
27 |
+
num_queries: int = 300,
|
28 |
+
device: Literal["cpu", "cuda", "mps"] = DEVICE,
|
29 |
+
resolution: int = 560,
|
30 |
+
group_detr: int = 13,
|
31 |
+
gradient_checkpointing: bool = False,
|
32 |
+
**kwargs
|
33 |
+
):
|
34 |
+
self.model_name = model_name
|
35 |
+
self.pretrained = pretrained
|
36 |
+
self.out_feature_indexes = out_feature_indexes
|
37 |
+
self.dec_layers = dec_layers
|
38 |
+
self.two_stage = two_stage
|
39 |
+
self.bbox_reparam = bbox_reparam
|
40 |
+
self.lite_refpoint_refine = lite_refpoint_refine
|
41 |
+
self.layer_norm = layer_norm
|
42 |
+
self.amp = amp
|
43 |
+
self.num_classes = num_classes
|
44 |
+
self.device = device
|
45 |
+
self.resolution = resolution
|
46 |
+
self.group_detr = group_detr
|
47 |
+
self.gradient_checkpointing = gradient_checkpointing
|
48 |
+
self.num_queries = num_queries
|
49 |
+
if self.model_name == 'RFDETRBase':
|
50 |
+
self.encoder = "dinov2_windowed_small"
|
51 |
+
self.hidden_dim = 256
|
52 |
+
self.sa_nheads = 8
|
53 |
+
self.ca_nheads = 16
|
54 |
+
self.dec_n_points = 2
|
55 |
+
self.projector_scale = ["P4"]
|
56 |
+
self.pretrain_weights = "rf-detr-base.pth"
|
57 |
+
elif self.model_name == 'RFDETRLarge':
|
58 |
+
self.encoder = "dinov2_windowed_base"
|
59 |
+
self.hidden_dim = 384
|
60 |
+
self.sa_nheads = 12
|
61 |
+
self.ca_nheads = 24
|
62 |
+
self.dec_n_points = 4
|
63 |
+
self.projector_scale = ["P3", "P5"]
|
64 |
+
self.pretrain_weights = "rf-detr-large.pth"
|
65 |
+
if not self.pretrained:
|
66 |
+
self.pretrain_weights = ""
|
67 |
+
super().__init__(**kwargs)
|
68 |
+
|
69 |
+
|
70 |
+
class RFDetrDummyInputGenerator(DummyVisionInputGenerator):
|
71 |
+
def generate(self, input_name: str, framework: str = "pt", int_dtype: str = "int64", float_dtype: str = "fp32"):
|
72 |
+
if input_name == "pixel_mask":
|
73 |
+
return self.random_mask_tensor(
|
74 |
+
shape=[self.batch_size, self.height, self.width],
|
75 |
+
framework=framework,
|
76 |
+
dtype="bool",
|
77 |
+
)
|
78 |
+
else:
|
79 |
+
return self.random_float_tensor(
|
80 |
+
shape=[self.batch_size, self.num_channels, self.height, self.width],
|
81 |
+
framework=framework,
|
82 |
+
dtype=float_dtype,
|
83 |
+
)
|
84 |
+
|
85 |
+
|
86 |
+
class RFDetrOnnxConfig(ViTOnnxConfig):
|
87 |
+
DUMMY_INPUT_GENERATOR_CLASSES = (RFDetrDummyInputGenerator,)
|
88 |
+
|
89 |
+
@property
|
90 |
+
def inputs(self) -> Dict[str, Dict[int, str]]:
|
91 |
+
return OrderedDict(
|
92 |
+
{
|
93 |
+
"pixel_values": {0: "batch_size", 1: "num_channels", 2: "height", 3: "width"},
|
94 |
+
"pixel_mask": {0: "batch_size", 1: "height", 2: "width"},
|
95 |
+
}
|
96 |
+
)
|
97 |
+
|
98 |
+
@property
|
99 |
+
def outputs(self) -> Dict[str, Dict[int, str]]:
|
100 |
+
common_outputs = super().outputs
|
101 |
+
|
102 |
+
if self.task == "object-detection":
|
103 |
+
common_outputs["logits"] = {0: "batch_size", 1: "num_queries", 2: "num_classes"}
|
104 |
+
common_outputs["pred_boxes"] = {0: "batch_size", 1: "num_queries", 2: "4"}
|
105 |
+
|
106 |
+
return common_outputs
|
107 |
+
|
108 |
+
|
109 |
+
__all__ = [
|
110 |
+
'RFDetrConfig',
|
111 |
+
'RFDetrOnnxConfig'
|
112 |
+
]
|
model.safetensors
ADDED
@@ -0,0 +1,3 @@
|
|
|
|
|
|
|
|
|
1 |
+
version https://git-lfs.github.com/spec/v1
|
2 |
+
oid sha256:e111471a1b37b21f6970075eb663e383b63cf99585968e3f67c2cc1507511a02
|
3 |
+
size 128760872
|
modeling_rf_detr.py
ADDED
@@ -0,0 +1,249 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
1 |
+
from dataclasses import dataclass
|
2 |
+
from typing import List, Dict
|
3 |
+
|
4 |
+
import torch
|
5 |
+
from torchvision.transforms import Resize
|
6 |
+
from transformers import PreTrainedModel
|
7 |
+
from transformers.utils import ModelOutput, torch_int
|
8 |
+
from rfdetr import RFDETRBase, RFDETRLarge
|
9 |
+
from rfdetr.util.misc import NestedTensor
|
10 |
+
|
11 |
+
from .configuration_rf_detr import RFDetrConfig
|
12 |
+
|
13 |
+
### ONLY WORKS WITH Transformers version 4.50.3 and python 3.11
|
14 |
+
|
15 |
+
@dataclass
|
16 |
+
class RFDetrObjectDetectionOutput(ModelOutput):
|
17 |
+
loss: torch.Tensor = None
|
18 |
+
loss_dict: Dict[str, torch.Tensor] = None
|
19 |
+
logits: torch.FloatTensor = None
|
20 |
+
pred_boxes: torch.FloatTensor = None
|
21 |
+
aux_outputs: List[Dict[str, torch.Tensor]] = None
|
22 |
+
enc_outputs: Dict[str, torch.Tensor] = None
|
23 |
+
|
24 |
+
|
25 |
+
class RFDetrModelForObjectDetection(PreTrainedModel):
|
26 |
+
config_class = RFDetrConfig
|
27 |
+
|
28 |
+
def __init__(self, config):
|
29 |
+
super().__init__(config)
|
30 |
+
self.config = config
|
31 |
+
models = {
|
32 |
+
'RFDETRBase': RFDETRBase,
|
33 |
+
'RFDETRLarge': RFDETRLarge,
|
34 |
+
}
|
35 |
+
rf_detr_model = models[config.model_name](
|
36 |
+
out_feature_indexes = config.out_feature_indexes,
|
37 |
+
dec_layers = config.dec_layers,
|
38 |
+
two_stage = config.two_stage,
|
39 |
+
bbox_reparam = config.bbox_reparam,
|
40 |
+
lite_refpoint_refine = config.lite_refpoint_refine,
|
41 |
+
layer_norm = config.layer_norm,
|
42 |
+
amp = config.amp,
|
43 |
+
num_classes = config.num_classes,
|
44 |
+
device = config.device,
|
45 |
+
resolution = config.resolution,
|
46 |
+
group_detr = config.group_detr,
|
47 |
+
gradient_checkpointing = config.gradient_checkpointing,
|
48 |
+
num_queries = config.num_queries,
|
49 |
+
encoder = config.encoder,
|
50 |
+
hidden_dim = config.hidden_dim,
|
51 |
+
sa_nheads = config.sa_nheads,
|
52 |
+
ca_nheads = config.ca_nheads,
|
53 |
+
dec_n_points = config.dec_n_points,
|
54 |
+
projector_scale = config.projector_scale,
|
55 |
+
pretrain_weights = config.pretrain_weights,
|
56 |
+
)
|
57 |
+
self.model = rf_detr_model.model.model
|
58 |
+
self.criterion = rf_detr_model.model.criterion
|
59 |
+
|
60 |
+
def compute_loss(self, outputs, labels=None):
|
61 |
+
"""
|
62 |
+
Parameters
|
63 |
+
----------
|
64 |
+
labels: list[Dict[str, torch.Tensor]]
|
65 |
+
list of bounding boxes and labels for each image in the batch.
|
66 |
+
outputs:
|
67 |
+
outputs from rfdetr model
|
68 |
+
"""
|
69 |
+
loss = None
|
70 |
+
loss_dict = None
|
71 |
+
#if self.model.training:
|
72 |
+
if labels is None:
|
73 |
+
#torch._assert(False, "targets should not be none when in training mode")
|
74 |
+
pass
|
75 |
+
else:
|
76 |
+
losses = self.criterion(outputs, targets=labels)
|
77 |
+
loss_dict = {
|
78 |
+
'loss_fl': losses["loss_ce"],
|
79 |
+
### class error and cardinality error is for logging purposes only, no back propagation
|
80 |
+
'class_error': losses["class_error"],
|
81 |
+
'cardinality_error': losses["cardinality_error"],
|
82 |
+
'loss_bbox': losses["loss_bbox"],
|
83 |
+
'loss_giou': losses["loss_giou"],
|
84 |
+
}
|
85 |
+
loss = sum(loss_dict[k] for k in ['loss_fl', 'loss_bbox', 'loss_giou'])
|
86 |
+
|
87 |
+
return loss, loss_dict
|
88 |
+
|
89 |
+
def validate_labels(self, labels):
|
90 |
+
# Check for degenerate boxes
|
91 |
+
for label_idx, label in enumerate(labels):
|
92 |
+
boxes = label["boxes"]
|
93 |
+
degenerate_boxes = boxes[:, 2:] <= 0
|
94 |
+
if degenerate_boxes.any():
|
95 |
+
# print the first degenerate box
|
96 |
+
bb_idx = torch.where(degenerate_boxes.any(dim=1))[0][0]
|
97 |
+
degen_bb: List[float] = boxes[bb_idx].tolist()
|
98 |
+
torch._assert(
|
99 |
+
False,
|
100 |
+
"All bounding boxes should have positive height and width."
|
101 |
+
f" Found invalid box {degen_bb} for target at index {label_idx}.",
|
102 |
+
)
|
103 |
+
# rename key class_labels to labels for compute_loss
|
104 |
+
if 'class_labels' in label.keys():
|
105 |
+
label['labels'] = label.pop('class_labels')
|
106 |
+
|
107 |
+
def resize_labels(self, labels, h, w):
|
108 |
+
"""
|
109 |
+
Resize boxes coordinates to model's resolution
|
110 |
+
"""
|
111 |
+
hr = self.config.resolution / float(h)
|
112 |
+
wr = self.config.resolution / float(w)
|
113 |
+
|
114 |
+
for label in labels:
|
115 |
+
boxes = label["boxes"].to(device=self.config.device, dtype=torch.float32)
|
116 |
+
# resize boxes to model's resolution
|
117 |
+
boxes[:, [0, 2]] *= wr
|
118 |
+
boxes[:, [1, 3]] *= hr
|
119 |
+
# normalize to [0, 1] by model's resolution
|
120 |
+
boxes[:] /= self.config.resolution
|
121 |
+
label["boxes"] = boxes
|
122 |
+
if "labels" in label:
|
123 |
+
label["labels"] = label["labels"].to(self.config.device)
|
124 |
+
|
125 |
+
### modified from https://github.com/roboflow/rf-detr/blob/develop/rfdetr/models/backbone/dinov2_with_windowed_attn.py
|
126 |
+
def _onnx_interpolate_pos_encoding(self, embeddings: torch.Tensor, height: int, width: int) -> torch.Tensor:
|
127 |
+
"""
|
128 |
+
This method allows to interpolate the pre-trained position encodings, to be able to use the model on higher
|
129 |
+
resolution images. This implementation supports torch.jit tracing while maintaining backwards compatibility
|
130 |
+
with the original implementation.
|
131 |
+
|
132 |
+
Adapted from:
|
133 |
+
- https://github.com/facebookresearch/dino/blob/main/vision_transformer.py
|
134 |
+
- https://github.com/facebookresearch/dinov2/blob/main/dinov2/models/vision_transformer.py
|
135 |
+
"""
|
136 |
+
position_embeddings = self.model.backbone[0].encoder.encoder.embeddings.position_embeddings
|
137 |
+
config = self.model.backbone[0].encoder.encoder.embeddings.config
|
138 |
+
|
139 |
+
num_patches = embeddings.shape[1] - 1
|
140 |
+
num_positions = position_embeddings.shape[1] - 1
|
141 |
+
|
142 |
+
# Skip interpolation for matching dimensions (unless tracing)
|
143 |
+
if not torch.jit.is_tracing() and num_patches == num_positions and height == width:
|
144 |
+
return position_embeddings
|
145 |
+
|
146 |
+
# Handle class token and patch embeddings separately
|
147 |
+
class_pos_embed = position_embeddings[:, 0]
|
148 |
+
patch_pos_embed = position_embeddings[:, 1:]
|
149 |
+
dim = embeddings.shape[-1]
|
150 |
+
|
151 |
+
# Calculate new dimensions
|
152 |
+
height = height // config.patch_size
|
153 |
+
width = width // config.patch_size
|
154 |
+
|
155 |
+
# Reshape for interpolation
|
156 |
+
sqrt_num_positions = torch_int(num_positions**0.5)
|
157 |
+
patch_pos_embed = patch_pos_embed.reshape(1, sqrt_num_positions, sqrt_num_positions, dim)
|
158 |
+
patch_pos_embed = patch_pos_embed.permute(0, 3, 1, 2)
|
159 |
+
|
160 |
+
# Store original dtype for restoration after interpolation
|
161 |
+
target_dtype = patch_pos_embed.dtype
|
162 |
+
|
163 |
+
# Interpolate at float32 precision
|
164 |
+
### disable antialiasing for ONNX export
|
165 |
+
patch_pos_embed = torch.nn.functional.interpolate(
|
166 |
+
patch_pos_embed.to(dtype=torch.float32),
|
167 |
+
size=(torch_int(height), torch_int(width)), # Explicit size instead of scale_factor
|
168 |
+
mode="bicubic",
|
169 |
+
align_corners=False,
|
170 |
+
antialias=False,
|
171 |
+
).to(dtype=target_dtype)
|
172 |
+
|
173 |
+
# Validate output dimensions if not tracing
|
174 |
+
if not torch.jit.is_tracing():
|
175 |
+
if int(height) != patch_pos_embed.shape[-2] or int(width) != patch_pos_embed.shape[-1]:
|
176 |
+
raise ValueError("Width or height does not match with the interpolated position embeddings")
|
177 |
+
|
178 |
+
# Reshape back to original format
|
179 |
+
patch_pos_embed = patch_pos_embed.permute(0, 2, 3, 1).view(1, -1, dim)
|
180 |
+
|
181 |
+
# Combine class and patch embeddings
|
182 |
+
return torch.cat((class_pos_embed.unsqueeze(0), patch_pos_embed), dim=1)
|
183 |
+
|
184 |
+
def forward(self, pixel_values: torch.Tensor, pixel_mask: torch.Tensor, labels=None, **kwargs) -> ModelOutput:
|
185 |
+
"""
|
186 |
+
Parameters
|
187 |
+
----------
|
188 |
+
pixel_values : torch.Tensor
|
189 |
+
Input tensor representing image pixel values.
|
190 |
+
labels : Optional[List[Dict[str, torch.Tensor | List]]]
|
191 |
+
List of annotations associated with the image or batch of images. If annotation is for object
|
192 |
+
detection, the annotations should be a dictionary with the following keys:
|
193 |
+
- boxes (FloatTensor[N, 4]): the ground-truth boxes in format [center_x, center_y, width, height]
|
194 |
+
- class_labels (Int64Tensor[N]): the class label for each ground-truth box
|
195 |
+
|
196 |
+
Returns
|
197 |
+
-------
|
198 |
+
RFDetrObjectDetectionOutput
|
199 |
+
Object containing
|
200 |
+
- loss: sum of focal loss, bounding box loss, and generalized iou loss
|
201 |
+
- loss_dict: dictionary of losses
|
202 |
+
- logits
|
203 |
+
- pred_boxes
|
204 |
+
- aux_outputs
|
205 |
+
- enc_outputs
|
206 |
+
"""
|
207 |
+
if torch.jit.is_tracing():
|
208 |
+
### disable antialiasing for ONNX export
|
209 |
+
resize = Resize((self.config.resolution, self.config.resolution), antialias=False)
|
210 |
+
self.model.backbone[0].encoder.encoder.embeddings.interpolate_pos_encoding = self._onnx_interpolate_pos_encoding
|
211 |
+
else:
|
212 |
+
resize = Resize((self.config.resolution, self.config.resolution))
|
213 |
+
|
214 |
+
if labels is not None:
|
215 |
+
self.validate_labels(labels)
|
216 |
+
_, _, h, w = pixel_values.shape
|
217 |
+
self.resize_labels(labels, h, w) # reshape labels with model's resolution
|
218 |
+
else:
|
219 |
+
self.model.training = False
|
220 |
+
self.model.transformer.training = False
|
221 |
+
for layer in self.model.transformer.decoder.layers:
|
222 |
+
layer.training = False
|
223 |
+
self.criterion.training = False
|
224 |
+
|
225 |
+
# resize pixel values and mask to model's resolution
|
226 |
+
pixel_values = pixel_values.to(self.config.device)
|
227 |
+
pixel_mask = pixel_mask.to(self.config.device)
|
228 |
+
pixel_values = resize(pixel_values)
|
229 |
+
pixel_mask = resize(pixel_mask)
|
230 |
+
|
231 |
+
samples = NestedTensor(pixel_values, pixel_mask)
|
232 |
+
outputs = self.model(samples)
|
233 |
+
|
234 |
+
# compute loss, return none and empty dict if not training
|
235 |
+
loss, loss_dict = self.compute_loss(outputs, labels)
|
236 |
+
|
237 |
+
return RFDetrObjectDetectionOutput(
|
238 |
+
loss=loss,
|
239 |
+
loss_dict=loss_dict,
|
240 |
+
logits=outputs["pred_logits"],
|
241 |
+
pred_boxes=outputs["pred_boxes"],
|
242 |
+
aux_outputs=outputs["aux_outputs"],
|
243 |
+
enc_outputs=outputs["enc_outputs"],
|
244 |
+
)
|
245 |
+
|
246 |
+
|
247 |
+
__all__ = [
|
248 |
+
"RFDetrModelForObjectDetection"
|
249 |
+
]
|