#                🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨
#           This file was automatically generated from src/transformers/models/granite_speech5/modular_granite_speech5.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_speech5.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
from ...utils import auto_docstring


@auto_docstring(checkpoint="ibm-granite/granite-speech-5.0-470m-turboctc")
@strict
class GraniteSpeech5EncoderConfig(PreTrainedConfig):
    r"""
    max_position_embeddings (`int`, *optional*, defaults to 512):
        Maximum relative position index of Shaw's relative positional encoding; the embedding table holds
        `2 * max_position_embeddings + 1` entries.
    context_size (`int`, *optional*, defaults to 128):
        Context size for block-wise conformer attention.
    conv_kernel_size (`int`, *optional*, defaults to 7):
        Kernel size of the depthwise convolution in the conformer convolution module.
    conv_expansion_factor (`int`, *optional*, defaults to 2):
        Expansion factor for the conformer convolution module.
    subsample_layers (`list[int]`, *optional*, defaults to `[0, 1]`):
        Indices of the conformer blocks that subsample time by 2 (stride-2 depthwise convolution with a
        mean-pooled residual).

    Example:

    ```python
    >>> from transformers import GraniteSpeech5EncoderConfig, GraniteSpeech5Encoder

    >>> # Initializing a GraniteSpeech5EncoderConfig
    >>> configuration = GraniteSpeech5EncoderConfig()

    >>> # Initializing a GraniteSpeech5Encoder (with random weights)
    >>> model = GraniteSpeech5Encoder(configuration)

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

    model_type = "granite_speech5_encoder"

    vocab_size: int = 16384
    hidden_size: int = 1024
    intermediate_size: int = 4096
    num_hidden_layers: int = 16
    num_attention_heads: int = 8
    num_key_value_heads: int | None = None
    num_mel_bins: int = 80
    head_dim: int | None = None
    hidden_act: str = "silu"
    max_position_embeddings: int = 512
    context_size: int = 128
    conv_kernel_size: int = 7
    conv_expansion_factor: int = 2
    subsample_layers: list[int] | None = None
    attention_bias: bool = True
    attention_dropout: float | int = 0.0
    activation_dropout: float | int = 0.0
    initializer_range: float = 0.02

    def __post_init__(self, **kwargs):
        super().__post_init__(**kwargs)
        if self.head_dim is None:
            self.head_dim = self.hidden_size // self.num_attention_heads
        if self.num_key_value_heads is None:
            self.num_key_value_heads = self.num_attention_heads
        if self.subsample_layers is None:
            self.subsample_layers = [0, 1]
        if self.context_size <= 0 or self.context_size > self.max_position_embeddings:
            raise ValueError(
                f"`context_size` must be in (0, max_position_embeddings={self.max_position_embeddings}], "
                f"got {self.context_size}."
            )


@auto_docstring(checkpoint="ibm-granite/granite-speech-5.0-470m-turboctc")
@strict
class GraniteSpeech5CTCConfig(PreTrainedConfig):
    r"""
    ctc_loss_reduction (`str`, *optional*, defaults to `"mean"`):
        Specifies the reduction to apply to the output of `torch.nn.CTCLoss`. Only relevant when training an
        instance of [`GraniteSpeech5ForCTC`].
    ctc_zero_infinity (`bool`, *optional*, defaults to `True`):
        Whether to zero infinite losses and the associated gradients of `torch.nn.CTCLoss`. Infinite losses mainly
        occur when the inputs are too short to be aligned to the targets. Only relevant when training an instance
        of [`GraniteSpeech5ForCTC`].
    encoder_config (`Union[dict, GraniteSpeech5EncoderConfig]`, *optional*):
        The config object or dictionary of the encoder.

    Example:

    ```python
    >>> from transformers import GraniteSpeech5ForCTC, GraniteSpeech5CTCConfig
    >>> # Initializing a GraniteSpeech5 configuration
    >>> configuration = GraniteSpeech5CTCConfig()
    >>> # Initializing a model from the configuration
    >>> model = GraniteSpeech5ForCTC(configuration)
    >>> # Accessing the model configuration
    >>> configuration = model.config
    ```
    """

    model_type = "granite_speech5_ctc"
    sub_configs = {"encoder_config": GraniteSpeech5EncoderConfig}

    vocab_size: int = 16384
    ctc_loss_reduction: str = "mean"
    ctc_zero_infinity: bool = True
    encoder_config: dict | PreTrainedConfig | None = None
    pad_token_id: int | None = 0
    # controls the tying of `ctc_head` to the encoder's (self-conditioning) CTC head `out`
    tie_word_embeddings: bool = True

    def __post_init__(self, **kwargs):
        if isinstance(self.encoder_config, dict):
            self.encoder_config = GraniteSpeech5EncoderConfig(**self.encoder_config)
        elif self.encoder_config is None:
            self.encoder_config = GraniteSpeech5EncoderConfig()
        self.initializer_range = self.encoder_config.initializer_range
        super().__post_init__(**kwargs)

    def validate_architecture(self):
        if self.encoder_config.vocab_size != self.vocab_size:
            raise ValueError(
                f"The encoder config vocabulary size ({self.encoder_config.vocab_size}) does not match the CTC "
                f"config vocabulary size ({self.vocab_size})."
            )


__all__ = ["GraniteSpeech5CTCConfig", "GraniteSpeech5EncoderConfig"]
