#                🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨
#           This file was automatically generated from src/transformers/models/granite_docling/modular_granite_docling.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_granite_docling.py file directly. One of our CI enforces this.
#                🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨
# Copyright 2026 IBM and The HuggingFace 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 ...modeling_rope_utils import RopeParameters
from ...utils import auto_docstring


@auto_docstring(
    custom_intro="""
    Configuration of the SigLIP-style vision encoder that embeds every 512x512 tile of a page, and of the connector
    that turns its outputs into image tokens.
    """,
    checkpoint="ibm-granite/granite-for-docling-500m",
)
@strict
class GraniteDoclingVisionConfig(PreTrainedConfig):
    r"""
    out_hidden_size (`int`, *optional*, defaults to 1024):
        Hidden size of the text decoder that the connector projects to.
    scale_factor (`int`, *optional*, defaults to 4):
        Pixel shuffle factor of the connector. Each tile of `(image_size // patch_size) ** 2` vision tokens is
        reduced by `scale_factor ** 2`.
    deepstack_visual_indexes (`list[int]`, *optional*, defaults to `[3, 7, 10]`):
        Indices of the vision encoder layers whose output is projected by the DeepStack mergers. Index 0 is the
        output of the first layer.
    use_fine_route (`bool`, *optional*, defaults to `True`):
        Whether to build the fine connector path, which shuffles pixels by half of `scale_factor` and yields four
        times as many image tokens per tile. The 500M checkpoint has it, the 2B checkpoint does not.

    Example:

    ```python
    >>> from transformers import GraniteDoclingVisionConfig, GraniteDoclingVisionModel

    >>> # Initializing a GraniteDoclingVisionConfig with ibm-granite/granite-for-docling-500m style configuration
    >>> configuration = GraniteDoclingVisionConfig()

    >>> # Initializing a GraniteDoclingVisionModel (with random weights) from the ibm-granite/granite-for-docling-500m style configuration
    >>> model = GraniteDoclingVisionModel(configuration)

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

    model_type = "granite_docling_vision"
    base_config_key = "vision_config"

    hidden_size: int = 768
    intermediate_size: int = 3072
    num_hidden_layers: int = 12
    num_attention_heads: int = 12
    num_channels: int = 3
    image_size: int | list[int] | tuple[int, int] = 512
    patch_size: int | list[int] | tuple[int, int] = 16
    hidden_act: str = "gelu_pytorch_tanh"
    layer_norm_eps: float = 1e-6
    attention_dropout: float | int = 0.0
    initializer_range: float = 0.02
    out_hidden_size: int = 1024
    scale_factor: int = 4
    deepstack_visual_indexes: list[int] | None = None
    use_fine_route: bool = True

    def __post_init__(self, **kwargs):
        if self.deepstack_visual_indexes is None:
            self.deepstack_visual_indexes = [3, 7, 10]
        super().__post_init__(**kwargs)


@auto_docstring(checkpoint="ibm-granite/granite-for-docling-500m")
@strict
class GraniteDoclingTextConfig(PreTrainedConfig):
    r"""
    ```python
    >>> from transformers import GraniteDoclingTextModel, GraniteDoclingTextConfig

    >>> # Initializing a GraniteDoclingText granite_docling_text-3b style configuration
    >>> configuration = GraniteDoclingTextConfig()

    >>> # Initializing a model from the granite_docling_text-7b style configuration
    >>> model = GraniteDoclingTextModel(configuration)

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

    model_type = "granite_docling_text"
    keys_to_ignore_at_inference = ["past_key_values"]
    # Default tensor parallel plan for base model `GraniteDoclingTextModel`
    base_model_tp_plan = {
        "layers.*.self_attn.q_proj": "colwise",
        "layers.*.self_attn.k_proj": "colwise",
        "layers.*.self_attn.v_proj": "colwise",
        "layers.*.self_attn.o_proj": "rowwise",
        "layers.*.mlp.gate_proj": "colwise",
        "layers.*.mlp.up_proj": "colwise",
        "layers.*.mlp.down_proj": "rowwise",
    }
    base_model_pp_plan = {
        "embed_tokens": (["input_ids"], ["inputs_embeds"]),
        "layers": (["hidden_states", "attention_mask"], ["hidden_states"]),
        "norm": (["hidden_states"], ["hidden_states"]),
    }

    vocab_size: int = 133800
    hidden_size: int = 1024
    intermediate_size: int = 2048
    num_hidden_layers: int = 28
    num_attention_heads: int = 16
    num_key_value_heads: int | None = 4
    hidden_act: str = "silu"
    max_position_embeddings: int = 32768
    initializer_range: float = 0.02
    rms_norm_eps: float = 1e-5
    use_cache: bool = True
    pad_token_id: int | None = 100256
    bos_token_id: int | None = 100257
    eos_token_id: int | list[int] | None = 100257
    tie_word_embeddings: bool = True
    rope_parameters: RopeParameters | dict | None = None
    attention_bias: bool = False
    attention_dropout: float | int = 0.0
    mlp_bias: bool = False
    embedding_multiplier: float | int = 12.0
    logits_scaling: float | int = 4.0
    residual_multiplier: float | int = 0.263
    attention_multiplier: float | int = 0.015625
    base_config_key = "text_config"

    def __post_init__(self, **kwargs):
        if self.num_key_value_heads is None:
            self.num_key_value_heads = self.num_attention_heads

        super().__post_init__(**kwargs)


@auto_docstring(checkpoint="ibm-granite/granite-for-docling-500m")
@strict
class GraniteDoclingConfig(PreTrainedConfig):
    r"""
    density_router_hidden_size (`int`, *optional*):
        Hidden size of the density router, which predicts from the vision encoder features whether a page needs the
        fine connector path. No router is built when `None`.
    density_router_threshold (`float`, *optional*, defaults to 0.4):
        Probability above which the density router selects the fine connector path.
    density_router_loss_weight (`float`, *optional*, defaults to 0.1):
        Weight of the density router loss when `router_labels` are given.
    """

    model_type = "granite_docling"
    sub_configs_defaults = {
        "text_config": SubConfigSpec(config_class=GraniteDoclingTextConfig),
        "vision_config": SubConfigSpec(config_class=GraniteDoclingVisionConfig),
    }

    text_config: dict | PreTrainedConfig | None = None
    vision_config: dict | PreTrainedConfig | None = None
    image_token_id: int = 100337
    tie_word_embeddings: bool = True
    use_cache: bool = True
    pad_token_id: int | None = 100256
    density_router_hidden_size: int | None = None
    density_router_threshold: float = 0.4
    density_router_loss_weight: float = 0.1

    def validate_architecture(self):
        if self.vision_config.out_hidden_size != self.text_config.hidden_size:
            raise ValueError(
                f"vision_config.out_hidden_size ({self.vision_config.out_hidden_size}) must equal "
                f"text_config.hidden_size ({self.text_config.hidden_size})."
            )
        if self.density_router_hidden_size is not None and not self.vision_config.use_fine_route:
            raise ValueError(
                "The density router selects the fine connector path, it needs `vision_config.use_fine_route=True`."
            )


__all__ = ["GraniteDoclingConfig", "GraniteDoclingTextConfig", "GraniteDoclingVisionConfig"]
