Thastp commited on
Commit
b263aee
·
verified ·
1 Parent(s): e2a576d

Upload model

Browse files
Files changed (5) hide show
  1. README.md +199 -0
  2. config.json +41 -0
  3. configuration_rf_detr.py +93 -0
  4. model.safetensors +3 -0
  5. modeling_rf_detr.py +158 -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,93 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
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
+
7
+ ### modified from https://github.com/roboflow/rf-detr/blob/main/rfdetr/config.py
8
+
9
+ DEVICE = "cuda" if torch.cuda.is_available() else "mps" if torch.backends.mps.is_available() else "cpu"
10
+
11
+ class RFDetrConfig(PretrainedConfig):
12
+ model_type = 'rf-detr'
13
+
14
+ def __init__(
15
+ self,
16
+ model_name: Literal['RFDETRBase, RFDETRLarge'] = 'RFDETRBase',
17
+ pretrained: bool = True,
18
+ out_feature_indexes: List[int] = [2, 5, 8, 11],
19
+ dec_layers: int = 3,
20
+ two_stage: bool = True,
21
+ bbox_reparam: bool = True,
22
+ lite_refpoint_refine: bool = True,
23
+ layer_norm: bool = True,
24
+ amp: bool = True,
25
+ num_classes: int = 90,
26
+ num_queries: int = 300,
27
+ device: Literal["cpu", "cuda", "mps"] = DEVICE,
28
+ resolution: int = 560,
29
+ group_detr: int = 13,
30
+ gradient_checkpointing: bool = False,
31
+ **kwargs
32
+ ):
33
+ self.model_name = model_name
34
+ self.pretrained = pretrained
35
+ self.out_feature_indexes = out_feature_indexes
36
+ self.dec_layers = dec_layers
37
+ self.two_stage = two_stage
38
+ self.bbox_reparam = bbox_reparam
39
+ self.lite_refpoint_refine = lite_refpoint_refine
40
+ self.layer_norm = layer_norm
41
+ self.amp = amp
42
+ self.num_classes = num_classes
43
+ self.device = device
44
+ self.resolution = resolution
45
+ self.group_detr = group_detr
46
+ self.gradient_checkpointing = gradient_checkpointing
47
+ self.num_queries = num_queries
48
+ if self.model_name == 'RFDETRBase':
49
+ self.encoder = "dinov2_windowed_small"
50
+ self.hidden_dim = 256
51
+ self.sa_nheads = 8
52
+ self.ca_nheads = 16
53
+ self.dec_n_points = 2
54
+ self.projector_scale = ["P4"]
55
+ self.pretrain_weights = "rf-detr-base.pth"
56
+ elif self.model_name == 'RFDETRLarge':
57
+ self.encoder = "dinov2_windowed_base"
58
+ self.hidden_dim = 384
59
+ self.sa_nheads = 12
60
+ self.ca_nheads = 24
61
+ self.dec_n_points = 4
62
+ self.projector_scale = ["P3", "P5"]
63
+ self.pretrain_weights = "rf-detr-large.pth"
64
+ if not self.pretrained:
65
+ self.pretrain_weights = ""
66
+ super().__init__(**kwargs)
67
+
68
+
69
+ class RFDetrOnnxConfig(ViTOnnxConfig):
70
+ @property
71
+ def inputs(self) -> Dict[str, Dict[int, str]]:
72
+ return OrderedDict(
73
+ {
74
+ "pixel_values": {0: "batch_size", 1: "num_channels", 2: "height", 3: "width"},
75
+ "pixel_mask": {0: "batch_size", 2: "height", 3: "width"},
76
+ }
77
+ )
78
+
79
+ @property
80
+ def outputs(self) -> Dict[str, Dict[int, str]]:
81
+ common_outputs = super().outputs
82
+
83
+ if self.task == "object-detection":
84
+ common_outputs["logits"] = {0: "batch_size", 1: "num_queries", 2: "num_classes"}
85
+ common_outputs["pred_boxes"] = {0: "batch_size", 1: "num_queries", 2: "4"}
86
+
87
+ return common_outputs
88
+
89
+
90
+ __all__ = [
91
+ 'RFDetrConfig',
92
+ 'RFDetrOnnxConfig'
93
+ ]
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,158 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
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
8
+ from rfdetr import RFDETRBase, RFDETRLarge
9
+ from rfdetr.util.misc import NestedTensor
10
+
11
+ from .configuration_rf_detr import RFDetrConfig
12
+
13
+
14
+ @dataclass
15
+ class RFDetrObjectDetectionOutput(ModelOutput):
16
+ loss: torch.Tensor = None
17
+ loss_dict: Dict[str, torch.Tensor] = None
18
+ logits: torch.FloatTensor = None
19
+ pred_boxes: torch.FloatTensor = None
20
+ aux_outputs: List[Dict[str, torch.Tensor]] = None
21
+ enc_outputs: Dict[str, torch.Tensor] = None
22
+
23
+
24
+ class RFDetrModelForObjectDetection(PreTrainedModel):
25
+ config_class = RFDetrConfig
26
+
27
+ def __init__(self, config):
28
+ super().__init__(config)
29
+ self.config = config
30
+ models = {
31
+ 'RFDETRBase': RFDETRBase,
32
+ 'RFDETRLarge': RFDETRLarge,
33
+ }
34
+ rf_detr_model = models[config.model_name](
35
+ out_feature_indexes = config.out_feature_indexes,
36
+ dec_layers = config.dec_layers,
37
+ two_stage = config.two_stage,
38
+ bbox_reparam = config.bbox_reparam,
39
+ lite_refpoint_refine = config.lite_refpoint_refine,
40
+ layer_norm = config.layer_norm,
41
+ amp = config.amp,
42
+ num_classes = config.num_classes,
43
+ device = config.device,
44
+ resolution = config.resolution,
45
+ group_detr = config.group_detr,
46
+ gradient_checkpointing = config.gradient_checkpointing,
47
+ num_queries = config.num_queries,
48
+ encoder = config.encoder,
49
+ hidden_dim = config.hidden_dim,
50
+ sa_nheads = config.sa_nheads,
51
+ ca_nheads = config.ca_nheads,
52
+ dec_n_points = config.dec_n_points,
53
+ projector_scale = config.projector_scale,
54
+ pretrain_weights = config.pretrain_weights,
55
+ )
56
+ self.model = rf_detr_model.model.model
57
+ self.criterion = rf_detr_model.model.criterion
58
+
59
+ def compute_loss(self, labels, outputs):
60
+ """
61
+ Parameters
62
+ ----------
63
+ labels: list[Dict[str, torch.Tensor]]
64
+ list of bounding boxes and labels for each image in the batch.
65
+ outputs:
66
+ outputs from rfdetr model
67
+ """
68
+ loss = None
69
+ loss_dict = None
70
+ if self.model.training:
71
+ if labels is None:
72
+ torch._assert(False, "targets should not be none when in training mode")
73
+ else:
74
+ losses = self.criterion(outputs, targets=labels)
75
+ loss_dict = {
76
+ 'loss_fl': losses["loss_ce"],
77
+ 'class_error': losses["class_error"],
78
+ 'cardinality_error': losses["cardinality_error"],
79
+ 'loss_bbox': losses["loss_bbox"],
80
+ 'loss_giou': losses["loss_giou"],
81
+ }
82
+ loss = sum(loss_dict[k] for k in ['loss_fl', 'loss_bbox', 'loss_giou'])
83
+
84
+ return loss, loss_dict
85
+
86
+ def validate_labels(self, labels):
87
+ # Check for degenerate boxes
88
+ for label_idx, label in enumerate(labels):
89
+ boxes = label["boxes"]
90
+ degenerate_boxes = boxes[:, 2:] <= boxes[:, :2]
91
+ if degenerate_boxes.any():
92
+ # print the first degenerate box
93
+ bb_idx = torch.where(degenerate_boxes.any(dim=1))[0][0]
94
+ degen_bb: List[float] = boxes[bb_idx].tolist()
95
+ torch._assert(
96
+ False,
97
+ "All bounding boxes should have positive height and width."
98
+ f" Found invalid box {degen_bb} for target at index {label_idx}.",
99
+ )
100
+ # rename key class_labels to labels for compute_loss
101
+ if 'class_labels' in label.keys():
102
+ label['labels'] = label.pop('class_labels')
103
+
104
+ def resize_labels(self, labels, h, w):
105
+ hr = self.config.resolution / float(h)
106
+ wr = self.config.resolution / float(w)
107
+
108
+ for label in labels:
109
+ boxes = label["boxes"].to(device=self.config.device, dtype=torch.float32)
110
+ # resize boxes to model's resolution
111
+ boxes[:, 0] *= wr
112
+ boxes[:, 1] *= hr
113
+ boxes[:, 2] *= wr
114
+ boxes[:, 3] *= hr
115
+ # convert top left to center x, y
116
+ boxes[:, 0] = (boxes[:, 0] + boxes[:, 2]) / 2
117
+ boxes[:, 1] = (boxes[:, 1] + boxes[:, 3]) / 2
118
+ # normalize to [0, 1] by model's resolution
119
+ boxes[:] /= self.config.resolution
120
+ label["boxes"] = boxes
121
+ if "labels" in label:
122
+ label["labels"] = label["labels"].to(self.config.device)
123
+
124
+ def forward(self, pixel_values: torch.Tensor, pixel_mask: torch.Tensor, labels=None, **kwargs) -> ModelOutput:
125
+ resize = Resize((self.config.resolution, self.config.resolution)) # resize pixel values and mask to model's resolution
126
+ pixel_values = pixel_values.to(self.config.device)
127
+ pixel_mask = pixel_mask.to(self.config.device)
128
+ pixel_values = resize(pixel_values)
129
+ pixel_mask = resize(pixel_mask)
130
+
131
+ if labels is not None:
132
+ self.validate_labels(labels)
133
+ _, _, h, w = pixel_values.shape
134
+ self.resize_labels(labels, h, w) # reshape labels with model's resolution
135
+ else:
136
+ self.model.training = False
137
+ self.model.transformer.training = False
138
+ for layer in self.model.transformer.decoder.layers:
139
+ layer.training = False
140
+ self.criterion.training = False
141
+
142
+ samples = NestedTensor(pixel_values, pixel_mask)
143
+ outputs = self.model(samples)
144
+
145
+ loss, loss_dict = self.compute_loss(labels, outputs)
146
+
147
+ return RFDetrObjectDetectionOutput(
148
+ loss=loss,
149
+ loss_dict=loss_dict,
150
+ logits=outputs["pred_logits"],
151
+ pred_boxes=outputs["pred_boxes"],
152
+ aux_outputs=outputs["aux_outputs"],
153
+ enc_outputs=outputs["enc_outputs"],
154
+ )
155
+
156
+ __all__ = [
157
+ "RFDetrModelForObjectDetection"
158
+ ]