# Copyright 2022 SenseTime and The HuggingFace Inc. 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.
"""Deformable DETR model configuration"""

from huggingface_hub.dataclasses import strict

from ...configuration_utils import PreTrainedConfig, SubConfigSpec
from ...utils import auto_docstring
from ..auto import AutoConfig


@auto_docstring(checkpoint="SenseTime/deformable-detr")
@strict
class DeformableDetrConfig(PreTrainedConfig):
    r"""
    num_queries (`int`, *optional*, defaults to 300):
        Number of object queries, i.e. detection slots. This is the maximal number of objects
        [`DeformableDetrModel`] can detect in a single image. In case `two_stage` is set to `True`, we use
        `two_stage_num_proposals` instead.
    return_intermediate (`bool`, *optional*, defaults to True):
        Whether to return the intermediate state or not
    position_embedding_type (`str`, *optional*, defaults to `"sine"`):
        Type of position embeddings to be used on top of the image features. One of `"sine"` or `"learned"`.
    dilation (`bool`, *optional*, defaults to `False`):
        Whether to replace stride with dilation in the last convolutional block (DC5). Only supported when
        `use_timm_backbone` = `True`.
    num_feature_levels (`int`, *optional*, defaults to 4):
        The number of input feature levels.
    encoder_n_points (`int`, *optional*, defaults to 4):
        The number of sampled keys in each feature level for each attention head in the encoder.
    decoder_n_points (`int`, *optional*, defaults to 4):
        The number of sampled keys in each feature level for each attention head in the decoder.
    two_stage (`bool`, *optional*, defaults to `False`):
        Whether to apply a two-stage deformable DETR, where the region proposals are also generated by a variant of
        Deformable DETR, which are further fed into the decoder for iterative bounding box refinement.
    two_stage_num_proposals (`int`, *optional*, defaults to 300):
        The number of region proposals to be generated, in case `two_stage` is set to `True`.
    with_box_refine (`bool`, *optional*, defaults to `False`):
        Whether to apply iterative bounding box refinement, where each decoder layer refines the bounding boxes
        based on the predictions from the previous layer.
    disable_custom_kernels (`bool`, *optional*, defaults to `False`):
        Disable the use of custom CUDA and CPU kernels. This option is necessary for the ONNX export, as custom
        kernels are not supported by PyTorch ONNX export.

    Examples:

    ```python
    >>> from transformers import DeformableDetrConfig, DeformableDetrModel

    >>> # Initializing a Deformable DETR SenseTime/deformable-detr style configuration
    >>> configuration = DeformableDetrConfig()

    >>> # Initializing a model (with random weights) from the SenseTime/deformable-detr style configuration
    >>> model = DeformableDetrModel(configuration)

    >>> # Accessing the model configuration
    >>> configuration = model.config
    ```"""

    model_type = "deformable_detr"
    sub_configs_defaults = {
        "backbone_config": SubConfigSpec(
            config_class=AutoConfig,
            model_type="resnet",
            init_kwargs={"out_features": ["stage4"]},
        ),
    }
    attribute_map = {
        "hidden_size": "d_model",
        "num_attention_heads": "encoder_attention_heads",
    }

    backbone_config: dict | PreTrainedConfig | None = None
    num_channels: int = 3
    num_queries: int = 300
    max_position_embeddings: int = 1024
    encoder_layers: int = 6
    encoder_ffn_dim: int = 1024
    encoder_attention_heads: int = 8
    decoder_layers: int = 6
    decoder_ffn_dim: int = 1024
    decoder_attention_heads: int = 8
    encoder_layerdrop: float | int = 0.0
    is_encoder_decoder: bool = True
    activation_function: str = "relu"
    d_model: int = 256
    dropout: float | int = 0.1
    attention_dropout: float | int = 0.0
    activation_dropout: float | int = 0.0
    init_std: float = 0.02
    init_xavier_std: float = 1.0
    return_intermediate: bool = True
    auxiliary_loss: bool = False
    position_embedding_type: str = "sine"
    dilation: bool = False
    num_feature_levels: int = 4
    encoder_n_points: int = 4
    decoder_n_points: int = 4
    two_stage: bool = False
    two_stage_num_proposals: int = 300
    with_box_refine: bool = False
    class_cost: int = 1
    bbox_cost: int = 5
    giou_cost: int = 2
    mask_loss_coefficient: int = 1
    dice_loss_coefficient: int = 1
    bbox_loss_coefficient: int = 5
    giou_loss_coefficient: int = 2
    eos_coefficient: float = 0.1
    focal_alpha: float = 0.25
    disable_custom_kernels: bool = False
    tie_word_embeddings: bool = True

    def __post_init__(self, **kwargs):
        # Init timm backbone with hardcoded values for BC
        if (
            self.backbone_config is None
            and kwargs.pop("use_timm_backbone", True)
            and not kwargs.get("backbone_kwargs")
        ):
            self.backbone_config = {
                "model_type": "timm_backbone",
                "backbone": kwargs.pop("backbone", None) or "resnet50",
                "num_channels": 3,
                "features_only": True,
                "use_pretrained_backbone": False,
                "out_indices": [2, 3, 4] if self.num_feature_levels > 1 else [4],
            }
            if self.dilation:
                self.backbone_config["output_stride"] = 16
        super().__post_init__(**kwargs)

    def validate_architecture(self):
        """Part of `@strict`-powered validation. Validates the architecture of the config."""
        if self.two_stage is True and self.with_box_refine is False:
            raise ValueError("If two_stage is True, with_box_refine must be True.")


__all__ = ["DeformableDetrConfig"]
