#                🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨
#           This file was automatically generated from src/transformers/models/pp_doclayout_v4/modular_pp_doclayout_v4.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_pp_doclayout_v4.py file directly. One of our CI enforces this.
#                🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨
# Copyright 2026 The PaddlePaddle Team 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.

from huggingface_hub.dataclasses import strict

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


@auto_docstring(checkpoint="PaddlePaddle/PP-DocLayoutV4_safetensors")
@strict
class PPDocLayoutV4Config(PreTrainedConfig):
    r"""
    initializer_bias_prior_prob (`float`, *optional*):
        The prior probability used by the bias initializer to initialize biases for `enc_score_head` and `class_embed`.
        If `None`, it defaults to `1 / (num_labels + 1)`.
    freeze_backbone_batch_norms (`bool`, *optional*, defaults to `True`):
        Whether to freeze the batch normalization layers in the backbone.
    encoder_in_channels (`list`, *optional*, defaults to `[512, 1024, 2048]`):
        Multi level features input for encoder.
    feat_strides (`list[int]`, *optional*, defaults to `[8, 16, 32]`):
        Strides used in each feature map.
    encode_proj_layers (`list[int]`, *optional*, defaults to `[2]`):
        Indexes of the projected layers to be used in the encoder.
    positional_encoding_temperature (`int`, *optional*, defaults to 10000):
        The temperature parameter used to create the positional encodings.
    encoder_activation_function (`str`, *optional*, defaults to `"gelu"`):
        The non-linear activation function (function or string) in the encoder and pooler. If string, `"gelu"`,
        `"relu"`, `"silu"` and `"gelu_new"` are supported.
    eval_size (`tuple[int, int]`, *optional*):
        Height and width used to computes the effective height and width of the position embeddings after taking
        into account the stride. Must be left as `None` to reproduce the reference implementation, which computes the
        position embeddings dynamically.
    normalize_before (`bool`, *optional*, defaults to `False`):
        Determine whether to apply layer normalization in the transformer encoder layer before self-attention and
        feed-forward modules.
    hidden_expansion (`float`, *optional*, defaults to 1.0):
        Expansion ratio to enlarge the dimension size of RepVGGBlock and CSPRepLayer.
    num_queries (`int`, *optional*, defaults to 300):
        Number of object queries.
    decoder_in_channels (`list`, *optional*, defaults to `[256, 256, 256]`):
        Multi level features dimension for decoder
    decoder_ffn_dim (`int`, *optional*, defaults to 1024):
        Dimension of the "intermediate" (often named feed-forward) layer in decoder.
    num_feature_levels (`int`, *optional*, defaults to 3):
        The number of input feature levels.
    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_activation_function (`str`, *optional*, defaults to `"relu"`):
        The non-linear activation function (function or string) in the decoder. If string, `"gelu"`,
        `"relu"`, `"silu"` and `"gelu_new"` are supported.
    num_denoising (`int`, *optional*, defaults to 100):
        The total number of denoising tasks or queries to be used for contrastive denoising.
    anchor_image_size (`tuple[int, int]`, *optional*):
        Height and width of the input image used during evaluation to generate the bounding box anchors. If None, automatic generate anchor is applied.
    disable_custom_kernels (`bool`, *optional*, defaults to `True`):
        Whether to disable custom kernels.
    global_pointer_head_size (`int`, *optional*, defaults to 64):
        The size of the global pointer head.
    gp_dropout_value (`float`, *optional*, defaults to 0.1):
        The dropout probability in the global pointer head.
    hidden_size (`int`, *optional*, defaults to 256):
        Dimension of the decoder layers, excluding the hybrid encoder. Also readable as `d_model`, the name used by
        the RT-DETR lineage this model descends from.
    num_coords (`int`, *optional*, defaults to 10):
        Size of the box parameterization predicted by the bbox heads. PP-DocLayoutV4 regresses a four point
        quadrilateral encoded as `[center_x, center_y, dx1, dy1, dx2, dy2, dx3, dy3, dx4, dy4]` in sigmoid space,
        where the corner offsets are shifted by `+0.5`. Only `10` is supported.
    s2r_steps (`int`, *optional*, defaults to 3):
        Number of propagation steps used to approximate the transitive closure of the successor matrix.
    s2r_damping (`float`, *optional*, defaults to 0.5):
        Damping factor applied to every additional propagation step of the transitive closure.
    s2r_closure_weight_init (`float`, *optional*, defaults to 0.0):
        Initial value of the learnable gate that weights the closure term. Defaults to `0.0` so that an untrained
        fusion module is numerically identical to using the relative order logits alone.

    Examples:

    ```python
    >>> from transformers import PPDocLayoutV4Config, PPDocLayoutV4ForObjectDetection

    >>> # Initializing a PP-DocLayoutV4 configuration
    >>> configuration = PPDocLayoutV4Config()

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

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

    model_type = "pp_doclayout_v4"
    sub_configs_defaults = {
        "backbone_config": SubConfigSpec(
            config_class=AutoConfig,
            model_type="hgnet_v2",
            init_kwargs={
                # PP-DocLayoutV4 has no mask branch, so the stride 4 feature is never consumed and the
                # backbone only has to emit the last three stages.
                "return_idx": [1, 2, 3],
                "freeze_stem_only": True,
                "freeze_at": 0,
                "freeze_norm": True,
                "lr_mult_list": [0, 0.05, 0.05, 0.05, 0.05],
                "out_features": ["stage2", "stage3", "stage4"],
            },
        ),
    }

    # PP-DocLayoutV3 declares `d_model` and aliases `hidden_size` onto it; PP-DocLayoutV4 does the reverse so
    # that the canonical name is the one the rest of the library expects.
    attribute_map = {
        "d_model": "hidden_size",
        "num_attention_heads": "encoder_attention_heads",
    }

    initializer_range: float = 0.01
    initializer_bias_prior_prob: float | None = None
    layer_norm_eps: float = 1e-5
    batch_norm_eps: float = 1e-5
    tie_word_embeddings: bool = True
    backbone_config: dict | PreTrainedConfig | None = None
    freeze_backbone_batch_norms: bool = True
    encoder_hidden_dim: int = 256
    encoder_in_channels: list[int] | tuple[int, ...] = (512, 1024, 2048)
    feat_strides: list[int] | tuple[int, ...] = (8, 16, 32)
    encoder_layers: int = 1
    encoder_ffn_dim: int = 1024
    encoder_attention_heads: int = 8
    dropout: float | int = 0.0
    activation_dropout: float | int = 0.0
    encode_proj_layers: list[int] | tuple[int, ...] = (2,)
    positional_encoding_temperature: int = 10000
    encoder_activation_function: str = "gelu"
    activation_function: str = "silu"
    eval_size: list[int] | tuple[int, int] | None = None
    normalize_before: bool = False
    hidden_expansion: float = 1.0
    num_queries: int = 300
    decoder_in_channels: list[int] | tuple[int, ...] = (256, 256, 256)
    decoder_ffn_dim: int = 1024
    num_feature_levels: int = 3
    decoder_n_points: int = 4
    decoder_layers: int = 6
    decoder_attention_heads: int = 8
    decoder_activation_function: str = "relu"
    attention_dropout: float | int = 0.0
    num_denoising: int = 100
    anchor_image_size: list[int] | tuple[int, int] | None = None
    disable_custom_kernels: bool = True
    is_encoder_decoder: bool = True
    global_pointer_head_size: int = 64
    gp_dropout_value: float | int = 0.1

    hidden_size: int = 256
    num_coords: int = 10
    s2r_steps: int = 3
    s2r_damping: float = 0.5
    s2r_closure_weight_init: float = 0.0

    def __post_init__(self, **kwargs):
        super().__post_init__(**kwargs)

        # Resolved here rather than in `_init_weights` so that the effective prior is visible on the config.
        # `num_labels` is only materialized by `PreTrainedConfig.__post_init__`, hence the ordering.
        if self.initializer_bias_prior_prob is None:
            self.initializer_bias_prior_prob = 1 / (self.num_labels + 1)

    def validate_architecture(self):
        """Part of `@strict`-powered validation. Validates the architecture of the config."""
        if self.num_coords != 10:
            raise ValueError(f"PP-DocLayoutV4 only supports `num_coords=10`, got {self.num_coords}.")


__all__ = ["PPDocLayoutV4Config"]
