#                🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨
#           This file was automatically generated from src/transformers/models/lw_detr/modular_lw_detr.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_lw_detr.py file directly. One of our CI enforces this.
#                🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨
# Copyright 2026 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.
import math

from huggingface_hub.dataclasses import strict

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


logger = logging.get_logger(__name__)


@auto_docstring(checkpoint="AnnaZhang/lwdetr_small_60e_coco")
@strict
class LwDetrViTConfig(BackboneConfigMixin, PreTrainedConfig):
    r"""
    pretrain_image_size (`int`, *optional*, defaults to 224):
        The size (resolution) of each image during pretraining.
    window_block_indices (`list[int]`, *optional*, defaults to `[]`):
        List of indices of blocks that should have window attention instead of regular global self-attention.
    use_absolute_position_embeddings (`bool`, *optional*, defaults to `True`):
        Whether to add absolute position embeddings to the patch embeddings.
    cae_init_values (`float`, *optional*, defaults to 0.1):
        Initialization value for CAE parameters when `use_cae` is enabled.
    num_windows (`int`, *optional*, defaults to 16):
        Number of windows for window-based attention. Must be a perfect square and the image size must be
        divisible by the square root of this value. This enables efficient window-major feature map organization.

    Example:

    ```python
    >>> from transformers import LwDetrViTConfig, LwDetrViTModel

    >>> # Initializing a LW-DETR ViT configuration
    >>> configuration = LwDetrViTConfig()

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

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

    model_type = "lw_detr_vit"

    hidden_size: int = 768
    num_hidden_layers: int = 12
    num_attention_heads: int = 12
    mlp_ratio: int = 4
    hidden_act: str = "gelu"
    dropout_prob: float | int = 0.0
    initializer_range: float = 0.02
    layer_norm_eps: float = 1e-6

    image_size: int | list[int] | tuple[int, int] = 256
    pretrain_image_size: int | list[int] | tuple[int, int] = 224
    patch_size: int | list[int] | tuple[int, int] = 16
    num_channels: int = 3
    qkv_bias: bool = True
    window_block_indices: list[int] | tuple[int, ...] = ()
    use_absolute_position_embeddings: bool = True
    _out_features: list[str] | None = None
    _out_indices: list[int] | None = None
    cae_init_values: float = 0.1
    num_windows: int = 16

    def __post_init__(self, **kwargs):
        self.num_windows_side = int(math.sqrt(self.num_windows))
        self.stage_names = ["stem"] + [f"stage{idx}" for idx in range(1, self.num_hidden_layers + 1)]
        self.set_output_features_output_indices(
            out_indices=kwargs.pop("out_indices", None), out_features=kwargs.pop("out_features", None)
        )
        super().__post_init__(**kwargs)

    def validate_architecture(self):
        """Part of `@strict`-powered validation. Validates the architecture of the config."""
        if self.num_windows % math.sqrt(self.num_windows) != 0:
            raise ValueError(
                f"`num_windows` has to be a perfect square, where num_windows % math.sqrt(num_windows) != 0, but got {self.num_windows}."
            )
        if self.image_size / self.num_windows % math.sqrt(self.num_windows) != 0:
            raise ValueError(
                f"`image_size` has to be divisible by `num_windows`, where image_size / num_windows % math.sqrt(num_windows) != 0,but got {self.image_size} and {self.num_windows}."
            )


@auto_docstring(checkpoint="AnnaZhang/lwdetr_small_60e_coco")
@strict
class LwDetrConfig(PreTrainedConfig):
    r"""
    projector_scale_factors (`list[float]`, *optional*, defaults to `[]`):
        Scale factors for the feature pyramid network. Each scale factor determines the resolution of features
        at different levels. Supported values are 0.5, 1.0, and 2.0.
    hidden_expansion (`float`, *optional*, defaults to 0.5):
        Expansion factor for hidden dimensions in the projector layers.
    c2f_num_blocks (`int`, *optional*, defaults to 3):
        Number of blocks in the C2F layer.
    activation_function (`str`, *optional*, defaults to `"silu"`):
        The non-linear activation function in the projector. Supported values are `"silu"`, `"relu"`, `"gelu"`.
    batch_norm_eps (`float`, *optional*, defaults to 1e-05):
        The epsilon value for batch normalization layers.
    decoder_ffn_dim (`int`, *optional*, defaults to 2048):
        Dimension of the "intermediate" (often named feed-forward) layer in decoder.
    decoder_n_points (`int`, *optional*, defaults to 4):
        The number of sampled keys in each feature level for each attention head in the decoder.
    decoder_self_attention_heads (`int`, *optional*, defaults to 8):
        Number of attention heads for each attention layer in the decoder self-attention.
    decoder_cross_attention_heads (`int`, *optional*, defaults to 16):
        Number of attention heads for each attention layer in the decoder cross-attention.
    decoder_activation_function (`str`, *optional*, defaults to `"relu"`):
        The non-linear activation function in the decoder. Supported values are `"relu"`, `"silu"`, `"gelu"`.
    num_queries (`int`, *optional*, defaults to 300):
        Number of object queries, i.e. detection slots. This is the maximal number of objects
        [`LwDetrModel`] can detect in a single image.
    group_detr (`int`, *optional*, defaults to 13):
        Number of groups for Group DETR attention mechanism, which helps reduce computational complexity.
    disable_custom_kernels (`bool`, *optional*, defaults to `True`):
        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.
    class_loss_coefficient (`float`, *optional*, defaults to 1):
        Relative weight of the classification loss in the Hungarian matching cost.

    Examples:

    ```python
    >>> from transformers import LwDetrConfig, LwDetrModel

    >>> # Initializing a LW-DETR AnnaZhang/lwdetr_small_60e_coco style configuration
    >>> configuration = LwDetrConfig()

    >>> # Initializing a model (with random weights) from the AnnaZhang/lwdetr_small_60e_coco style configuration
    >>> model = LwDetrModel(configuration)

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

    model_type = "lw_detr"
    sub_configs = {"backbone_config": AutoConfig}

    backbone_config: dict | PreTrainedConfig | None = None
    projector_scale_factors: list[float] | tuple[float, ...] = ()
    hidden_expansion: float = 0.5
    c2f_num_blocks: int = 3
    activation_function: str = "silu"
    batch_norm_eps: float = 1e-5
    dropout: float | int = 0.0
    decoder_ffn_dim: int = 2048
    decoder_n_points: int = 4
    decoder_layers: int = 3
    decoder_self_attention_heads: int = 8
    decoder_cross_attention_heads: int = 16
    decoder_activation_function: str = "relu"
    num_queries: int = 300
    attention_bias: bool = True
    attention_dropout: float | int = 0.0
    activation_dropout: float | int = 0.0
    group_detr: int = 13
    init_std: float = 0.02
    disable_custom_kernels: bool = True
    class_cost: int | float = 2
    bbox_cost: int | float = 5
    giou_cost: int | float = 2
    class_loss_coefficient: int | float = 1
    dice_loss_coefficient: int | float = 1
    bbox_loss_coefficient: int | float = 5
    giou_loss_coefficient: int | float = 2
    eos_coefficient: float = 0.1
    focal_alpha: float = 0.25
    auxiliary_loss: bool = True
    d_model: int = 256

    def __post_init__(self, **kwargs):
        if "mask_loss_coefficient" in kwargs:
            logger.warning_once(
                "The parameter `mask_loss_coefficient` was renamed to `class_loss_coefficient` in LW-DETR. "
                "Please use `class_loss_coefficient` instead. `mask_loss_coefficient` will be removed in a future version."
            )
            self.class_loss_coefficient = kwargs.pop("mask_loss_coefficient")

        self.backbone_config, kwargs = consolidate_backbone_kwargs_to_config(
            backbone_config=self.backbone_config,
            default_config_type="lw_detr_vit",
            default_config_kwargs={
                "image_size": 1024,
                "hidden_size": 192,
                "num_hidden_layers": 10,
                "window_block_indices": [0, 1, 3, 6, 7, 9],
                "out_indices": [2, 4, 5, 9],
            },
            **kwargs,
        )

        self.projector_in_channels = [self.d_model] * len(self.projector_scale_factors)
        self.projector_out_channels = self.d_model
        self.num_feature_levels = len(self.projector_scale_factors)
        super().__post_init__(**kwargs)

    def validate_architecture(self):
        """Part of `@strict`-powered validation. Validates the architecture of the config."""
        for scale in self.projector_scale_factors:
            if scale not in [0.5, 1.0, 2.0]:
                raise ValueError(f"Unsupported scale factor: {scale}")


__all__ = ["LwDetrConfig", "LwDetrViTConfig"]
