
    %	&h3                     f   d dl mZmZ d dlZd dlZd dlmZ ddlmZ ddlm	Z	 ddl
mZmZ dd	lmZmZmZmZ d
dlmZ  ej(                  e      ZdZ G d dej0                        Z G d de      ZdZ ede       G d de             ZdZ ede       G d de             Z G d de      Zg dZ y)    )OptionalTupleN)nn   )ACT2FN)Cache)add_start_docstringslogging   )GraniteMoeDecoderLayerGraniteMoeForCausalLMGraniteMoeModelGraniteMoePreTrainedModel   )GraniteMoeSharedConfigr   c                   `     e Zd ZdZdef fdZdej                  dej                  fdZ xZ	S )GraniteMoeSharedMLPz~
    MLP layer for shared experts

    Args:
        config:
            Configuration object with model hyperparameters.
    configc                 h   t         t        |           |j                  | _        |j
                  | _        t        |j                     | _        t        j                  | j                  | j                  dz  d      | _        t        j                  | j                  | j                  d      | _        y )Nr   F)bias)superr   __init__hidden_size
input_sizeshared_intermediate_sizer   
hidden_act
activationr   Linearinput_linearoutput_linearselfr   	__class__s     /var/www/pru.catia.catastroantioquia-mas.com/valormas/lib/python3.12/site-packages/transformers/models/granitemoeshared/modular_granitemoeshared.pyr   zGraniteMoeSharedMLP.__init__1   s    !413 ,,!:: !2!23IIdoot7G7G!7KRWXYYt'7'7uU    hidden_statesreturnc                     | j                  |      }|j                  dd      }| j                  |d         |d   z  }| j                  |      }|S )Nr   )dimr   r   )r   chunkr   r    )r"   r&   chunked_hidden_statess      r$   forwardzGraniteMoeSharedMLP.forward:   s^    ))-8 - 3 3A2 3 >(=a(@ADYZ[D\\**=9r%   )
__name__
__module____qualname____doc__r   r   torchTensorr-   __classcell__r#   s   @r$   r   r   (   s2    V5 VU\\ ell r%   r   c                   r    e Zd Zdedef fdZ	 	 	 	 	 	 	 	 ddej                  deej                     deej                     dee
   dee   d	ee   d
eej                     dee   deeej                  ej                  f      deej                  eeej                  ej                  f      f   fdZ xZS )GraniteMoeSharedDecoderLayerr   	layer_idxc                 t    t         |   ||       |j                  dk(  rd | _        y t        |      | _        y )Nr   )r   r   r   r   
shared_mlpr"   r   r8   r#   s      r$   r   z%GraniteMoeSharedDecoderLayer.__init__C   s3    +"("A"AQ"F$L_`fLgr%   r&   attention_maskposition_idspast_key_valueoutput_attentions	use_cachecache_positionoutput_router_logitsposition_embeddingsr'   c
                 ~   |}| j                  |      } | j                  d||||||||	d|
\  }}}||| j                  z  z   }|}| j                  |      }| j	                  |      \  }}| j
                  |}n|| j                  |      z   }~||| j                  z  z   }|f}|r||fz  }|r||fz  }|r||fz  }|S )a  
        Args:
            hidden_states (`torch.FloatTensor`): input to the layer of shape `(batch, seq_len, embed_dim)`
            attention_mask (`torch.FloatTensor`, *optional*):
                attention mask of size `(batch_size, sequence_length)` if flash attention is used or `(batch_size, 1,
                query_sequence_length, key_sequence_length)` if default attention is used.
            output_attentions (`bool`, *optional*):
                Whether or not to return the attentions tensors of all attention layers. See `attentions` under
                returned tensors for more detail.
            use_cache (`bool`, *optional*):
                If set to `True`, `past_key_values` key value states are returned and can be used to speed up decoding
                (see `past_key_values`).
            past_key_value (`Tuple(torch.FloatTensor)`, *optional*): cached past key and value projection states
            cache_position (`torch.LongTensor` of shape `(sequence_length)`, *optional*):
                Indices depicting the position of the input sequence tokens in the sequence
            output_router_logits (`bool`, *optional*):
                Whether or not to return the logits of all the routers. They are useful for computing the router loss, and
                should not be returned during inference.
            position_embeddings (`Tuple[torch.FloatTensor, torch.FloatTensor]`, *optional*):
                Tuple containing the cosine and sine positional embeddings of shape `(batch_size, seq_len, head_dim)`,
                with `head_dim` being the embedding dimension of each attention head.
            kwargs (`dict`, *optional*):
                Arbitrary kwargs to be ignored, used for FSDP and other methods that injects code
                into the model
        )r&   r<   r=   r>   r?   r@   rA   rC    )input_layernorm	self_attnresidual_multiplierpost_attention_layernormblock_sparse_moer:   )r"   r&   r<   r=   r>   r?   r@   rA   rB   rC   kwargsresidualself_attn_weightspresent_key_valuemoe_hidden_statesrouter_logitsoutputss                    r$   r-   z$GraniteMoeSharedDecoderLayer.forwardG   s   L !,,]; ?Mdnn 
?
')%)/) 3
?
 
?
;(*; !=43K3K#KK !55mD+/+@+@+O(=??"-M-0NNM =43K3K#KK ")++G)++G''Gr%   )NNNFFNFN)r.   r/   r0   r   intr   r2   r3   r   
LongTensorr   boolr   FloatTensorr-   r4   r5   s   @r$   r7   r7   B   s   h5 h# h 2637*.,1$)59/4KOR||R !.R u//0	R
 !R $D>R D>R !!1!12R 'tnR &eELL%,,,F&GHR 
u  (51B1BEDUDU1U+V"WW	XRr%   r7   aU  
    This model inherits from [`PreTrainedModel`]. Check the superclass documentation for the generic methods the
    library implements for all its model (such as downloading or saving, resizing the input embeddings, pruning heads
    etc.)

    This model is also a PyTorch [torch.nn.Module](https://pytorch.org/docs/stable/nn.html#torch.nn.Module) subclass.
    Use it as a regular PyTorch Module and refer to the PyTorch documentation for all matter related to general usage
    and behavior.

    Parameters:
        config ([`GraniteMoeSharedConfig`]):
            Model configuration class with all the parameters of the model. Initializing with a config file does not
            load the weights associated with the model, only the configuration. Check out the
            [`~PreTrainedModel.from_pretrained`] method to load the model weights.
z^The bare GraniteMoeShared Model outputting raw hidden-states without any specific head on top.c                       e Zd ZeZdgZy)GraniteMoeSharedPreTrainedModelr7   N)r.   r/   r0   r   config_class_no_split_modulesrE   r%   r$   rW   rW      s    
 *L78r%   rW   a  
    Args:
        input_ids (`torch.LongTensor` of shape `(batch_size, sequence_length)`):
            Indices of input sequence tokens in the vocabulary. Padding will be ignored by default should you provide
            it.

            Indices can be obtained using [`AutoTokenizer`]. See [`PreTrainedTokenizer.encode`] and
            [`PreTrainedTokenizer.__call__`] for details.

            [What are input IDs?](../glossary#input-ids)
        attention_mask (`torch.Tensor` of shape `(batch_size, sequence_length)`, *optional*):
            Mask to avoid performing attention on padding token indices. Mask values selected in `[0, 1]`:

            - 1 for tokens that are **not masked**,
            - 0 for tokens that are **masked**.

            [What are attention masks?](../glossary#attention-mask)

            Indices can be obtained using [`AutoTokenizer`]. See [`PreTrainedTokenizer.encode`] and
            [`PreTrainedTokenizer.__call__`] for details.

            If `past_key_values` is used, optionally only the last `input_ids` have to be input (see
            `past_key_values`).

            If you want to change padding behavior, you should read [`modeling_opt._prepare_decoder_attention_mask`]
            and modify to your needs. See diagram 1 in [the paper](https://arxiv.org/abs/1910.13461) for more
            information on the default strategy.

            - 1 indicates the head is **not masked**,
            - 0 indicates the head is **masked**.
        position_ids (`torch.LongTensor` of shape `(batch_size, sequence_length)`, *optional*):
            Indices of positions of each input sequence tokens in the position embeddings. Selected in the range `[0,
            config.n_positions - 1]`.

            [What are position IDs?](../glossary#position-ids)
        past_key_values (`Cache` or `tuple(tuple(torch.FloatTensor))`, *optional*):
            Pre-computed hidden-states (key and values in the self-attention blocks and in the cross-attention
            blocks) that can be used to speed up sequential decoding. This typically consists in the `past_key_values`
            returned by the model at a previous stage of decoding, when `use_cache=True` or `config.use_cache=True`.

            Two formats are allowed:
            - a [`~cache_utils.Cache`] instance;
            - Tuple of `tuple(torch.FloatTensor)` of length `config.n_layers`, with each tuple having 2 tensors of
            shape `(batch_size, num_heads, sequence_length, embed_size_per_head)`). This is also known as the legacy
            cache format.

            The model will output the same cache format that is fed as input. If no `past_key_values` are passed, the
            legacy cache format will be returned.

            If `past_key_values` are used, the user can optionally input only the last `input_ids` (those that don't
            have their past key value states given to this model) of shape `(batch_size, 1)` instead of all `input_ids`
            of shape `(batch_size, sequence_length)`.
        inputs_embeds (`torch.FloatTensor` of shape `(batch_size, sequence_length, hidden_size)`, *optional*):
            Optionally, instead of passing `input_ids` you can choose to directly pass an embedded representation. This
            is useful if you want more control over how to convert `input_ids` indices into associated vectors than the
            model's internal embedding lookup matrix.
        use_cache (`bool`, *optional*):
            If set to `True`, `past_key_values` key value states are returned and can be used to speed up decoding (see
            `past_key_values`).
        output_attentions (`bool`, *optional*):
            Whether or not to return the attentions tensors of all attention layers. See `attentions` under returned
            tensors for more detail.
        output_hidden_states (`bool`, *optional*):
            Whether or not to return the hidden states of all layers. See `hidden_states` under returned tensors for
            more detail.
        return_dict (`bool`, *optional*):
            Whether or not to return a [`~utils.ModelOutput`] instead of a plain tuple.
        cache_position (`torch.LongTensor` of shape `(sequence_length)`, *optional*):
            Indices depicting the position of the input sequence tokens in the sequence. Contrarily to `position_ids`,
            this tensor is not affected by padding. It is used to update the cache in the correct position and to infer
            the complete sequence length.
c                   (     e Zd ZdZdef fdZ xZS )GraniteMoeSharedModelz
    Transformer decoder consisting of *config.num_hidden_layers* layers. Each layer is a [`GraniteMoeDecoderLayer`]

    Args:
        config: GraniteMoeSharedConfig
    r   c           	          t         |   |       t        j                  t	        |j
                        D cg c]  }t        ||       c}      | _        y c c}w N)r   r   r   
ModuleListrangenum_hidden_layersr7   layersr;   s      r$   r   zGraniteMoeSharedModel.__init__  sE     mmNSTZTlTlNmn)&)<n
ns   A)r.   r/   r0   r1   r   r   r4   r5   s   @r$   r[   r[      s    

5 
 
r%   r[   c                   *     e Zd ZdgZdef fdZ xZS )GraniteMoeSharedForCausalLMzlm_head.weightr   c                 d    t         |   |       t        |      | _        | j	                          y r]   )r   r   r[   model	post_initr!   s     r$   r   z$GraniteMoeSharedForCausalLM.__init__  s&     *62
r%   )r.   r/   r0   _tied_weights_keysr   r   r4   r5   s   @r$   rc   rc     s    *+5  r%   rc   )rc   r[   rW   )!typingr   r   r2   torch.utils.checkpointr   activationsr   cache_utilsr   utilsr	   r
   granitemoe.modeling_granitemoer   r   r   r   configuration_granitemoesharedr   
get_loggerr.   logger_CONFIG_FOR_DOCModuler   r7    GRANITEMOESHARED_START_DOCSTRINGrW   !GRANITEMOESHARED_INPUTS_DOCSTRINGr[   rc   __all__rE   r%   r$   <module>rv      s     #    !   2  C 
		H	% +")) 4W#9 Wt$  " d$9&? 9	9
G% !T d$
O 
	
"7  fr%   