CoolFace
Apppublic

Aluode/PerceptionLabPortable

sourceHugging Faceupdated 9mo agoView on Hugging Face
0likes
configuration_t5gemma.py328 linesDownload Raw Back to t5gemma
1#                ๐Ÿšจ๐Ÿšจ๐Ÿšจ๐Ÿšจ๐Ÿšจ๐Ÿšจ๐Ÿšจ๐Ÿšจ๐Ÿšจ๐Ÿšจ๐Ÿšจ๐Ÿšจ๐Ÿšจ๐Ÿšจ๐Ÿšจ๐Ÿšจ๐Ÿšจ๐Ÿšจ๐Ÿšจ๐Ÿšจ๐Ÿšจ๐Ÿšจ๐Ÿšจ๐Ÿšจ๐Ÿšจ๐Ÿšจ๐Ÿšจ๐Ÿšจ๐Ÿšจ๐Ÿšจ๐Ÿšจ๐Ÿšจ๐Ÿšจ๐Ÿšจ๐Ÿšจ๐Ÿšจ๐Ÿšจ๐Ÿšจ๐Ÿšจ๐Ÿšจ๐Ÿšจ๐Ÿšจ๐Ÿšจ๐Ÿšจ๐Ÿšจ๐Ÿšจ๐Ÿšจ๐Ÿšจ2#           This file was automatically generated from src/transformers/models/t5gemma/modular_t5gemma.py.3#               Do NOT edit this file manually as any edits will be overwritten by the generation of4#             the file from the modular. If any change should be done, please apply the change to the5#                          modular_t5gemma.py file directly. One of our CI enforces this.6#                ๐Ÿšจ๐Ÿšจ๐Ÿšจ๐Ÿšจ๐Ÿšจ๐Ÿšจ๐Ÿšจ๐Ÿšจ๐Ÿšจ๐Ÿšจ๐Ÿšจ๐Ÿšจ๐Ÿšจ๐Ÿšจ๐Ÿšจ๐Ÿšจ๐Ÿšจ๐Ÿšจ๐Ÿšจ๐Ÿšจ๐Ÿšจ๐Ÿšจ๐Ÿšจ๐Ÿšจ๐Ÿšจ๐Ÿšจ๐Ÿšจ๐Ÿšจ๐Ÿšจ๐Ÿšจ๐Ÿšจ๐Ÿšจ๐Ÿšจ๐Ÿšจ๐Ÿšจ๐Ÿšจ๐Ÿšจ๐Ÿšจ๐Ÿšจ๐Ÿšจ๐Ÿšจ๐Ÿšจ๐Ÿšจ๐Ÿšจ๐Ÿšจ๐Ÿšจ๐Ÿšจ๐Ÿšจ7# coding=utf-88# Copyright 2025 Google Inc. HuggingFace Inc. team. All rights reserved.9#10#11# Licensed under the Apache License, Version 2.0 (the "License");12# you may not use this file except in compliance with the License.13# You may obtain a copy of the License at14#15#     http://www.apache.org/licenses/LICENSE-2.016#17# Unless required by applicable law or agreed to in writing, software18# distributed under the License is distributed on an "AS IS" BASIS,19# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.20# See the License for the specific language governing permissions and21# limitations under the License.22from typing import Any, Optional, Union23 24from ...configuration_utils import PretrainedConfig, layer_type_validation25 26 27class T5GemmaModuleConfig(PretrainedConfig):28    r"""29    This is the configuration class to store the configuration of a [`T5GemmaModuleModel`]. It is used to instantiate an T5GemmaModule30    model according to the specified arguments, defining the model architecture. Instantiating a configuration with the31    defaults will yield a similar configuration to that of the T5GemmaModule-7B.32    e.g. [google/t5_gemma_module-7b](https://huggingface.co/google/t5_gemma_module-7b)33    Configuration objects inherit from [`PretrainedConfig`] and can be used to control the model outputs. Read the34    documentation from [`PretrainedConfig`] for more information.35    Args:36        vocab_size (`int`, *optional*, defaults to 256000):37            Vocabulary size of the T5GemmaModule model. Defines the number of different tokens that can be represented by the38            `inputs_ids` passed when calling [`T5GemmaModuleModel`]39        hidden_size (`int`, *optional*, defaults to 2304):40            Dimension of the hidden representations.41        intermediate_size (`int`, *optional*, defaults to 9216):42            Dimension of the MLP representations.43        num_hidden_layers (`int`, *optional*, defaults to 26):44            Number of hidden layers in the Transformer decoder.45        num_attention_heads (`int`, *optional*, defaults to 8):46            Number of attention heads for each attention layer in the Transformer decoder.47        num_key_value_heads (`int`, *optional*, defaults to 4):48            This is the number of key_value heads that should be used to implement Grouped Query Attention. If49            `num_key_value_heads=num_attention_heads`, the model will use Multi Head Attention (MHA), if50            `num_key_value_heads=1` the model will use Multi Query Attention (MQA) otherwise GQA is used. When51            converting a multi-head checkpoint to a GQA checkpoint, each group key and value head should be constructed52            by meanpooling all the original heads within that group. For more details, check out [this53            paper](https://huggingface.co/papers/2305.13245). If it is not specified, will default to54            `num_attention_heads`.55        head_dim (`int`, *optional*, defaults to 256):56            The attention head dimension.57        hidden_activation (`str` or `function`, *optional*, defaults to `"gelu_pytorch_tanh"`):58            The non-linear activation function (function or string) in the decoder. Will default to `"gelu_pytorch_tanh"`59            if not specified. `"gelu_pytorch_tanh"` uses an approximation of the `"gelu"` activation function.60        max_position_embeddings (`int`, *optional*, defaults to 8192):61            The maximum sequence length that this model might ever be used with.62        initializer_range (`float`, *optional*, defaults to 0.02):63            The standard deviation of the truncated_normal_initializer for initializing all weight matrices.64        rms_norm_eps (`float`, *optional*, defaults to 1e-06):65            The epsilon used by the rms normalization layers.66        use_cache (`bool`, *optional*, defaults to `True`):67            Whether or not the model should return the last key/values attentions (not used by all models). Only68            relevant if `config.is_decoder=True`.69        pad_token_id (`int`, *optional*, defaults to 0):70            Padding token id.71        eos_token_id (`int`, *optional*, defaults to 1):72            End of stream token id.73        bos_token_id (`int`, *optional*, defaults to 2):74            Beginning of stream token id.75        tie_word_embeddings (`bool`, *optional*, defaults to `True`):76            Whether to tie weight embeddings77        rope_theta (`float`, *optional*, defaults to 10000.0):78            The base period of the RoPE embeddings.79        attention_bias (`bool`, defaults to `False`, *optional*, defaults to `False`):80            Whether to use a bias in the query, key, value and output projection layers during self-attention.81        attention_dropout (`float`, *optional*, defaults to 0.0):82            The dropout ratio for the attention probabilities.83        query_pre_attn_scalar (`float`, *optional*, defaults to 256):84            scaling factor used on the attention scores85        sliding_window (`int`, *optional*, defaults to 4096):86            in T5GemmaModule, every other layer uses sliding window attention. This is the size of the sliding window.87        layer_types (`list`, *optional*):88            Attention pattern for each layer.89        final_logit_softcapping (`float`, *optional*, defaults to 30.0):90            scaling factor when applying tanh softcapping on the logits.91        attn_logit_softcapping (`float`, *optional*, defaults to 50.0):92            scaling factor when applying tanh softcapping on the attention scores.93 94    ```python95    >>> from transformers import T5GemmaModuleModel, T5GemmaModuleConfig96    >>> # Initializing a T5GemmaModule t5_gemma_module-7b style configuration97    >>> configuration = T5GemmaModuleConfig()98    >>> # Initializing a model from the t5_gemma_module-7b style configuration99    >>> model = T5GemmaModuleModel(configuration)100    >>> # Accessing the model configuration101    >>> configuration = model.config102    ```"""103 104    model_type = "t5_gemma_module"105    keys_to_ignore_at_inference = ["past_key_values"]106    base_model_tp_plan = {107        "layers.*.self_attn.q_proj": "colwise",108        "layers.*.self_attn.k_proj": "colwise",109        "layers.*.self_attn.v_proj": "colwise",110        "layers.*.self_attn.o_proj": "rowwise",111        "layers.*.mlp.gate_proj": "colwise",112        "layers.*.mlp.up_proj": "colwise",113        "layers.*.mlp.down_proj": "rowwise",114    }115    base_model_pp_plan = {116        "embed_tokens": (["input_ids"], ["inputs_embeds"]),117        "layers": (["hidden_states", "attention_mask"], ["hidden_states"]),118        "norm": (["hidden_states"], ["hidden_states"]),119    }120 121    def __init__(122        self,123        vocab_size=256000,124        hidden_size=2304,125        intermediate_size=9216,126        num_hidden_layers=26,127        num_attention_heads=8,128        num_key_value_heads=4,129        head_dim=256,130        hidden_activation="gelu_pytorch_tanh",131        max_position_embeddings=8192,132        initializer_range=0.02,133        rms_norm_eps=1e-6,134        use_cache=True,135        pad_token_id=0,136        eos_token_id=1,137        bos_token_id=2,138        tie_word_embeddings=True,139        rope_theta=10000.0,140        attention_bias=False,141        attention_dropout=0.0,142        query_pre_attn_scalar=256,143        sliding_window=4096,144        layer_types=None,145        final_logit_softcapping=30.0,146        attn_logit_softcapping=50.0,147        **kwargs,148    ):149        super().__init__(150            pad_token_id=pad_token_id,151            bos_token_id=bos_token_id,152            eos_token_id=eos_token_id,153            tie_word_embeddings=tie_word_embeddings,154            **kwargs,155        )156        self.vocab_size = vocab_size157        self.max_position_embeddings = max_position_embeddings158        self.hidden_size = hidden_size159        self.intermediate_size = intermediate_size160        self.num_hidden_layers = num_hidden_layers161        self.num_attention_heads = num_attention_heads162        self.head_dim = head_dim163        self.num_key_value_heads = num_key_value_heads164        self.initializer_range = initializer_range165        self.rms_norm_eps = rms_norm_eps166        self.use_cache = use_cache167        self.rope_theta = rope_theta168        self.attention_bias = attention_bias169        self.attention_dropout = attention_dropout170        self.hidden_activation = hidden_activation171        self.query_pre_attn_scalar = query_pre_attn_scalar172        self.sliding_window = sliding_window173        self.final_logit_softcapping = final_logit_softcapping174        self.attn_logit_softcapping = attn_logit_softcapping175        self.layer_types = layer_types176 177        if self.layer_types is None:178            self.layer_types = [179                "sliding_attention" if bool((i + 1) % 2) else "full_attention" for i in range(self.num_hidden_layers)180            ]181        layer_type_validation(self.layer_types, self.num_hidden_layers)182 183 184class T5GemmaConfig(PretrainedConfig):185    r"""186    This is the configuration class to store the configuration of a [`T5GemmaModel`]. It is used to instantiate an T5Gemma187    model according to the specified arguments, defining the model architecture. Instantiating a configuration with the188    defaults will yield a similar configuration to a hypothetical balanced Gemma2 encoder-decoder model.189    e.g. [google/t5gemma-2b-2b-prefixlm-it](https://huggingface.co/google/t5gemma-2b-2b-prefixlm-it)190    ```python191    >>> from transformers import T5GemmaConfig, T5GemmaModel192    >>> t5gemma_config = T5GemmaConfig.from_pretrained("google/t5gemma-2b-2b-prefixlm-it")193    >>> model = T5GemmaModel(t5gemma_config)194    ```195    Configuration objects inherit from [PretrainedConfig] and can be used to control the model outputs. Read the196    documentation from [PretrainedConfig] for more information.197    Args:198        encoder (`Union[T5GemmaModuleConfig, dict]`, optional, *optional*):199            Configuration for the encoder.200        decoder (`Union[T5GemmaModuleConfig, dict]`, optional, *optional*):201            Configuration for the decoder.202        is_encoder_decoder (bool, optional, *optional*, defaults to `True`):203            Whether the model is used as an encoder/decoder or not.204        dropout_rate (`float`, *optional*, defaults to 0.0):205            The ratio for all dropout layers (following T5).206        classifier_dropout_rate (`float`, *optional*, defaults to 0.0):207            The dropout ratio for classifier (following T5).208        attention_dropout (`float`, *optional*, defaults to 0.0):209            The dropout ratio for attention.210        tie_word_embeddings (`bool`, *optional*, defaults to `True`):211            Whether tie input and output embeddings.212        vocab_size (`int`, *optional*, defaults to 256000):213            Vocabulary size of the T5Gemma model (the same as Gemma 2).214        kwargs (additional keyword arguments, optional, *optional*):215            Will be passed to the PretrainedConfig base class.216    """217 218    model_type = "t5gemma"219    keys_to_ignore_at_inference = ["past_key_values"]220    base_model_tp_plan = {221        # encoder222        "encoder.layers.*.self_attn.q_proj": "colwise",223        "encoder.layers.*.self_attn.k_proj": "colwise",224        "encoder.layers.*.self_attn.v_proj": "colwise",225        "encoder.layers.*.self_attn.o_proj": "rowwise",226        "encoder.layers.*.mlp.gate_proj": "colwise",227        "encoder.layers.*.mlp.up_proj": "colwise",228        "encoder.layers.*.mlp.down_proj": "rowwise",229        # decoder230        "decoder.layers.*.self_attn.q_proj": "colwise",231        "decoder.layers.*.self_attn.k_proj": "colwise",232        "decoder.layers.*.self_attn.v_proj": "colwise",233        "decoder.layers.*.self_attn.o_proj": "rowwise",234        "decoder.layers.*.cross_attn.q_proj": "colwise",235        "decoder.layers.*.cross_attn.k_proj": "colwise",236        "decoder.layers.*.cross_attn.v_proj": "colwise",237        "decoder.layers.*.cross_attn.o_proj": "rowwise",238        "decoder.layers.*.mlp.gate_proj": "colwise",239        "decoder.layers.*.mlp.up_proj": "colwise",240        "decoder.layers.*.mlp.down_proj": "rowwise",241    }242    base_model_pp_plan = {243        # encoder244        "encoder.embed_tokens": (["input_ids"], ["inputs_embeds"]),245        "encoder.layers": (["hidden_states", "attention_mask"], ["hidden_states"]),246        "encoder.norm": (["hidden_states"], ["hidden_states"]),247        # decoder248        "decoder.embed_tokens": (["input_ids"], ["inputs_embeds"]),249        "decoder.layers": (["hidden_states", "attention_mask"], ["hidden_states"]),250        "decoder.norm": (["hidden_states"], ["hidden_states"]),251    }252 253    def __init__(254        self,255        encoder: Optional[Union[T5GemmaModuleConfig, dict[Any, Any]]] = None,256        decoder: Optional[Union[T5GemmaModuleConfig, dict[Any, Any]]] = None,257        is_encoder_decoder: bool = True,258        dropout_rate: float = 0.0,259        classifier_dropout_rate: float = 0.0,260        attention_dropout: float = 0.0,261        tie_word_embeddings: bool = True,262        vocab_size: int = 256000,263        **kwargs,264    ):265        if isinstance(encoder, dict):266            encoder = T5GemmaModuleConfig(**encoder)267        elif encoder is None:268            encoder = T5GemmaModuleConfig()269        else:270            assert isinstance(encoder, T5GemmaModuleConfig), f"{type(encoder)} is not supported."271 272        if isinstance(decoder, dict):273            decoder = T5GemmaModuleConfig(**decoder)274        elif decoder is None:275            decoder = encoder276        else:277            assert isinstance(decoder, T5GemmaModuleConfig), f"{type(decoder)} is not supported."278 279        encoder = T5GemmaModuleConfig(**encoder.to_dict())280        decoder = T5GemmaModuleConfig(**decoder.to_dict())281 282        encoder.is_decoder = False283        encoder.dropout_rate = dropout_rate284        encoder.attention_dropout = attention_dropout285        self.encoder = encoder286 287        decoder.is_decoder = True288        decoder.use_cache = True289        decoder.dropout_rate = dropout_rate290        decoder.attention_dropout = attention_dropout291        decoder.cross_attention_hidden_size = encoder.hidden_size292        self.decoder = decoder293 294        for special_token_key in ["bos_token_id", "pad_token_id", "eos_token_id"]:295            if special_token_key not in kwargs:296                kwargs[special_token_key] = getattr(decoder, special_token_key)297 298        super().__init__(**kwargs)299 300        self.is_encoder_decoder = is_encoder_decoder301        self.use_cache = kwargs.get("use_cache", decoder.use_cache)302        self.initializer_range = kwargs.get("initializer_range", decoder.initializer_range)303        self.dropout_rate = dropout_rate304        self.attention_dropout = attention_dropout305        self.classifier_dropout_rate = classifier_dropout_rate306        self.tie_word_embeddings = tie_word_embeddings307 308        # Used in pipeline generation.309        self.vocab_size = vocab_size310 311    def __setattr__(self, key, value):312        shared_attr_with_submodules = [313            "output_hidden_states",314            "output_attentions",315            "_attn_implementation",316            "dropout_rate",317            "attention_dropout",318            "vocab_size",319        ]320 321        if key in shared_attr_with_submodules:322            setattr(self.encoder, key, value)323            setattr(self.decoder, key, value)324        super().__setattr__(key, value)325 326 327__all__ = ["T5GemmaConfig", "T5GemmaModuleConfig"]328