CoolFace
Apppublic

Aluode/PerceptionLabPortable

sourceHugging Faceupdated 9mo agoView on Hugging Face
0likes
configuration_ernie4_5.py203 linesDownload Raw Back to ernie4_5
1# Copyright (c) 2025 Baidu, Inc. and HuggingFace Inc. team. All Rights Reserved.2#3# Licensed under the Apache License, Version 2.0 (the "License");4# you may not use this file except in compliance with the License.5# You may obtain a copy of the License at6#7#     http://www.apache.org/licenses/LICENSE-2.08#9# Unless required by applicable law or agreed to in writing, software10# distributed under the License is distributed on an "AS IS" BASIS,11# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.12# See the License for the specific language governing permissions and13# limitations under the License.14"""Ernie 4.5 model configuration"""15 16from ...configuration_utils import PretrainedConfig17from ...modeling_rope_utils import rope_config_validation18 19 20class Ernie4_5Config(PretrainedConfig):21    r"""22    This is the configuration class to store the configuration of a [`Ernie4_5Model`]. It is used to instantiate an Ernie 4.523    model according to the specified arguments, defining the model architecture. Instantiating a configuration with the24    defaults will yield a similar configuration to that of the Ernie 4.5 0.3B.25    e.g. [baidu/ERNIE-4.5-0.3B-PT](https://huggingface.co/baidu/ERNIE-4.5-0.3B-PT)26 27    Configuration objects inherit from [`PretrainedConfig`] and can be used to control the model outputs. Read the28    documentation from [`PretrainedConfig`] for more information.29 30 31    Args:32        vocab_size (`int`, *optional*, defaults to 103424):33            Vocabulary size of the Ernie 4.5 model. Defines the number of different tokens that can be represented by the34            `inputs_ids` passed when calling [`Ernie4_5Model`]35        hidden_size (`int`, *optional*, defaults to 1024):36            Dimension of the hidden representations.37        intermediate_size (`int`, *optional*, defaults to 3072):38            Dimension of the MLP representations.39        num_hidden_layers (`int`, *optional*, defaults to 18):40            Number of hidden layers in the Transformer decoder.41        num_attention_heads (`int`, *optional*, defaults to 16):42            Number of attention heads for each attention layer in the Transformer decoder.43        num_key_value_heads (`int`, *optional*, defaults to 2):44            This is the number of key_value heads that should be used to implement Grouped Query Attention. If45            `num_key_value_heads=num_attention_heads`, the model will use Multi Head Attention (MHA), if46            `num_key_value_heads=1` the model will use Multi Query Attention (MQA) otherwise GQA is used. When47            converting a multi-head checkpoint to a GQA checkpoint, each group key and value head should be constructed48            by meanpooling all the original heads within that group. For more details, check out [this49            paper](https://huggingface.co/papers/2305.13245). If it is not specified, will default to50            `num_attention_heads`.51        hidden_act (`str` or `function`, *optional*, defaults to `"silu"`):52            The non-linear activation function (function or string) in the decoder.53        max_position_embeddings (`int`, *optional*, defaults to 131072):54            The maximum sequence length that this model might ever be used with.55        initializer_range (`float`, *optional*, defaults to 0.02):56            The standard deviation of the truncated_normal_initializer for initializing all weight matrices.57        rms_norm_eps (`float`, *optional*, defaults to 1e-05):58            The epsilon used by the rms normalization layers.59        use_cache (`bool`, *optional*, defaults to `True`):60            Whether or not the model should return the last key/values attentions.61        pad_token_id (`int`, *optional*, defaults to 0):62            Padding token id.63        bos_token_id (`int`, *optional*, defaults to 1):64            Beginning of stream token id.65        eos_token_id (`int`, *optional*, defaults to 2):66            End of stream token id.67        tie_word_embeddings (`bool`, *optional*, defaults to `True`):68            Whether to tie weight embeddings69        rope_theta (`float`, *optional*, defaults to 500000.0):70            The base period of the RoPE embeddings.71        rope_scaling (`Dict`, *optional*):72            Dictionary containing the scaling configuration for the RoPE embeddings. NOTE: if you apply new rope type73            and you expect the model to work on longer `max_position_embeddings`, we recommend you to update this value74            accordingly.75            Expected contents:76                `rope_type` (`str`):77                    The sub-variant of RoPE to use. Can be one of ['default', 'linear', 'dynamic', 'yarn', 'longrope',78                    'llama3'], with 'default' being the original RoPE implementation.79                `factor` (`float`, *optional*):80                    Used with all rope types except 'default'. The scaling factor to apply to the RoPE embeddings. In81                    most scaling types, a `factor` of x will enable the model to handle sequences of length x *82                    original maximum pre-trained length.83                `original_max_position_embeddings` (`int`, *optional*):84                    Used with 'dynamic', 'longrope' and 'llama3'. The original max position embeddings used during85                    pretraining.86                `attention_factor` (`float`, *optional*):87                    Used with 'yarn' and 'longrope'. The scaling factor to be applied on the attention88                    computation. If unspecified, it defaults to value recommended by the implementation, using the89                    `factor` field to infer the suggested value.90                `beta_fast` (`float`, *optional*):91                    Only used with 'yarn'. Parameter to set the boundary for extrapolation (only) in the linear92                    ramp function. If unspecified, it defaults to 32.93                `beta_slow` (`float`, *optional*):94                    Only used with 'yarn'. Parameter to set the boundary for interpolation (only) in the linear95                    ramp function. If unspecified, it defaults to 1.96                `short_factor` (`list[float]`, *optional*):97                    Only used with 'longrope'. The scaling factor to be applied to short contexts (<98                    `original_max_position_embeddings`). Must be a list of numbers with the same length as the hidden99                    size divided by the number of attention heads divided by 2100                `long_factor` (`list[float]`, *optional*):101                    Only used with 'longrope'. The scaling factor to be applied to long contexts (<102                    `original_max_position_embeddings`). Must be a list of numbers with the same length as the hidden103                    size divided by the number of attention heads divided by 2104                `low_freq_factor` (`float`, *optional*):105                    Only used with 'llama3'. Scaling factor applied to low frequency components of the RoPE106                `high_freq_factor` (`float`, *optional*):107                    Only used with 'llama3'. Scaling factor applied to high frequency components of the RoPE108        use_bias (`bool`, *optional*, defaults to `False`):109            Whether to use a bias in any of the projections including mlp and attention for example.110        head_dim (`int`, *optional*, defaults to 128):111            The attention head dimension. If None, it will default to hidden_size // num_attention_heads112 113    ```python114    >>> from transformers import Ernie4_5Model, Ernie4_5Config115 116    >>> # Initializing a Ernie4_5 0.3B style configuration117    >>> configuration = Ernie4_5Config()118 119    >>> # Initializing a model from the 0.3B style configuration120    >>> model = Ernie4_5Model(configuration)121 122    >>> # Accessing the model configuration123    >>> configuration = model.config124    ```"""125 126    model_type = "ernie4_5"127    keys_to_ignore_at_inference = ["past_key_values"]128    # Default tensor parallel plan for base model `Ernie4_5Model`129    base_model_tp_plan = {130        "layers.*.self_attn.q_proj": "colwise",131        "layers.*.self_attn.k_proj": "colwise",132        "layers.*.self_attn.v_proj": "colwise",133        "layers.*.self_attn.o_proj": "rowwise",134        "layers.*.mlp.gate_proj": "colwise",135        "layers.*.mlp.up_proj": "colwise",136        "layers.*.mlp.down_proj": "rowwise",137    }138    base_model_pp_plan = {139        "embed_tokens": (["input_ids"], ["inputs_embeds"]),140        "layers": (["hidden_states", "attention_mask"], ["hidden_states"]),141        "norm": (["hidden_states"], ["hidden_states"]),142    }143 144    def __init__(145        self,146        vocab_size=103424,147        hidden_size=1024,148        intermediate_size=3072,149        num_hidden_layers=18,150        num_attention_heads=16,151        num_key_value_heads=2,152        hidden_act="silu",153        max_position_embeddings=131072,154        initializer_range=0.02,155        rms_norm_eps=1e-05,156        use_cache=True,157        pad_token_id=0,158        bos_token_id=1,159        eos_token_id=2,160        tie_word_embeddings=True,161        rope_theta=500000.0,162        rope_scaling=None,163        use_bias=False,164        head_dim=128,165        **kwargs,166    ):167        self.vocab_size = vocab_size168        self.max_position_embeddings = max_position_embeddings169        self.hidden_size = hidden_size170        self.intermediate_size = intermediate_size171        self.num_hidden_layers = num_hidden_layers172        self.num_attention_heads = num_attention_heads173 174        # for backward compatibility175        if num_key_value_heads is None:176            num_key_value_heads = num_attention_heads177 178        self.num_key_value_heads = num_key_value_heads179        self.hidden_act = hidden_act180        self.initializer_range = initializer_range181        self.rms_norm_eps = rms_norm_eps182        self.use_cache = use_cache183        self.rope_theta = rope_theta184        self.rope_scaling = rope_scaling185        self.use_bias = use_bias186        self.head_dim = head_dim if head_dim is not None else self.hidden_size // self.num_attention_heads187        # Validate the correctness of rotary position embeddings parameters188        # BC: if there is a 'type' field, copy it it to 'rope_type'.189        if self.rope_scaling is not None and "type" in self.rope_scaling:190            self.rope_scaling["rope_type"] = self.rope_scaling["type"]191        rope_config_validation(self)192 193        super().__init__(194            pad_token_id=pad_token_id,195            bos_token_id=bos_token_id,196            eos_token_id=eos_token_id,197            tie_word_embeddings=tie_word_embeddings,198            **kwargs,199        )200 201 202__all__ = ["Ernie4_5Config"]203 
Aluode/PerceptionLabPortable · CoolFace