-
Notifications
You must be signed in to change notification settings - Fork 31.9k
[WIP] Add DINO DETR Model to HuggingFace Transformers #36711
New issue
Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.
By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.
Already on GitHub? Sign in to your account
Open
konstantinos-p
wants to merge
104
commits into
huggingface:main
Choose a base branch
from
konstantinos-p:dino_detr_model
base: main
Could not load branches
Branch not found: {{ refName }}
Loading
Could not load tags
Nothing to show
Loading
Are you sure you want to change the base?
Some commits from the old base branch may be removed from the timeline,
and old review comments may become outdated.
Open
Changes from all commits
Commits
Show all changes
104 commits
Select commit
Hold shift + click to select a range
81f044d
First commit for DINO - DETR. Copy-paste files from Deformable DETR a…
e4f726d
Add dino detr loss
216c444
First implementation of dino detr post processor
e7ea7f9
Add misc functions to dino modeling, make config first version
19f79d2
Restructure dino detr modeling code, major changes are now required o…
f2f3d02
Match config to source code in modeling dino detr, defaults in config…
2e438d8
Clean up dino_detr_config
efcadcf
Fixed import errors, code can now be executed
b9f6f15
Model now can be instantiated with random weights
a5c9f5a
Forward pass for randomly initialized model now executes without errors
e464c28
Forward pass works for DINO model with pretrained weights and matches…
51c565c
Add dino detr conversion to pytorch script
e2dcc0c
Ensure model outputs for single COCO image are within 1e-3 error of r…
14dfc25
Add draft unit tests
87065ac
Apply make style
254adfa
Modeling integration test passes
b9daab5
Add integration and unit tests
d20be46
Remove unnecessary dependency on pretrained model class from some cla…
db789ed
All image processing tests pass
4efe590
Consistently start module names with DinoDetr
ebd4fa6
Pass test_hidden_states_output test
72689b3
Dino detr doesn't support gradient checkpointing
e8f055b
Pass test_model_is_small test
5bfe3a1
Pass test_model_outputs_equivalence test
35181a0
Pass test_attention_outputs
c76d6e3
Pass test_retain_grad_hidden_states_attentions
c5f3cb0
Pass safetensor tests
00e2932
All tests pass for the first model draft
f7bac4c
Convert weights to hf using a single key mapping and regex
6454cad
Add some missing copied_from comments, these work with the huggingfac…
1eec3f7
Move all asserts to the config
b9cfd1e
Remove some unused config parameters
28de022
Remove unused config parameters, simplify inits
9aa7b73
Clean up decoder code
1e6567f
Clean up deformable transformer code
52f9e8a
Clean DinoDetrModel code
4bfa659
Clean up DinoDetrForObjectDetection class
476c4fa
Add type hints
bc845c7
Add a model checkpoint to hub
8eef2a1
Fix copied from in image_processing_dino_detr
0ca2f6a
Some changes to make copied from mechanism work
479cdd1
Fix more code quality errors
7cf7ae0
Fill missing values config docstring
d1556d1
Add dino detr to models/__init__.py file
388cae3
DinoDetrDeformableTransformer is recognized as a model, attempt a fix
8f4dcf4
Attempt fix for DinoDetrDeformableTransformer getting classified as a…
a817f84
Add docs template
e3c3a53
Add missing model type to the constant
ca9dd3c
Remove config from loss function definition
9ab7bb8
Remove unused config parameters
6671acf
DinoDetr docs first complete draft
abb3a67
Clean docstrings
ea928f0
Add docs to toctree.yml
a059714
Fix some errors after rebase
58fa28b
Update deformable attention definition
aed7208
Implement using modular
7f5f8cd
Apply conditions on some imports
98f7f25
Remove asserts from postprocessing method
d201f21
Sort imports
c367c4e
Small fixes
9703b52
Style changes from make fixup
14d4dc8
Small fixes
0b818da
Address reviewer comments
67c1d50
Clean up dino_loss import from detection_loss when possible
2f4d20a
Clean up configuration_dino_detr.py
ca3073a
Clean up convert_dino_detr_to_pytorch.py
8af3f3f
Remove feature extraction file
9818289
Address reviewer comments
aa07ace
Replace _get_activation_fn with ACT2FN
b01762a
Use get_contrastive_denoising_training_group from rt_detr
c90bd59
Reuse deformable_detr image_processor
8d26a08
Simplify config
1380dd5
Clean up modular code, add comments
f1163d7
Cleanup of embeddings
02a1197
Cleanup embeddings
8442405
Cleanup: remove layer dropout, two_stage options, ref_token, etc
578585f
Clean modeling code
626d62d
Add DinoDetrImageProcessor to __all__
116d400
Make fix copies
323e567
Revert changes to test modeling deformable detr
3b3b07a
Small fix
922ac92
Fix docstring
5987ad9
Ignore docstring consistency, it throws misleading errors
df64313
Add architecture link to config docstring
348cb35
Replace return_dict with can_return_tuple
45b6d13
Use _can_record_outputs instead of output_attentions output_hidden_st…
a97f835
Simplify code
5cda82b
Simplify layer share
a4e4bc6
Make code simpler
b89edb0
Rename cardinality loss to cardinality error
c0acd49
Remove redundant imports from modular
01692bb
Improve docs
a7326d8
Fix failing tests after rebase
701a7ad
Fix most tests apart from test_can_use_safetensors and test_load_save…
8128b03
Remove tied weights
9f28b71
Simplify code
83c818f
Simplify _can_record_outputs
b578c84
Add auto_docstring
a9647a5
Simplify EmbeddingSineHW
b10f26a
Simplify code
7f6c0f5
Simplify decoder layer
08b1130
Remove get_clones completely
97c723a
Fix auto_docstring
5a3fec3
Fix ini_weights
File filter
Filter by extension
Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
There are no files selected for viewing
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
| Original file line number | Diff line number | Diff line change |
|---|---|---|
| @@ -0,0 +1,130 @@ | ||
| <!--Copyright 2025 The HuggingFace Team. All rights reserved. | ||
|
|
||
| Licensed under the Apache License, Version 2.0 (the "License"); you may not use this file except in compliance with | ||
| the License. You may obtain a copy of the License at | ||
|
|
||
| http://www.apache.org/licenses/LICENSE-2.0 | ||
|
|
||
| Unless required by applicable law or agreed to in writing, software distributed under the License is distributed on | ||
| an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the License for the | ||
| specific language governing permissions and limitations under the License. | ||
|
|
||
| ⚠️ Note that this file is in Markdown but contain specific syntax for our doc-builder (similar to MDX) that may not be | ||
| rendered properly in your Markdown viewer. | ||
|
|
||
| --> | ||
|
|
||
| # DINO DETR | ||
|
|
||
| <div class="flex flex-wrap space-x-1"> | ||
| <img alt="PyTorch" src="https://img.shields.io/badge/PyTorch-DE3412?style=flat&logo=pytorch&logoColor=white"> | ||
| </div> | ||
|
|
||
| ## Overview | ||
|
|
||
| DINO DETR (DETR with Improved DeNoising Anchor Boxes) is a state-of-the-art end-to-end object detection model introduced in the paper [DINO: DETR with Improved DeNoising Anchor Boxes for End-to-End Object Detection](https://arxiv.org/abs/2203.03605) by Hao Zhang, Feng Li, Shilong Liu, Lei Zhang, Hang Su, Jun Zhu, Lionel M. Ni and Heung-Yeung Shum. It builds upon the original DETR framework by addressing key challenges in convergence speed and detection accuracy. | ||
|
|
||
| DINO DETR enhances the DETR architecture through three main innovations: | ||
|
|
||
| * **Mixed Query Selection for Anchor Initialization**: In DINO DETR decoder queries consist of query locations and query features. The decoder query locations are selected by passing the encoder features through a classification head and selecting the topk locations in terms of max class probability. The decoder query features are learnable weights shared across all samples. In this way, the query locations are initialized close to interesting objects and the query features are made robust to different object classes. | ||
|
|
||
| * **Contrastive Denoising Training**: DINO Detr uses denoising queries together with "standard" DETR queries. The denoising queries are strongly perturbed versions of standard queries, assigned to negative labels. This improves the model's robustness and convergence speed. | ||
|
|
||
| * **Look Forward Twice Scheme for Box Prediction**: This term means that the bounding boxes are refined iteratively from one decoder layer to the next, by adding corrections to the previous layer bounding boxes. This improves training stability. | ||
|
|
||
| These advancements enable DINO DETR to achieve significant performance improvements over previous DETR-like models. For instance, with a ResNet-50 backbone and multi-scale features, DINO attains 49.4 AP in 12 epochs and 51.3 AP in 24 epochs on the COCO dataset, marking a substantial enhancement in detection performance. | ||
|
|
||
| The abstract of the paper is the following: | ||
|
|
||
| *We present DINO (DETR with Improved deNoising anchOr boxes), a state-of-the-art end-to-end object detector. DINO improves over previous DETR-like models in performance and efficiency by using a contrastive way for denoising training, a mixed query selection method for anchor initialization, and a look forward twice scheme for box prediction. DINO achieves 49.4AP in 12 epochs and 51.3AP in 24 epochs on COCO with a ResNet-50 backbone and multi-scale features, yielding a significant improvement of +6.0AP and +2.7AP, respectively, compared to DN-DETR, the previous best DETR-like model. DINO scales well in both model size and data size. Without bells and whistles, after pre-training on the Objects365 dataset with a SwinL backbone, DINO obtains the best results on both COCO val2017 (63.2AP) and test-dev (63.3AP). Compared to other models on the leaderboard, DINO significantly reduces its model size and pre-training data size while achieving better results.* | ||
|
|
||
| This implementation is contributed by [kostaspitas](https://huggingface.co/kostaspitas) and is based on the official code available at [https://github.com/IDEA-Research/DINO](https://github.com/IDEA-Research/DINO). | ||
|
|
||
| ### Model Architecture | ||
|
|
||
| DINO DETR with Improved DeNoising Anchor Boxes (DINO) follows a similar architecture to the original DETR but introduces enhancements for improved performance and efficiency. | ||
|
|
||
| #### 1. Backbone | ||
|
|
||
| An input image is processed through a pre-trained convolutional backbone, such as ResNet-50 or ResNet-101. This backbone extracts multi-scale feature maps, which are then projected to match the hidden dimension of the Transformer encoder. For instance, a feature map of shape `(batch_size, 2048, height/32, width/32)` is transformed to `(batch_size, 256, height/32, width/32)` using a convolutional layer. These feature maps are then flattened and transposed to obtain a tensor of shape `(batch_size, seq_len, d_model)`, where `seq_len` is the number of spatial locations and `d_model` is the model dimension (e.g., 256). | ||
|
|
||
| #### 2. Transformer Encoder | ||
|
|
||
| The flattened feature maps are passed through a multi-layer transformer encoder. The self-attention implementation is deformable attention as first introduced in the [Deformable DETR](https://arxiv.org/abs/2010.04159) paper. This encoder processes the input sequence and outputs `encoder_hidden_states`, which serve as the image features for the subsequent decoder. | ||
|
|
||
| #### 3. Object Queries and Decoder | ||
|
|
||
| DINO introduces dynamic anchor boxes as object queries. These queries are initialized based on anchor box coordinates and are updated through the decoder layers. The decoder receives these object queries along with the encoder outputs and processes them through multiple self-attention and encoder-decoder cross-attention layers. The decoder cross attention layers perform deformable attention while self-attention is standard multi-head self-attention. The result is `decoder_hidden_states`, which are then used for prediction. | ||
|
|
||
| #### 4. Prediction Heads | ||
|
|
||
| On top of the decoder outputs, DINO adds two prediction heads: | ||
|
|
||
| * **Classification Head**: A linear layer that classifies each object query into one of the object categories or "no object". | ||
|
|
||
| * **Bounding Box Head**: A multi-layer perceptron (MLP) that predicts the bounding box coordinates for each object query. | ||
|
|
||
| #### 5. Training with Bipartite Matching Loss | ||
|
|
||
| DINO employs a bipartite matching loss during training. The predicted classes and bounding boxes for each object query are compared to the ground truth annotations, padded to the same length. The Hungarian algorithm is used to find an optimal one-to-one mapping between the predicted and ground truth annotations. The loss function combines focal loss for classification and a linear combination of L1 loss and generalized Intersection over Union (IoU) loss for bounding box regression. In addition to the original DETR queries, DINO DETR adds a denoising query set which feeds noised groundtruth labels and boxes into the decoder to provide an aixiliary denoising loss. The denoising loss effectively stabilizes and speeds up the DINO DETR training. | ||
|
|
||
| ## Usage Tips | ||
|
|
||
| - **Object Queries**: DINO utilizes dynamic anchor boxes as object queries to detect objects within an image. The number of queries (`num_queries`) determines the maximum number of objects that can be detected in a single image. By default, this is set to 900 (e.g., 300 queries × 3 patterns) to enhance detection performance. | ||
| - **Decoder Parallelism**: Similar to the original DETR, DINO's decoder updates object queries in parallel, differing from autoregressive models like GPT-2. Consequently, no causal attention mask is employed. | ||
| - **Position Embeddings**: DINO adds position embeddings to the hidden states at each self-attention and cross-attention layer before projecting to queries and keys. For image position embeddings, you can choose between fixed sinusoidal or learned absolute position embeddings. By default, the `position_embedding_type` parameter in `DinoDetrConfig` is set to `"SineWH"`. | ||
| - **Auxiliary Losses**: During training, employing auxiliary losses in the decoder can be beneficial, especially for improving the model's ability to predict the correct number of objects per class. Setting the `auxiliary_loss` parameter in `DinoDetrConfig` to `True` adds an auxiliary_loss after each decoder layer. | ||
| - **Distributed Training**: When training the model across multiple nodes, it's important to update the `num_boxes` variable in the `DinoLoss` class to reflect the average number of target boxes across all nodes. This adjustment ensures proper loss computation during distributed training. | ||
| - **Backbone Initialization**: `DinoDetrForObjectDetection` can be initialized with any convolutional backbone available in the [timm library](https://github.com/rwightman/pytorch-image-models). For instance, to use a MobileNet backbone, set the `backbone` attribute in `DinoDetrConfig` to `"tf_mobilenetv3_small_075"` and initialize the model with this configuration. | ||
| - **Image Preprocessing**: DINO resizes input images such that the shortest side is at least a certain number of pixels, while the longest side is at most 1333 pixels. During training, scale augmentation is applied, randomly setting the shortest side to between 480 and 800 pixels and its longer side to be at most 1333 pixels. At inference time, the shortest side is set to 800 pixels. Use `DinoDetrImageProcessor` to prepare images (and optional annotations in COCO format) for the model. Due to resizing, images in a batch may have different sizes. DinoDetr addresses this by padding images to the largest size in the batch and creating a pixel mask to differentiate real pixels from padding. Alternatively, you can define a custom `collate_fn` to batch images using `DinoDetrImageProcessor.pad_and_create_pixel_mask`. | ||
| - **Batch Size Considerations**: The size of input images affects memory usage and, consequently, the `batch_size`. | ||
|
|
||
| ### Model Initialization Options | ||
|
|
||
| There are three ways to instantiate a DinoDetr model: | ||
|
|
||
| **Option 1**: Instantiate DinoDetr with pre-trained weights for the entire model | ||
| ```python | ||
| >>> from transformers import DinoDetrForObjectDetection | ||
|
|
||
| >>> model = DinoDetrForObjectDetection.from_pretrained("IDEA-Research/dino-resnet-50") | ||
| ``` | ||
| **Option 2**: Instantiate DinoDetr with randomly initialized Transformer weights but pre-trained backbone weights | ||
| ```python | ||
| >>> from transformers import DinoDetrConfig, DinoDetrForObjectDetection | ||
|
|
||
| >>> config = DinoDetrConfig() | ||
| >>> model = DinoDetrForObjectDetection(config) | ||
| ``` | ||
| **Option 3**: Instantiate DinoDetr with randomly initialized weights for both backbone and Transformer | ||
| ```python | ||
| >>> config = DinoDetrConfig(use_pretrained_backbone=False) | ||
| >>> model = DinoDetrForObjectDetection(config) | ||
| ``` | ||
| One should prepare the data in COCO detection format, then use | ||
| [`~transformers.DetrImageProcessor`] to create `pixel_values`, `pixel_mask` and optional | ||
| `labels`, which can then be used to train (or fine-tune) a model. For evaluation, one should first convert the | ||
| outputs of the model using one of the postprocessing methods of [`~transformers.DetrImageProcessor`]. These can | ||
| be provided to either `CocoEvaluator` which allow you to calculate metrics like | ||
| mean Average Precision (mAP). | ||
|
|
||
| ## DinoDetrModel | ||
|
|
||
| [[autodoc]] DinoDetrModel | ||
|
|
||
| ## DinoDetrForObjectDetection | ||
|
|
||
| [[autodoc]] DinoDetrForObjectDetection | ||
|
|
||
| ## DinoDetrConfig | ||
|
|
||
| [[autodoc]] DinoDetrConfig | ||
|
|
||
| ## DinoDetrImageProcessor | ||
|
|
||
| [[autodoc]] DinoDetrImageProcessor | ||
|
|
||
| ## DinoDetrFeatureExtractor | ||
|
|
||
| [[autodoc]] DinoDetrFeatureExtractor | ||
|
|
||
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
Oops, something went wrong.
Add this suggestion to a batch that can be applied as a single commit.
This suggestion is invalid because no changes were made to the code.
Suggestions cannot be applied while the pull request is closed.
Suggestions cannot be applied while viewing a subset of changes.
Only one suggestion per line can be applied in a batch.
Add this suggestion to a batch that can be applied as a single commit.
Applying suggestions on deleted lines is not supported.
You must change the existing code in this line in order to create a valid suggestion.
Outdated suggestions cannot be applied.
This suggestion has been applied or marked resolved.
Suggestions cannot be applied from pending reviews.
Suggestions cannot be applied on multi-line comments.
Suggestions cannot be applied while the pull request is queued to merge.
Suggestion cannot be applied right now. Please check back later.
There was a problem hiding this comment.
Choose a reason for hiding this comment
The reason will be displayed to describe this comment to others. Learn more.
Since there are new losses introduced, would be cool to have a code snippet here to guide people through training as well! Would add a lot of value to the release