#                🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨
#           This file was automatically generated from src/transformers/models/mm_grounding_dino/modular_mm_grounding_dino.py.
#               Do NOT edit this file manually as any edits will be overwritten by the generation of
#             the file from the modular. If any change should be done, please apply the change to the
#                          modular_mm_grounding_dino.py file directly. One of our CI enforces this.
#                🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨
# Copyright 2025 The HuggingFace Inc. team.
#
# 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.
from huggingface_hub.dataclasses import strict

from ...backbone_utils import consolidate_backbone_kwargs_to_config
from ...configuration_utils import PreTrainedConfig
from ...utils import auto_docstring, logging
from ..auto import CONFIG_MAPPING, AutoConfig


logger = logging.get_logger(__name__)


@auto_docstring(checkpoint="openmmlab-community/mm_grounding_dino_tiny_o365v1_goldg_v3det")
@strict
class MMGroundingDinoConfig(PreTrainedConfig):
    r"""
    num_queries (`int`, *optional*, defaults to 900):
        Number of object queries, i.e. detection slots. This is the maximal number of objects
        [`MMGroundingDinoModel`] can detect in a single image.
    auxiliary_loss (`bool`, *optional*, defaults to `False`):
        Whether auxiliary decoding losses (loss at each decoder layer) are to be used.
    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"`.
    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 `True`):
        Whether to apply a two-stage deformable DETR, where the region proposals are also generated by a variant of
        Grounding DINO, which are further fed into the decoder for iterative bounding box refinement.
    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.
    max_text_len (`int`, *optional*, defaults to 256):
        The maximum length of the text input.
    text_enhancer_dropout (`float`, *optional*, defaults to 0.0):
        The dropout ratio for the text enhancer.
    fusion_droppath (`float`, *optional*, defaults to 0.1):
        The droppath ratio for the fusion module.
    fusion_dropout (`float`, *optional*, defaults to 0.0):
        The dropout ratio for the fusion module.
    embedding_init_target (`bool`, *optional*, defaults to `True`):
        Whether to initialize the target with Embedding weights.
    query_dim (`int`, *optional*, defaults to 4):
        The dimension of the query vector.
    positional_embedding_temperature (`float`, *optional*, defaults to 20):
        The temperature for Sine Positional Embedding that is used together with vision backbone.

    Examples:

    ```python
    >>> from transformers import MMGroundingDinoConfig, MMGroundingDinoModel

    >>> # Initializing a MM Grounding DINO configuration
    >>> configuration = MMGroundingDinoConfig()

    >>> # Initializing a model (with random weights) from the configuration
    >>> model = MMGroundingDinoModel(configuration)

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

    model_type = "mm-grounding-dino"
    sub_configs = {"backbone_config": AutoConfig, "text_config": AutoConfig}
    attribute_map = {
        "hidden_size": "d_model",
        "num_attention_heads": "encoder_attention_heads",
    }

    backbone_config: dict | PreTrainedConfig | None = None
    text_config: dict | PreTrainedConfig | None = None
    num_queries: int = 900
    encoder_layers: int = 6
    encoder_ffn_dim: int = 2048
    encoder_attention_heads: int = 8
    decoder_layers: int = 6
    decoder_ffn_dim: int = 2048
    decoder_attention_heads: int = 8
    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
    auxiliary_loss: bool = False
    position_embedding_type: str = "sine"
    num_feature_levels: int = 4
    encoder_n_points: int = 4
    decoder_n_points: int = 4
    two_stage: bool = True
    class_cost: float = 1.0
    bbox_cost: float = 5.0
    giou_cost: float = 2.0
    bbox_loss_coefficient: float = 5.0
    giou_loss_coefficient: float = 2.0
    focal_alpha: float = 0.25
    disable_custom_kernels: bool = False
    max_text_len: int = 256
    text_enhancer_dropout: float | int = 0.0
    fusion_droppath: float | int = 0.1
    fusion_dropout: float | int = 0.0
    embedding_init_target: bool = True
    query_dim: int = 4
    positional_embedding_temperature: int = 20
    init_std: float = 0.02
    layer_norm_eps: float = 1e-5
    tie_word_embeddings: bool = True

    def __post_init__(self, **kwargs):
        self.backbone_config, kwargs = consolidate_backbone_kwargs_to_config(
            backbone_config=self.backbone_config,
            default_config_type="swin",
            default_config_kwargs={"out_indices": [2, 3, 4]},
            **kwargs,
        )

        # Text backbone
        if isinstance(self.text_config, dict):
            self.text_config["model_type"] = self.text_config.get("model_type", "bert")
            self.text_config = CONFIG_MAPPING[self.text_config["model_type"]](**self.text_config)
        elif self.text_config is None:
            logger.info("text_config is None. Initializing the text config with default values (`BertConfig`).")
            self.text_config = CONFIG_MAPPING["bert"]()

        super().__post_init__(**kwargs)


__all__ = ["MMGroundingDinoConfig"]
