#                🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨
#           This file was automatically generated from src/transformers/models/pp_doclayout_v2/modular_pp_doclayout_v2.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_v2.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 ...backbone_utils import consolidate_backbone_kwargs_to_config
from ...configuration_utils import PreTrainedConfig
from ...utils import auto_docstring
from ..auto import AutoConfig


@auto_docstring(checkpoint="PaddlePaddle/PP-DocLayoutV2_safetensors")
@strict
class PPDocLayoutV2ReadingOrderConfig(PreTrainedConfig):
    r"""
    has_relative_attention_bias (`bool`, *optional*, defaults to `True`):
        Whether or not to use a relative attention bias in the self-attention mechanism.
    has_spatial_attention_bias (`bool`, *optional*, defaults to `True`):
        Whether or not to use a spatial attention bias in the self-attention mechanism.
    rel_pos_bins (`int`, *optional*, defaults to 32):
        The number of relative position bins to be used in the self-attention mechanism.
    max_rel_pos (`int`, *optional*, defaults to 128):
        The maximum number of relative positions to be used in the self-attention mechanism.
    rel_2d_pos_bins (`int`, *optional*, defaults to 64):
        The number of 2D relative position bins in the self-attention mechanism.
    max_rel_2d_pos (`int`, *optional*, defaults to 256):
        The maximum number of relative 2D positions in the self-attention mechanism.
    max_2d_position_embeddings (`int`, *optional*, defaults to 1024):
        The maximum value that the 2D position embedding might ever be used with. Typically set this to something
        large just in case (e.g., 1024).
    start_token_id (`int`, *optional*, defaults to 0):
        Token id representing the start of a sequence.
    end_token_id (`int`, *optional*, defaults to 2):
        Token id representing the end of a sequence.
    pred_token_id (`int`, *optional*, defaults to 3):
        Token id representing valid prediction positions (placeholders) in the sequence.
    coordinate_size (`int`, *optional*, defaults to 171):
        Dimension of the coordinate embeddings.
    shape_size (`int`, *optional*, defaults to 170):
        Dimension of the width and height embeddings.
    num_classes (`int`, *optional*, defaults to 20):
        Number of labels or classes for the layout elements.
    relation_bias_embed_dim (`int`, *optional*, defaults to 16):
        Embedding dimension for the relation bias.
    relation_bias_theta (`float`, *optional*, defaults to 10000):
        Temperature parameter used for relation bias scaling.
    relation_bias_scale (`float`, *optional*, defaults to 100):
        Scale parameter for the relation bias.
    global_pointer_head_size (`int`, *optional*, defaults to 64):
        The size of the global pointer head.
    gp_dropout_value (`float`, *optional*, defaults to 0.0):
        The dropout probability in the global pointer head.
    """

    hidden_size: int = 512
    num_attention_heads: int = 8
    attention_probs_dropout_prob: float = 0.1
    has_relative_attention_bias: bool = False
    has_spatial_attention_bias: bool = True
    layer_norm_eps: float = 1e-5
    hidden_dropout_prob: float = 0.1
    intermediate_size: int = 2048
    hidden_act: str = "gelu"
    num_hidden_layers: int = 6
    rel_pos_bins: int = 32
    max_rel_pos: int = 128
    rel_2d_pos_bins: int = 64
    max_rel_2d_pos: int = 256
    max_position_embeddings: int = 514
    max_2d_position_embeddings: int = 1024
    type_vocab_size: int = 1
    vocab_size: int = 4
    initializer_range: float = 0.01
    start_token_id: int = 0
    pad_token_id: int | None = 1
    end_token_id: int = 2
    pred_token_id: int = 3
    coordinate_size: int = 171
    shape_size: int = 170
    num_classes: int = 20
    relation_bias_embed_dim: int = 16
    relation_bias_theta: int = 10000
    relation_bias_scale: int = 100
    global_pointer_head_size: int = 64
    gp_dropout_value: float = 0.0


@auto_docstring(checkpoint="PaddlePaddle/PP-DocLayoutV2_safetensors")
@strict
class PPDocLayoutV2Config(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`, `prior_prob` computed as `prior_prob = 1 / (num_labels + 1)` while initializing model weights.
    freeze_backbone_batch_norms (`bool`, *optional*, defaults to `True`):
        Whether to freeze the batch normalization layers in the backbone.
    encoder_hidden_dim (`int`, *optional*, defaults to 256):
        Dimension of the layers in hybrid encoder.
    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.
    encoder_layers (`int`, *optional*, defaults to 1):
        Total of layers to be used by the encoder.
    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.
    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.
    label_noise_ratio (`float`, *optional*, defaults to 0.5):
        The fraction of denoising labels to which random noise should be added.
    box_noise_scale (`float`, *optional*, defaults to 1.0):
        Scale or magnitude of noise to be added to the bounding boxes.
    learn_initial_query (`bool`, *optional*, defaults to `False`):
        Indicates whether the initial query embeddings for the decoder should be learned during training
    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.
    class_thresholds (`list[float]`, *optional*):
        The thresholds for each label.
    class_order (`list[int]`, *optional*):
        The priority for each label.
    reading_order_config (`dict`, *optional*):
        The configuration of a `PPDocLayoutV2ReadingOrder`.

    Examples:

    ```python
    >>> from transformers import PPDocLayoutV2Config, PPDocLayoutV2ForObjectDetection

    >>> # Initializing a PP-DocLayoutV2 configuration
    >>> configuration = PPDocLayoutV2Config()

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

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

    model_type = "pp_doclayout_v2"
    sub_configs = {"backbone_config": AutoConfig, "reading_order_config": PPDocLayoutV2ReadingOrderConfig}

    layer_types = ("basic", "bottleneck")
    attribute_map = {
        "hidden_size": "d_model",
        "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
    backbone_config: PreTrainedConfig | dict | None = None
    freeze_backbone_batch_norms: bool = True
    encoder_hidden_dim: int = 256
    encoder_in_channels: list[int] | tuple[int, ...] | None = (512, 1024, 2048)
    feat_strides: list[int] | tuple[int, ...] | None = (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, ...] | None = (2,)
    positional_encoding_temperature: int = 10000
    encoder_activation_function: str = "gelu"
    activation_function: str = "silu"
    eval_size: list[int] | None = None
    normalize_before: bool = False
    hidden_expansion: float = 1.0
    d_model: int = 256
    num_queries: int = 300
    decoder_in_channels: list[int] | tuple[int, ...] | None = (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
    label_noise_ratio: float = 0.5
    box_noise_scale: float = 1.0
    learn_initial_query: bool = False
    anchor_image_size: list[int] | None = None
    disable_custom_kernels: bool = True
    is_encoder_decoder: bool = True
    class_thresholds: list[float] | None = None
    class_order: list[int] | None = None
    reading_order_config: PreTrainedConfig | dict | None = None

    def __post_init__(self, **kwargs):
        if isinstance(self.reading_order_config, dict):
            self.reading_order_config = self.sub_configs["reading_order_config"](**self.reading_order_config)
        elif self.reading_order_config is None:
            self.reading_order_config = self.sub_configs["reading_order_config"]()

        self.backbone_config, kwargs = consolidate_backbone_kwargs_to_config(
            backbone_config=self.backbone_config,
            default_config_type="hgnet_v2",
            default_config_kwargs={
                "arch": "L",
                "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"],
            },
            **kwargs,
        )

        self.encoder_in_channels = list(self.encoder_in_channels)
        self.feat_strides = list(self.feat_strides)
        self.encode_proj_layers = list(self.encode_proj_layers)
        self.eval_size = list(self.eval_size) if self.eval_size is not None else None
        self.decoder_in_channels = list(self.decoder_in_channels)
        self.anchor_image_size = list(self.anchor_image_size) if self.anchor_image_size is not None else None

        super().__post_init__(**kwargs)


__all__ = ["PPDocLayoutV2Config"]
