o
    پi06                     @   sR   d Z ddlmZ ddlmZ ddlmZmZ ee	Z
dZdZG dd deZd	S )
z$GraniteMoeHybrid model configuration    )PretrainedConfig)logging)Mamba2CacheParamsMamba2StateShapemamba	attentionc                       s   e Zd ZdZdZdgZ								
																													 	!	!			"d- fd#d$	Zed%d& Zed'd( Z	ed)d* Z
ed+d, Z  ZS ).GraniteMoeHybridConfiga/  
    This is the configuration class to store the configuration of a [`GraniteMoeHybridModel`]. It is used to instantiate a
    GraniteMoeHybrid model according to the specified arguments, defining the model architecture. The GraniteMoeHybrid is a
    hybrid architecture combining Mamba2 layers with attention layers, developed by IBM.

    Configuration objects inherit from [`PretrainedConfig`] and can be used to control the model outputs. Read the
    documentation from [`PretrainedConfig`] for more information.

    Args:
        vocab_size (`int`, *optional*, defaults to 100352):
            Vocabulary size of the GraniteMoeHybrid model. Defines the number of different tokens that can be represented by the
            `inputs_ids` passed when calling [`GraniteMoeHybridModel`]
        tie_word_embeddings (`bool`, *optional*, defaults to `True`):
            Whether the model's input and output word embeddings should be tied. Note that this is only relevant if the
            model has a output word embedding layer.
        hidden_size (`int`, *optional*, defaults to 2048):
            Dimension of the hidden representations.
        intermediate_size (`int`, *optional*, defaults to 8192):
            Dimension of the MLP representations.
        num_hidden_layers (`int`, *optional*, defaults to 40):
            Number of hidden layers in the model.
        layer_types (`list[str]`, *optional*):
            List of layer types for each layer. Each element should be either "mamba" or "attention".
            If not provided, defaults to alternating pattern based on num_hidden_layers.
        num_attention_heads (`int`, *optional*, defaults to 32):
            Number of attention heads for each attention layer.
        num_key_value_heads (`int`, *optional*, defaults to 8):
            This is the number of key_value heads that should be used to implement Grouped Query Attention. If
            `num_key_value_heads=num_attention_heads`, the model will use Multi Head Attention (MHA), if
            `num_key_value_heads=1` the model will use Multi Query Attention (MQA) otherwise GQA is used.
        hidden_act (`str` or `function`, *optional*, defaults to `"silu"`):
            The non-linear activation function (function or string) in the decoder.
        initializer_range (`float`, *optional*, defaults to 0.1):
            The standard deviation of the truncated_normal_initializer for initializing all weight matrices.
        rms_norm_eps (`float`, *optional*, defaults to 1e-05):
            The epsilon used by the rms normalization layers.
        normalization_function (`str`, *optional*, defaults to `"rmsnorm"`):
            The normalization function to use. Currently only "rmsnorm" is supported.
        use_cache (`bool`, *optional*, defaults to `True`):
            Whether or not the model should return the last key/values attentions (not used by all models). Only
            relevant if `config.is_decoder=True`.
        pad_token_id (`int`, *optional*, defaults to 100256):
            The id of the padding token.
        bos_token_id (`int`, *optional*, defaults to 100257):
            The id of the "beginning-of-sequence" token.
        eos_token_id (`int`, *optional*, defaults to 100257):
            The id of the "end-of-sequence" token.
        max_position_embeddings (`int`, *optional*, defaults to 131072):
            Max cached sequence length for the model
        attention_dropout (`float`, *optional*, defaults to 0.0):
            The dropout ratio for the attention probabilities.
        attention_bias (`bool`, *optional*, defaults to `False`):
            Whether to use bias in attention layers.
        position_embedding_type (`str`, *optional*, defaults to `"nope"`):
            Type of position embedding. Can be "nope" (no position embedding) or "rope".
        rope_theta (`float`, *optional*, defaults to 10000.0):
            The theta value used for the RoPE embeddings.
        rope_scaling (`dict`, *optional*):
            The scaling configuration for the RoPE embeddings. If `None`, no scaling is applied.
        mamba_d_state (`int`, *optional*, defaults to 128):
            The dimension of the mamba state space latents
        mamba_d_conv (`int`, *optional*, defaults to 4):
            The size of the mamba convolution kernel
        mamba_expand (`int`, *optional*, defaults to 2):
            Expanding factor (relative to hidden_size) used to determine the mamba intermediate size
        mamba_d_head (`int`, *optional*, defaults to 64):
            Head embedding dimension size for Mamba
        mamba_n_heads (`int`, *optional*, defaults to 64):
            The number of mamba heads
        mamba_n_groups (`int`, *optional*, defaults to 1):
            The number of the mamba groups
        mamba_chunk_size (`int`, *optional*, defaults to 256):
            The chunks in which to break the sequence when doing prefill/training
        mamba_conv_bias (`bool`, *optional*, defaults to `True`):
            Flag indicating whether or not to use bias in the convolution layer of the mamba mixer block.
        mamba_proj_bias (`bool`, *optional*, defaults to `False`):
            Flag indicating whether or not to use bias in the input and output projections of the mamba mixer block
        embedding_multiplier (`float`, *optional*, defaults to 12.0):
            The multiplier for the embedding layer. This is used to scale the output of the embedding layer.
        logits_scaling (`float`, *optional*, defaults to 8.0):
            The scaling factor for the logits.
        attention_multiplier (`float`, *optional*, defaults to 0.015625):
            The multiplier for the attention layers.
        residual_multiplier (`float`, *optional*, defaults to 0.22):
            The multiplier for residual connections.
        num_local_experts (`int`, *optional*, defaults to 0):
            Number of local experts in MoE layers.
        num_experts_per_tok (`int`, *optional*, defaults to 0):
            Number of experts to use per token in MoE layers.
        shared_intermediate_size (`int`, *optional*, defaults to 8192):
            Intermediate size for shared experts.
        output_router_logits (`bool`, *optional*, defaults to `False`):
            Whether to output router logits.
        router_aux_loss_coef (`float`, *optional*, defaults to 0.01):
            Auxiliary loss coefficient for the router.
    granitemoehybridpast_key_values  T       (   N       silu皙?h㈵>rmsnorm頇 顇            Fnope     @         @               (@       @      ?)\(?r   {Gz?c)           ,   	      s  || _ || _|| _|| _|d u r0g | _t|D ]}*|*d d dkr(| jt q| jt qn|| _t	| j| jkrHt
d| dt	| j | jD ]}+|+ttfvrat
dt dt d|+ d	qK|| _|| _|	| _|
| _|| _|| _|| _|| _|| _|| _|| _|| _|| _|| _|| _|| _|| _|| _|| _|| _|| _|| _ || | _!| j!| dkrt
d
| j! d| d|| | j!krt
d| d| d| j! d| | _"|!| _#|"| _$|#| _%|$| _&|%| _'|&| _(|'| _)|(| _*t+ j,d||||d|) d S )Nr      r   z9layer_types must have length equal to num_hidden_layers (z), but got z,Each element in layer_types must be either 'z' or 'z', but got ''zmamba_intermediate_size (z&) must be divisible by mamba_n_heads ()zmamba_d_head (z) * mamba_n_heads (z&) must equal mamba_intermediate_size ()pad_token_idbos_token_ideos_token_idtie_word_embeddings )-
vocab_sizehidden_sizeintermediate_sizenum_hidden_layerslayer_typesrangeappend	ATTENTIONMAMBAlen
ValueErrornum_attention_headsnum_key_value_heads
hidden_actinitializer_rangerms_norm_epsnormalization_function	use_cachemax_position_embeddingsattention_dropoutattention_biasposition_embedding_type
rope_thetarope_scalingmamba_d_statemamba_d_convmamba_expandmamba_d_headmamba_n_headsmamba_n_groupsmamba_chunk_sizemamba_conv_biasmamba_proj_biasmamba_intermediate_sizeembedding_multiplierlogits_scalingattention_multiplierresidual_multipliernum_local_expertsnum_experts_per_tokshared_intermediate_sizeoutput_router_logitsrouter_aux_loss_coefsuper__init__),selfr.   r,   r/   r0   r1   r2   r9   r:   r;   r<   r=   r>   r?   r)   r*   r+   r@   rA   rB   rC   rD   rE   rF   rG   rH   rI   rJ   rK   rL   rM   rN   rP   rQ   rR   rS   rT   rU   rV   rW   rX   kwargsi
layer_type	__class__r-   W/home/ubuntu/.local/lib/python3.10/site-packages/sglang/srt/configs/granitemoehybrid.pyrZ      s   ,



zGraniteMoeHybridConfig.__init__c                        fddt  jD S )z4Returns the indices of layers that are Mamba layers.c                       g | ]} j | tkr|qS r-   )r2   r6   .0r]   r[   r-   ra   
<listcomp>      z:GraniteMoeHybridConfig.mamba_layer_ids.<locals>.<listcomp>r3   r1   rf   r-   rf   ra   mamba_layer_ids     
z&GraniteMoeHybridConfig.mamba_layer_idsc                    rb   )z8Returns the indices of layers that are attention layers.c                    rc   r-   )r2   r5   rd   rf   r-   ra   rg     rh   z>GraniteMoeHybridConfig.attention_layer_ids.<locals>.<listcomp>ri   rf   r-   rf   ra   attention_layer_ids  rk   z*GraniteMoeHybridConfig.attention_layer_idsc                 C   s   | j S )z0Alias for attention_layer_ids for compatibility.)rl   rf   r-   r-   ra   full_attention_layer_ids  s   z/GraniteMoeHybridConfig.full_attention_layer_idsc              	   C   s@   ddl m} tj| | j| j| j| j| j| j	d}t
|| jdS )z;Returns the Mamba2 cache parameters for this configuration.r   )get_attention_tp_size)tp_world_sizer0   n_groups	num_headshead_dim
state_sizeconv_kernel)shapelayers)sglang.srt.layers.dp_attentionrn   r   createrO   rK   rJ   rI   rF   rG   r   rj   )r[   rn   ru   r-   r-   ra   mamba2_cache_params  s   	z*GraniteMoeHybridConfig.mamba2_cache_params)(r   Tr   r   r   Nr   r   r   r   r   r   Tr   r   r   r   r   Fr   r   Nr   r   r   r   r   r   r    TFr!   r"   r#   r$   r   r   r   Fr%   )__name__
__module____qualname____doc__
model_typekeys_to_ignore_at_inferencerZ   propertyrj   rl   rm   ry   __classcell__r-   r-   r_   ra   r      sl    a 


r   N)r}    transformers.configuration_utilsr   transformers.utilsr   sglang.srt.configs.mamba_utilsr   r   
get_loggerrz   loggerr6   r5   r   r-   r-   r-   ra   <module>   s   
