
    ^j2                        d dl Z d dlmc mZ d dl mZ ddlmZ ddlm	Z	m
Z
 ddlmZ ddlmZ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 ddlmZ ddlmZmZ ddlm Z m!Z! ddl"m#Z#m$Z$m%Z%m&Z&m'Z' ddl(m)Z)  G d de      Z* G d de      Z+ G d dejX                        Z- G d de$      Z. G d dejX                        Z/ G d de       Z0 G d d e#      Z1e G d! d"e!e             Z2e G d# d$e&             Z3 G d% d&e%      Z4g d'Z5y)(    N)nn   )initialization)CacheDynamicCache)create_causal_mask)MoeCausalLMOutputWithPastMoeModelOutputWithPast)PreTrainedModel)Unpack)TransformersKwargsauto_docstring)can_return_tuplemerge_with_config_defaults)capture_outputs   )GraniteRMSNormGraniteRotaryEmbedding)LlamaAttentionLlamaPreTrainedModel)MixtralDecoderLayerMixtralExpertsMixtralForCausalLMMixtralModelload_balancing_loss_func   )GraniteMoeConfigc                       e Zd Zy)GraniteMoeRMSNormN__name__
__module____qualname__     |/var/www/ramen.bs-engineer-server.com/venv/lib/python3.12/site-packages/transformers/models/granitemoe/modular_granitemoe.pyr   r   )       r%   r   c                       e Zd Zy)GraniteMoeRotaryEmbeddingNr    r$   r%   r&   r)   r)   -   r'   r%   r)   c                        e Zd ZdZdef fdZdej                  deej                  ej                  ej                  f   fdZ	 xZ
S )GraniteMoeTopKRoutera  Top-k gating that returns the routing decisions without grouping tokens by expert.

    Returns ``(top_k_index, top_k_weights, router_logits)``; the grouping/scattering used to live
    here (via ``expert_size.tolist()``, which broke fullgraph compile) and now happens inside the
    experts forward via ``use_experts_implementation`` so the default ``grouped_mm`` / ``batched_mm``
    paths can compile cleanly.
    configc                     t         |           |j                  | _        |j                  | _        t        j                  t        j                  | j                  |j                              | _        y N)super__init__num_local_expertsnum_expertsnum_experts_per_toktop_kr   	Parametertorchemptyhidden_sizeweightselfr,   	__class__s     r&   r0   zGraniteMoeTopKRouter.__init__:   sP    !33//
ll5;;t/?/?ASAS#TUr%   hidden_statesreturnc                     t        j                  || j                        j                         }|j	                  | j
                  d      \  }}t        j                  |d      j                  |      }|||fS )N)dim)	Flinearr9   floattopkr4   r6   softmaxtype_as)r;   r=   router_logitstop_k_logitstop_k_indextop_k_weightss         r&   forwardzGraniteMoeTopKRouter.forward@   se    <BBD$1$6$6tzzr$6$J!kl;CCMRM=88r%   )r!   r"   r#   __doc__r   r0   r6   TensortuplerL   __classcell__r<   s   @r&   r+   r+   1   sI    V/ V9U\\ 9eELL%,,X]XdXd<d6e 9r%   r+   c                       e Zd Zy)GraniteMoeExpertsNr    r$   r%   r&   rS   rS   G   r'   r%   rS   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 )GraniteMoeMoEzISparsely-gated mixture-of-experts block: router decides, experts compute.r,   c                     t         |           |j                  | _        t	        |      | _        t        |      | _        y r.   )r/   r0   r8   
input_sizer+   routerrS   expertsr:   s     r&   r0   zGraniteMoeMoE.__init__N   s3     ,,*62(0r%   layer_inputr>   c                     |j                         \  }}}|j                  d|      }| j                  |      \  }}}| j                  |||      }	|	j	                  ||| j
                        S )Nr@   )sizereshaperX   rY   viewrW   )
r;   rZ   bszlengthemb_sizer=   rJ   rK   _layer_outputs
             r&   rL   zGraniteMoeMoE.forwardT   si     + 0 0 2VX#++B9(,M(B%]A||M;N  fdoo>>r%   )
r!   r"   r#   rM   r   r0   r6   rN   rL   rP   rQ   s   @r&   rU   rU   K   s.    S1/ 1?5<< ?ELL ?r%   rU   c                   (     e Zd Zdedef fdZ xZS )GraniteMoeAttentionr,   	layer_idxc                 J    t         |   | ||       |j                  | _        y r.   )r/   r0   attention_multiplierscalingr;   r,   rf   r<   s      r&   r0   zGraniteMoeAttention.__init__]   s!    vy122r%   )r!   r"   r#   r   intr0   rP   rQ   s   @r&   re   re   \   s    3/ 3C 3 3r%   re   c                        e Zd Zdedef fdZ	 	 	 ddej                  dej                  dz  dedz  de	ej                  ej                  f   dz  d	ej                  f
d
Z
 xZS )GraniteMoeDecoderLayerr,   rf   c                 H   t         |   ||       t        ||      | _        t	        |      | _        t        |j                  |j                        | _	        t        |j                  |j                        | _
        | `t	        |      | _        |j                  | _        y )N)r,   rf   eps)r/   r0   re   	self_attnrU   block_sparse_moer   r8   rms_norm_epsinput_layernormpost_attention_layernormmlpresidual_multiplierrj   s      r&   r0   zGraniteMoeDecoderLayer.__init__c   s    +,FiP -f 501C1CI\I\](9&:L:LRXReRe(f%H -f 5#)#=#= r%   Nr=   attention_maskpast_key_valuesposition_embeddingsr>   c                     |}| j                  |      } | j                  d||||d|\  }}||| j                  z  z   }|}| j                  |      }| j	                  |      }||| j                  z  z   }|S )N)r=   rx   ry   rz   r$   )rt   rq   rw   ru   rr   )r;   r=   rx   ry   rz   kwargsresidualrb   s           r&   rL   zGraniteMoeDecoderLayer.forwardm   s     !,,];)4>> 
')+ 3	

 
q !=43K3K#KK 55mD--m< =43K3K#KKr%   )NNN)r!   r"   r#   r   rk   r0   r6   rN   r   rO   rL   rP   rQ   s   @r&   rm   rm   b   s    >/ >C > /3(,HL|| t+ 	
 #5<<#=>E 
r%   rm   c                   f    e Zd ZU eed<   dZdZdgZdgZdZ	dZ
dZ ej                         d        Zy)GraniteMoePreTrainedModelr,   modelTrm   ry   c                    t        j                  | |       t        |t              rmt	        j
                  |j                  d| j                  j                         t	        j
                  |j                  d| j                  j                         y t        |t              r7t	        j
                  |j                  d| j                  j                         y y )Ng        )meanstd)r   _init_weights
isinstancerS   initnormal_gate_up_projr,   initializer_range	down_projr+   r9   )r;   modules     r&   r   z'GraniteMoePreTrainedModel._init_weights   s    %%dF3f/0LL,,3DKK<Y<YZLL))9V9VW 45LLSdkk6S6ST 6r%   N)r!   r"   r#   r   __annotations__base_model_prefixsupports_gradient_checkpointing_no_split_modules_skip_keys_device_placement_supports_flash_attn_supports_sdpa_can_compile_fullgraphr6   no_gradr   r$   r%   r&   r   r      sS    &*#12#4"5N!U]]_U Ur%   r   c                        e Zd Zdef fdZeee	 	 	 	 	 	 ddej                  dz  dej                  dz  dej                  dz  dedz  dej                  dz  d	edz  d
ee   defd                     Z xZS )GraniteMoeModelr,   c           	      &   t         |   |       t        j                  t	        |j
                        D cg c]  }t        ||       c}      | _        t        |j                  |j                        | _        |j                  | _        y c c}w )Nro   )r/   r0   r   
ModuleListrangenum_hidden_layersrm   layersr   r8   rs   normembedding_multiplierrj   s      r&   r0   zGraniteMoeModel.__init__   sq     mmHMfNfNfHgh9#FI6h
 &f&8&8f>Q>QR	$*$?$?! is   BN	input_idsrx   position_idsry   inputs_embeds	use_cacher|   r>   c           
      X   |d u |d uz  rt        d      |r|t        | j                        }|| j                  |      }|V||j	                         nd}t        j                  |j                  d   |j                        |z   }|j                  d      }t        | j                  ||||      }	|| j                  z  }|}
| j                  |
|      }| j                  d | j                  j                   D ]  } ||
f||	|||d|}
 | j                  |
      }
t!        |
|      S )	Nz:You must specify exactly one of input_ids or inputs_embeds)r,   r   r   )device)r,   r   rx   ry   r   )rz   rx   r   ry   r   )last_hidden_statery   )
ValueErrorr   r,   embed_tokensget_seq_lengthr6   arangeshaper   	unsqueezer   r   
rotary_embr   r   r   r
   )r;   r   rx   r   ry   r   r   r|   past_seen_tokenscausal_maskr=   rz   decoder_layers                r&   rL   zGraniteMoeModel.forward   s\    -t";<YZZ0*$++>O  --i8MCRC^==?de <<(;(;A(>}G[G[\_ooL'11!4L(;;')+%
 &(A(AA% #oom\J![[)H4;;+H+HI 		M)$7*) /# M		 		-0%++
 	
r%   )NNNNNN)r!   r"   r#   r   r0   r   r   r   r6   
LongTensorrN   r   FloatTensorboolr   r   r
   rL   rP   rQ   s   @r&   r   r      s    @/ @   .2.204(,26!%5
##d*5
 t+5
 &&-	5

 5
 ((4/5
 $;5
 +,5
 
 5
    5
r%   r   c                   $    e Zd Zdef fdZee	 	 	 	 	 	 	 	 ddej                  dz  dej                  dz  dej                  dz  de
dz  dej                  dz  d	ej                  dz  d
edz  deej                  z  deez  fd              Z xZS )GraniteMoeForCausalLMr,   c                 f    t         |   |       t        |      | _        |j                  | _        y r.   )r/   r0   r   r   logits_scalingr:   s     r&   r0   zGraniteMoeForCausalLM.__init__   s*     $V,
$33r%   Nr   rx   r   ry   r   labelsoutput_router_logitslogits_to_keepr>   c	           	         ||n| j                   j                  } | j                  d|||||d|	}
|
j                  }t	        |t
              rt        | d      n|}| j                  |dd|ddf         }|| j                   j                  z  }d}|* | j                  ||fd| j                   j                  i|	}d}|rYt        |
j                  | j                  | j                  |      }|+|| j                  |j!                  |j"                        z  z  }t%        ||||
j&                  |
j(                  |
j*                  |
j                        S )al  
        labels (`torch.LongTensor` of shape `(batch_size, sequence_length)`, *optional*):
            Labels for computing the masked language modeling loss. Indices should either be in `[0, ...,
            config.vocab_size]` or -100 (see `input_ids` docstring). Tokens with indices set to `-100` are ignored
            (masked), the loss is only computed for the tokens with labels in `[0, ..., config.vocab_size]`.

        Example:

        ```python
        >>> from transformers import AutoTokenizer, GraniteMoeForCausalLM

        >>> model = GraniteMoeForCausalLM.from_pretrained("ibm/PowerMoE-3b")
        >>> tokenizer = AutoTokenizer.from_pretrained("ibm/PowerMoE-3b")

        >>> prompt = "Hey, are you conscious? Can you talk to me?"
        >>> inputs = tokenizer(prompt, return_tensors="pt")

        >>> # Generate
        >>> generate_ids = model.generate(inputs.input_ids, max_length=30)
        >>> tokenizer.batch_decode(generate_ids, skip_special_tokens=True, clean_up_tokenization_spaces=False)[0]
        "Hey, are you conscious? Can you talk to me?\nI'm not conscious, but I can talk to you."
        ```N)r   rx   r   ry   r   
vocab_size)lossaux_losslogitsry   r=   
attentionsrH   r$   )r,   r   r   r   r   rk   slicelm_headr   loss_functionr   r   rH   r2   r3   router_aux_loss_coeftor   r	   ry   r=   r   )r;   r   rx   r   ry   r   r   r   r   r|   outputsr=   slice_indicesr   r   r   s                   r&   rL   zGraniteMoeForCausalLM.forward   s|   J %9$D $++JjJj 	 $** 
)%+'
 
  118B>SV8W~ot4]kmA}a,?@A$++444%4%%  ;;11 	D /%%  ((	H !11HKK4LLL(#33!//))!//
 	
r%   )NNNNNNNr   )r!   r"   r#   r   r0   r   r   r6   r   rN   r   r   r   rk   rO   r	   rL   rP   rQ   s   @r&   r   r      s    4/ 4
  .2.204(,26*.,0-.Q
##d*Q
 t+Q
 &&-	Q

 Q
 ((4/Q
   4'Q
 #TkQ
 ell*Q
 
*	*Q
  Q
r%   r   )r   r   r   )6r6   torch.nn.functionalr   
functionalrB    r   r   cache_utilsr   r   masking_utilsr   modeling_outputsr	   r
   modeling_utilsr   processing_utilsr   utilsr   r   utils.genericr   r   utils.output_capturingr   granite.modeling_graniter   r   llama.modeling_llamar   r   mixtral.modeling_mixtralr   r   r   r   r   configuration_granitemoer   r   r)   Moduler+   rS   rU   re   rm   r   r   r   __all__r$   r%   r&   <module>r      s         & . / Q - & 7 I 5 M G  7	 		 6 	9299 9,	 	?BII ?"3. 3!0 !H U 4o U U( A
l A
 A
HY
. Y
x Tr%   