
    ^j                     j   d dl mZ d dlmZ 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 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 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% ddl&m'Z' ddl(m)Z)m*Z* ddl+m,Z,m-Z-m.Z. ddl/m0Z0m1Z1 ddl2m3Z3  ed       G d dejh                               Z5 G d dejh                        Z6 G d dejh                        Z7 G d dejh                        Z8e G d  d!ejh                               Z9 G d" d#ejh                        Z:d$ Z;dAd%Z<d&ejz                  d'e>d(ejz                  fd)Z?	 dBd*ejh                  d+ejz                  d,ejz                  d-ejz                  d.ejz                  dz  d/e@d0e@d1e'e,   fd2ZA G d3 d4ejh                        ZB G d5 d6e      ZCe) G d7 d8e%             ZDe) G d9 d:eD             ZE	 	 	 dCd;ejz                  eFejz                     z  dz  d<e>dz  d.ejz                  dz  d(ejz                  e>z  fd=ZGe) G d> d?eDe             ZHg d@ZIy)D    )Callable)OptionalN)nn   )initialization)ACT2FN)CacheDynamicCache)GenerationMixin)use_experts_implementationuse_kernel_forward_from_hub)create_causal_mask!create_sliding_window_causal_mask)FlashAttentionKwargs)GradientCheckpointingLayer)MoeCausalLMOutputWithPastMoeModelOutputWithPast)ROPE_INIT_FUNCTIONSdynamic_rope_update)ALL_ATTENTION_FUNCTIONSPreTrainedModel)Unpack)auto_docstringcan_return_tuple)TransformersKwargsmaybe_autocastmerge_with_config_defaults)OutputRecordercapture_outputs   )LagunaConfigRMSNormc                   h     e Zd Zddeddf fdZdej                  dej                  fdZd Z xZ	S )	LagunaRMSNormepsreturnNc                     t         |           t        j                  t	        j
                  |            | _        || _        y)z<
        LagunaRMSNorm is equivalent to T5LayerNorm
        N)super__init__r   	Parametertorchonesweightvariance_epsilon)selfhidden_sizer%   	__class__s      u/var/www/ramen.bs-engineer-server.com/venv/lib/python3.12/site-packages/transformers/models/laguna/modeling_laguna.pyr)   zLagunaRMSNorm.__init__0   s1     	ll5::k#:; #    hidden_statesc                 "   |j                   }|j                  t        j                        }|j	                  d      j                  dd      }|t        j                  || j                  z         z  }| j                  |j                  |      z  S )N   T)keepdim)	dtypetor+   float32powmeanrsqrtr.   r-   )r/   r4   input_dtypevariances       r2   forwardzLagunaRMSNorm.forward8   sy    #))%((7 $$Q',,R,>%Ht?T?T4T(UU{{]--k:::r3   c                 ^    t        | j                  j                         d| j                   S )Nz, eps=)tupler-   shaper.   )r/   s    r2   
extra_reprzLagunaRMSNorm.extra_repr?   s*    ))*+6$2G2G1HIIr3   )gư>)
__name__
__module____qualname__floatr)   r+   TensorrA   rE   __classcell__r1   s   @r2   r$   r$   .   s7    $ $$ $;U\\ ;ell ;Jr3   r$   c                        e Zd ZU ej                  ed<   def fdZe	 	 	 	 ddedz  de	d   de
dz  dedz  d	ed
ef   f
d       Z ej                         edd              Z xZS )LagunaRotaryEmbeddinginv_freqconfigc                 t   t         |           |j                  | _        |j                  | _        || _        t        t        |j                              | _        i | _	        | j                  D ]  }| j
                  j                  |   }||d   | j                  |<   | j                  }| j                  |   dk7  rt        | j                  |      } || j
                  |      \  }}| j                  | d|d       | j                  | d|j                         d       t        | | d|        y )	N	rope_typedefault
layer_type	_inv_freqF)
persistent_original_inv_freq_attention_scaling)r(   r)   max_position_embeddingsmax_seq_len_cachedoriginal_max_seq_lenrP   listsetlayer_typesrR   rope_parameterscompute_default_rope_parametersr   register_bufferclonesetattr)r/   rP   rU   rope_paramsrope_init_fncurr_inv_freqcurr_attention_scalingr1   s          r2   r)   zLagunaRotaryEmbedding.__init__F   s6   "("@"@$*$B$B!F$6$6 78** 	UJ++55jAK")4[)ADNN:&%)%I%IL~~j)Y624>>*3MN4@Yc4d1M1  J<y!9=UZ [  J</A!BMDWDWDYfk lDZL(:;=ST	Ur3   Ndeviceztorch.deviceseq_lenrU   r&   ztorch.Tensorc                 z   | j                   |   d   }| j                   |   j                  dd      }t        | dd      xs | j                  | j                  z  }t        ||z        }d}d|t        j                  d|dt        j                        j                  |t        j                  	      |z  z  z  }	|	|fS )
a{  
        Computes the inverse frequencies according to the original RoPE implementation
        Args:
            config ([`~transformers.PreTrainedConfig`]):
                The model configuration.
            device (`torch.device`):
                The device to use for initialization of the inverse frequencies.
            seq_len (`int`, *optional*):
                The current sequence length. Unused for this type of RoPE.
            layer_type (`str`, *optional*):
                The current layer type if the model has different RoPE parameters per type.
                Should not be used unless `config.layer_types is not None`
        Returns:
            Tuple of (`torch.Tensor`, `float`), containing the inverse frequencies for the RoPE embeddings and the
            post-processing scaling factor applied to the computed cos/sin (unused in this type of RoPE).
        
rope_thetapartial_rotary_factorg      ?head_dimNr   r6   r9   )ri   r9   )r`   getgetattrr0   num_attention_headsintr+   arangeint64r:   rI   )
rP   ri   rj   rU   baserm   rn   dimattention_factorrO   s
             r2   ra   z5LagunaRotaryEmbedding.compute_default_rope_parameters[   s    . %%j1,? & 6 6z B F FG^`c d6:t4h8J8JfNhNh8h(223 U\\!S!5;;?BB&X]XcXcBdgjjk
 )))r3   c                 N   t        | | d      }t        | | d      }|d d d d f   j                         j                  |j                  d   dd      j	                  |j
                        }|d d d d d f   j                         }t        |j
                  j                  t              r/|j
                  j                  dk7  r|j
                  j                  nd}t        |d	      5  |j                         |j                         z  j                  dd
      }	t        j                  |	|	fd      }
|
j                         |z  }|
j                         |z  }d d d        j	                  |j                        j	                  |j                        fS # 1 sw Y   AxY w)NrV   rY   r   r7   r    mpscpuF)device_typeenabledr6   rw   ro   )rq   rI   expandrD   r:   ri   
isinstancetypestrr   	transposer+   catcossinr9   )r/   xposition_idsrU   rO   attention_scalinginv_freq_expandedposition_ids_expandedr|   freqsembr   r   s                r2   rA   zLagunaRotaryEmbedding.forward   sl    4J<y!9:#DZL8J*KL$T1d]399;BB<CUCUVWCXZ\^_`ccdedldlm ,QaZ 8 > > @'1!((--'E!((--[`J`ahhmmfkUC 	0&,,.1F1L1L1NNYYZ[]^_E))UEN3C'')//C'')//C		0 vvAGGv$cff177f&;;;	0 	0s   *A1FF$)NNNNN)rF   rG   rH   r+   rJ   __annotations__r!   r)   staticmethodr   rs   r   rC   rI   ra   no_gradr   rA   rK   rL   s   @r2   rN   rN   C   s    llU| U* &*+/"!%	"*t#"*("* t"* $J	"*
 
~u$	%"* "*H U]]_<  <r3   rN   c                   &     e Zd Zd fd	Zd Z xZS )	LagunaMLPc                    t         |           || _        |j                  | _        ||j                  n|| _        t        j                  | j                  | j                  d      | _        t        j                  | j                  | j                  d      | _        t        j                  | j                  | j                  d      | _	        t        |j                     | _        y NFbias)r(   r)   rP   r0   intermediate_sizer   Linear	gate_projup_proj	down_projr   
hidden_actact_fn)r/   rP   r   r1   s      r2   r)   zLagunaMLP.__init__   s    !--=N=V!9!9\m4#3#3T5K5KRWXyy!1!143I3IPUV4#9#94;K;KRWXV../r3   c                     | j                  | j                  | j                  |            | j                  |      z        }|S r   )r   r   r   r   )r/   r   r   s      r2   rA   zLagunaMLP.forward   s6    NN4;;t~~a/@#ADLLQRO#ST	r3   r   )rF   rG   rH   r)   rA   rK   rL   s   @r2   r   r      s    0r3   r   c                        e Zd Z fdZdej
                  deej
                  ej
                  ej
                  f   fdZ xZS )LagunaTopKRouterc                    t         |           |j                  | _        |j                  | _        |j
                  | _        t        j                  t        j                  | j                  | j                              | _        t        j                  t        j                  |j                        d      | _        |j                  | _        y )NF)requires_grad)r(   r)   num_experts_per_toktop_knum_expertsr0   
hidden_dimr   r*   r+   zerosr-   e_score_correction_biasmoe_router_logit_softcappingrouter_logit_softcappingr/   rP   r1   s     r2   r)   zLagunaTopKRouter.__init__   s    //
!-- ,,ll5;;t/?/?#QR')||EKK@R@R4Sch'i$(.(K(K%r3   r4   r&   c                 f   |j                  d| j                        }t        j                  || j                        j                         }| j                  dkD  r/t        j                  || j                  z        | j                  z  }t        j                  |      }|| j                  j                  |j                        z   }t        j                  || j                  d      \  }}|j                  d|      }||j!                  dd      z  }|j                  |j                        }|||fS )Nr7           r~   T)rw   r8   )reshaper   Flinearr-   rI   r   r+   tanhsigmoidr   r:   r9   topkr   gathersum)r/   r4   router_logitsrouting_scoresscores_for_selection_selected_expertsrouting_weightss           r2   rA   zLagunaTopKRouter.forward   s
    &--b$//B<BBD((3.!JJ}t7T7T'TUX\XuXuuM}5-0L0L0O0OP^PdPd0ee#jj)=tzzrR(//4DE)O,?,?BPT,?,UU),,]-@-@Ao/???r3   )	rF   rG   rH   r)   r+   rJ   rC   rA   rK   rL   s   @r2   r   r      s?    L@||@ 
u||U\\5<<7	8@r3   r   c                        e Zd ZdZ fdZdej                  dej                  dej                  dej                  fdZ xZS )LagunaExpertsz2Collection of expert weights stored as 3D tensors.c                    t         |           |j                  | _        |j                  | _        |j
                  | _        t        j                  t        j                  | j                  d| j                  z  | j                              | _        t        j                  t        j                  | j                  | j                  | j                              | _        t        |j                     | _        y )Nr6   )r(   r)   r   r0   r   moe_intermediate_sizeintermediate_dimr   r*   r+   emptygate_up_projr   r   r   r   r   s     r2   r)   zLagunaExperts.__init__   s    !-- ,, & < <LLT5E5Eq4K`K`G`bfbqbq)rsekk$2B2BDOOUYUjUj&klV../r3   r4   top_k_indextop_k_weightsr&   c                 f   t        j                  |      }t        j                         5  t         j                  j                  j                  || j                        }|j                  ddd      }t        j                  |j                  d      d      j                         }d d d        D ]  }|d   }|| j                  k(  rt        j                  |         \  }}	||	   }
t        j                  j                  |
| j                  |         j                  dd      \  }}| j                  |      |z  }t        j                  j                  || j                   |         }|||	|d f   z  }|j#                  d|	|j%                  |j&                                |S # 1 sw Y   xY w)N)num_classesr6   r    r   )r7   r~   r7   )r+   
zeros_liker   r   
functionalone_hotr   permutegreaterr   nonzerowherer   r   chunkr   r   
index_add_r:   r9   )r/   r4   r   r   final_hidden_statesexpert_mask
expert_hit
expert_idx	top_k_pos	token_idxcurrent_stategateupcurrent_hidden_statess                 r2   rA   zLagunaExperts.forward   s    $..}=]]_ 	S((--55ktO_O_5`K%--aA6K{8'DaHPPRJ	S
 % 
	nJ#AJT---#(;;{:/F#G Iy))4M}}++M4;L;LZ;XY__`agi_jHD"$(KK$5$:!$&MM$8$89NPTP^P^_iPj$k!$9M)U^`dJd<e$e!**1i9N9Q9QReRkRk9lm
	n #"#	S 	Ss   A=F&&F0)	rF   rG   rH   __doc__r)   r+   rJ   rA   rK   rL   s   @r2   r   r      sF    <0#||# \\# ||	#
 
#r3   r   c                   \     e Zd Zdef fdZdej                  dej                  fdZ xZS )LagunaSparseMoeBlockrP   c                     t         |           t        |      | _        t	        |      | _        t        ||j                        | _        |j                  | _
        y )Nr   )r(   r)   r   expertsr   r   r   shared_expert_intermediate_sizeshared_expertsmoe_routed_scaling_factorrouted_scaling_factorr   s     r2   r)   zLagunaSparseMoeBlock.__init__   sI    $V,$V,	'&BhBhi%+%E%E"r3   r4   r&   c                 
   |j                   \  }}}|j                  d|      }| j                  |      }| j                  |      \  }}}| j	                  |||      }|| j
                  z  }||z   }|j                  |||      }|S )Nr7   )rD   viewr   r   r   r   r   )	r/   r4   
batch_sizesequence_lengthr   shared_outputr   r   r   s	            r2   rA   zLagunaSparseMoeBlock.forward   s    2?2E2E/
OZ%**2z:++M:/3yy/G,?,]4DoV%(B(BB%5%--j/:Vr3   )	rF   rG   rH   r!   r)   r+   rJ   rA   rK   rL   s   @r2   r   r      s,    F| FU\\ ell r3   r   c                     | dd| j                   d   dz  f   }| d| j                   d   dz  df   }t        j                  | |fd      S )z*Rotates half the hidden dims of the input..Nr7   r6   r~   )rD   r+   r   )r   x1x2s      r2   rotate_halfr     sZ    	
3"!''"+"""	#B	
3q ""	#B99rc2YB''r3   c                 h   |j                  |      }|j                  |      }|j                  d   }| dd|f   | d|df   }}|dd|f   |d|df   }	}||z  t        |      |z  z   }
||z  t        |      |z  z   }t        j                  |
|gd      }
t        j                  ||	gd      }|
|fS )a  Applies Rotary Position Embedding to the query and key tensors.

    Removes the interleaving of cos and sin from GLM

    Args:
        q (`torch.Tensor`): The query tensor.
        k (`torch.Tensor`): The key tensor.
        cos (`torch.Tensor`): The cosine part of the rotary embedding.
        sin (`torch.Tensor`): The sine part of the rotary embedding.
        unsqueeze_dim (`int`, *optional*, defaults to 1):
            The 'unsqueeze_dim' argument specifies the dimension along which to unsqueeze cos[position_ids] and
            sin[position_ids] so that they can be properly broadcasted to the dimensions of q and k. For example, note
            that cos[position_ids] and sin[position_ids] have the shape [batch_size, seq_len, head_dim]. Then, if q and
            k have the shape [batch_size, heads, seq_len, head_dim], then setting unsqueeze_dim=1 makes
            cos[position_ids] and sin[position_ids] broadcastable to the shapes of q and k. Similarly, if q and k have
            the shape [batch_size, seq_len, heads, head_dim], then set unsqueeze_dim=2.
    Returns:
        `tuple(torch.Tensor)` comprising of the query and key tensors rotated using the Rotary Position Embedding.
    r7   .Nr~   )	unsqueezerD   r   r+   r   )qkr   r   unsqueeze_dim
rotary_dimq_rotq_passk_rotk_passq_embedk_embeds               r2   apply_rotary_pos_embr   	  s    ( --
&C
--
&C 2Jc;J;&'3
+;)<6Ec;J;&'3
+;)<6E s{{51C78Gs{{51C78G ii&)r2Gii&)r2GGr3   r4   n_repr&   c                     | j                   \  }}}}|dk(  r| S | dddddddddf   j                  |||||      } | j                  |||z  ||      S )z
    This is the equivalent of torch.repeat_interleave(x, dim=1, repeats=n_rep). The hidden states go from (batch,
    num_key_value_heads, seqlen, head_dim) to (batch, num_attention_heads, seqlen, head_dim)
    r    N)rD   r   r   )r4   r   batchnum_key_value_headsslenrn   s         r2   	repeat_kvr  /  so    
 2?1D1D.Ehz!!Qa"23::5BUW\^bdlmM  (;e(CT8TTr3   modulequerykeyvalueattention_maskscalingdropoutkwargsc                    t        || j                        }t        || j                        }	t        j                  ||j	                  dd            |z  }
||
|z   }
t
        j                  j                  |
dt        j                        j                  |j                        }
t
        j                  j                  |
|| j                        }
t        j                  |
|	      }|j	                  dd      j                         }||
fS )Nr6   r   r7   )rw   r9   )ptrainingr    )r  num_key_value_groupsr+   matmulr   r   r   softmaxr;   r:   r9   r  r  
contiguous)r  r  r  r  r  r  r  r	  
key_statesvalue_statesattn_weightsattn_outputs               r2   eager_attention_forwardr  ;  s     3 ; ;<JUF$?$?@L<<z';';Aq'ABWLL!#n4==((2U]](SVVW\WbWbcL==((6??([L,,|\:K''1-88:K$$r3   c                        e Zd ZdZdededef fdZ	 ddej                  de	ej                  ej                  f   d	ej                  dz  d
e
dz  dee   de	ej                  ej                  dz  f   fdZ xZS )LagunaAttentionzSAfmoe-style SWA/GQA attention with Laguna-specific gating and per-layer head count.rP   	layer_idx	num_headsc                 n   t         |           || _        || _        || _        t        |d|j                  |j                  z        | _        | j                  |j                  z  | _
        | j                  dz  | _        |j                  | _        d| _        t        j                  |j                  | j                  | j                  z  |j                         | _        t        j                  |j                  |j                  | j                  z  |j                         | _        t        j                  |j                  |j                  | j                  z  |j                         | _        t        j                  | j                  | j                  z  |j                  |j                         | _        |j*                  |   dk(  | _        | j,                  r|j.                  nd | _        t1        | j                  |j2                        | _        t1        | j                  |j2                        | _        |j8                  du xs |j8                  dk(  | _        | j:                  r| j                  n| j                  | j                  z  }t        j                  |j                  |d      | _        y )	Nrn   g      Tr   sliding_attentionr%   zper-headF)r(   r)   r  rP   r  rq   r0   rr   rn   r   r  r  attention_dropout	is_causalr   r   attention_biasq_projk_projv_projo_projr_   is_local_attentionsliding_windowr$   rms_norm_epsq_normk_normgatinggate_per_headg_proj)r/   rP   r  r  
g_proj_dimr1   s        r2   r)   zLagunaAttention.__init__W  s   ""
F4F4F&JdJd4de$(NNf6P6P$P!}}d*!'!9!9ii 2 2DNNT]]4RY_YnYnoii : :T]] JQWQfQf
 ii : :T]] JQWQfQf
 ii >@R@RY_YnYno #)"4"4Y"?CV"V7;7N7Nf33TX#DMMv7J7JK#DMMv7J7JK#]]d2Qfmmz6Q'+'9'9T^^t~~PTP]P]?]
ii 2 2JUKr3   Nr4   position_embeddingsr  past_key_valuesr	  r&   c                    |j                   d d }g |d| j                  }| j                  |      j                  |      }| j	                  |      j                  |      }	| j                  |      j                  |      }
| j                  |      j                  dd      }| j                  |	      j                  dd      }	|
j                  dd      }
|\  }}t        ||	||      \  }}	| |j                  |	|
| j                        \  }	}
t        j                  | j                  j                  t               } || ||	|
|f| j"                  sdn| j$                  | j&                  | j(                  d|\  }} |j*                  g |d j-                         }t/        j0                  | j3                  |      j5                               j7                  |j8                        }| j:                  rE  |j                  g |d| j                   |j=                  d      z  j                  g |d }n||z  }| j?                  |      }||fS )Nr7   r    r6   r   )r  r  r%  ) rD   rn   r   r   r!  r"  r'  r   r(  r   updater  r   get_interfacerP   _attn_implementationr  r  r  r  r%  r   r  r   softplusr+  rI   r:   r9   r*  r   r#  )r/   r4   r-  r  r.  r	  input_shapehidden_shapequery_statesr  r  r   r   attention_interfacer  r  r   s                    r2   rA   zLagunaAttention.forwardv  sN    $))#2.88b8$--8{{=166|D[[/44\B
{{=166|D{{<0::1a@[[,66q!<
#--a3&S#7jRUWZ#[ j&'6'='=j,X\XfXf'g$J(?(M(MKK,,.E)
 %8
%
  $}}C$2H2HLL..
%
 
%
!\ *k));;;;FFHzz$++m4::<=@@ARARSg+;++L[L"LdmmLt~~^`Oaagg  K &,Kkk+.L((r3   r   )rF   rG   rH   r   r!   rs   r)   r+   rJ   rC   r	   r   r   rA   rK   rL   s   @r2   r  r  T  s    ]L| L L LH )-3)||3) #5<<#=>3) t+	3)
 3) -.3) 
u||U\\D00	13)r3   r  c                       e Zd Zdedef fdZ	 	 	 	 	 ddej                  dej                  dz  dej                  dz  de	dz  d	e
dz  d
eej                  ej                  f   dz  dee   dej                  fdZ xZS )LagunaDecoderLayerrP   r  c                    t         |           |j                  | _        t        |||j                  |         | _        |j                  |   dk(  rt        |      | _        nt        ||j                        | _        t        |j                  |j                        | _        t        |j                  |j                        | _        y )Nsparser   r  )r(   r)   r0   r  num_attention_heads_per_layer	self_attnmlp_layer_typesr   mlpr   r   r$   r&  input_layernormpost_attention_layernormr/   rP   r  r1   s      r2   r)   zLagunaDecoderLayer.__init__  s    !--(F<`<`aj<kl!!),8+F3DH 6;S;STDH,V-?-?VEXEXY(5f6H6HfNaNa(b%r3   Nr4   r  r   r.  	use_cacher-  r	  r&   c           
          |}| j                  |      } | j                  d||||||d|\  }}	||z   }|}| j                  |      }| j                  |      }||z   }|S )N)r4   r  r   r.  rC  r-   )r@  r=  rA  r?  )
r/   r4   r  r   r.  rC  r-  r	  residualr   s
             r2   rA   zLagunaDecoderLayer.forward  s     !,,];)4>> 
')%+ 3
 
q !=0 !55mD/ =0r3   )NNNFN)rF   rG   rH   r!   rs   r)   r+   rJ   
LongTensorr	   boolrC   r   r   rA   rK   rL   s   @r2   r9  r9    s    	c| 	c 	c /304(,!&HL|| t+ &&-	
  $; #5<<#=>E +, 
r3   r9  c                        e Zd ZU eed<   dZdZdgZdgZdZ	dZ
dZdZdZ eed      eedZ ej(                          fd	       Z xZS )
LagunaPreTrainedModelrP   modelTr9  r.  r   )index)r   r4   
attentionsc                 L   t         |   |       | j                  j                  }t	        |t
              rEt        j                  |j                  d|       t        j                  |j                  d|       n2t	        |t              r"t        j                  |j                  d|       t	        |t              r4t        j                  j                  j                  |j                         y t	        |t               r|j"                  D ]  }|j$                  }|j&                  |   dk7  rt(        |j&                  |      } ||j                  |      \  }}t        j*                  t-        || d      |       t        j*                  t-        || d      |        y y )Nr   )r=   stdrS   rT   rV   rX   )r(   _init_weightsrP   initializer_ranger   r   initnormal_r   r   r   r-   r+   r   zeros_r   rN   r_   ra   rR   r   copy_rq   )r/   r  rO  rU   rf   rg   r   r1   s          r2   rP  z#LagunaPreTrainedModel._init_weights  sC   f%kk++fm,LL,,3C@LL))= 01LLSc:f./HHMM  !?!?@ 56$00 ^
%EE##J/9<#6v7G7G
7S#TL#/*#U q

76j\+CDmT

76j\9K+LM}]^ 7r3   )rF   rG   rH   r!   r   base_model_prefixsupports_gradient_checkpointing_no_split_modules_skip_keys_device_placement_supports_flash_attn_supports_sdpa_supports_flex_attn_can_compile_fullgraph_supports_attention_backendr   r   r9  r  _can_record_outputsr+   r   rP  rK   rL   s   @r2   rJ  rJ    s{    &*#-.#4"5N!"&'(8B+% U]]_^ ^r3   rJ  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 )LagunaModelrP   c           	         t         |   |       |j                  | _        |j                  | _        t        j                  |j                  |j                  | j                        | _        t        j                  t        |j                        D cg c]  }t        ||       c}      | _        t        |j                  |j                        | _        t#        |      | _        d| _        | j)                          y c c}w )Nr  rP   F)r(   r)   pad_token_idpadding_idx
vocab_sizer   	Embeddingr0   embed_tokens
ModuleListrangenum_hidden_layersr9  layersr$   r&  normrN   
rotary_embgradient_checkpointing	post_initrB  s      r2   r)   zLagunaModel.__init__  s     !.. ++LL):):F<N<NPTP`P`ammDI&JbJbDcdy	2d
 "&"4"4&:M:MN	/v>&+# 	 es   DN	input_idsr  r   r.  inputs_embedsrC  r	  r&   c           	         |d u |d uz  rt        d      || j                  |      }|r|t        | j                        }|V||j	                         nd}t        j                  |j                  d   |j                        |z   }|j                  d      }t        |x}	t              sP| j                  ||||dfdfdd	}
i }	t        | j                  j                        D ]  } |
|          |	|<    |}i }t        | j                  j                        D ]  }| j                  |||      ||<    t        | j                   d | j                  j"                         D ]G  \  }} ||f|	| j                  j                  |      || j                  j                  |      ||d
|}I | j%                  |      }t'        ||r|      S d       S )Nz:You must specify exactly one of input_ids or inputs_embedsrc  r   r    )ri   )rP   rr  r  r.  r   c                      t        di  S NrE  )r   mask_kwargss   r2   <lambda>z%LagunaModel.forward.<locals>.<lambda>6  s    *<*K{*K r3   c                      t        di  S ru  )r   rv  s   r2   rx  z%LagunaModel.forward.<locals>.<lambda>7  s    -N-]Q\-] r3   )full_attentionr  )r  r-  r   r.  )last_hidden_stater.  )
ValueErrorrh  r
   rP   get_seq_lengthr+   rt   rD   ri   r   r   dictr^   r_   rn  	enumeraterl  rk  rm  r   )r/   rq  r  r   r.  rr  rC  r	  past_seen_tokenscausal_mask_mappingmask_creation_functionsrU   r4   r-  idecoder_layerrw  s                   @r2   rA   zLagunaModel.forward  s    -t";<YZZ  --i8M0*$++>OCRC^==?de <<(;(;A(>}G[G[\_ooL'11!4L?-F++!."0#2 ,K #L%]'# #%!$++"9"9: X
2U2I*2U2W#J/X & dkk556 	gJ.2oom\[e.f
+	g !*$++6U8U8U*V W 	A})24;;3J3J13MN$78O8OPQ8R$S) / M	 		-0%+/8O
 	
>B
 	
r3   )NNNNNN)rF   rG   rH   r!   r)   r   r   r   r+   rG  rJ   r	   FloatTensorrH  r   r   r   rA   rK   rL   s   @r2   ra  ra     s    |     .2.204(,26!%<
##d*<
 t+<
 &&-	<

 <
 ((4/<
 $;<
 +,<
 
 <
    <
r3   ra  gate_logitsr   c                    | t        | t              syt        | t              rC| d   j                  }t        j                  | D cg c]  }|j                  |       c}d      }t        j                  j                  j                  d      }t        j                  ||d      \  }}	t        j                  j                  j                  |	|      }
|>t        j                  |
j                         d      }t        j                  |d      }n|j                  \  }}|j                  d   ||z  z  }|dddddddf   j                  |||||f      j                  d||      j                        }t        j                   |
j                         |z  d      t        j                   |d      z  }|ddddddf   j                  ||||f      j                  d|      j                  |      }t        j                   ||z  d      t        j                   |d      z  }t        j                   ||j#                  d      z        }||z  S c c}w )a  
    Computes auxiliary load balancing loss as in Switch Transformer - implemented in Pytorch.

    See Switch Transformer (https://huggingface.co/papers/2101.03961) for more details. This function implements the loss
    function presented in equations (4) - (6) of the paper. It aims at penalizing cases where the routing between
    experts is too unbalanced.

    Args:
        gate_logits:
            Logits from the `gate`, should be a tuple of model.config.num_hidden_layers tensors of
            shape [batch_size X sequence_length, num_experts].
        num_experts:
            Number of experts
        top_k:
            The number of experts to route per-token, can be also interpreted as the `top-k` routing
            parameter.
        attention_mask (`torch.Tensor`, *optional*):
            The attention_mask used in forward function
            shape [batch_size X sequence_length] if not None.

    Returns:
        The auxiliary loss.
    Nr   r~   r7   )r   rC   ri   r+   r   r:   r   r   r  r   r   r=   rI   rD   r   r   r   r   )r  r   r   r  compute_device
layer_gateconcatenated_gate_logitsr   r   r   r   tokens_per_expertrouter_prob_per_expertr   r   rk  expert_attention_mask router_per_expert_attention_maskoverall_losss                      r2   load_balancing_loss_funcr  T  s9   : *[%"@+u%$Q..#(99^i-jPZjmmN.K-jpq#r hh))112JPR1SO**_eDA((%%--.>LK!JJ{'8'8':B "'O!C&4&:&:#
O4::1=*B^_ 4AtT12V&
OUKXYWR,R	 	 "IIk&7&7&9<Q&QWXY\a\e\e!q]
 
 4At+,V&
O[QRWR%R	 	) "'?=]+]cd!ehmhqhq,!i
 "
 99.1G1Q1QRS1TTUL+%%[ .ks   Ic                   N    e Zd ZddiZddiZddgdgfiZ 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dz  dee	j                  z  dee   defd              Z xZS )LagunaForCausalLMzlm_head.weightzmodel.embed_tokens.weightlm_headcolwise_gather_outputr4   logitsc                 N   t         |   |       t        |      | _        |j                  | _        t        j                  |j                  |j                  d      | _        |j                  | _	        |j                  | _
        |j                  | _        | j                          y r   )r(   r)   ra  rK  rf  r   r   r0   r  router_aux_loss_coefr   r   rp  r   s     r2   r)   zLagunaForCausalLM.__init__  s      (
 ++yy!3!3V5F5FUS$*$?$?!!--#)#=#=  	r3   Nrq  r  r   r.  rr  labelsrC  output_router_logitslogits_to_keepr	  r&   c
                 j   ||n| j                   j                  } | j                  d|||||||d|
}|j                  }t	        |	t
              rt        |	 d      n|	}| j                  |dd|ddf         }d}| | j                  ||| j                  fi |
}d}|rYt        |j                  | j                  | j                  |      }|+|| j                  |j                  |j                         z  z  }t#        ||||j$                  |j&                  |j(                  |j                        S )a  
        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]`.
        N)rq  r  r   r.  rr  rC  r  )lossaux_lossr  r.  r4   rM  r   rE  )rP   r  rK  r{  r   rs   slicer  loss_functionrf  r  r   r   r   r  r:   ri   r   r.  r4   rM  )r/   rq  r  r   r.  rr  r  rC  r  r  r	  outputsr4   slice_indicesr  r  r  s                    r2   rA   zLagunaForCausalLM.forward  sT   . %9$D $++JjJj 	
 +5$** 	+
)%+'!5	+
 	+
  118B>SV8W~ot4]kmA}a,?@A%4%%ffdooPPD/%%  ((	H !11HKK4LLL(#33!//))!//
 	
r3   )	NNNNNNNNr   )rF   rG   rH   _tied_weights_keys_tp_plan_pp_planr)   r   r   r+   rG  rJ   r	   r  rH  rs   r   r   r   rA   rK   rL   s   @r2   r  r    s5   *,GH23H_-z:;H
  .2.204(,26*.!%,0-.@
##d*@
 t+@
 &&-	@

 @
 ((4/@
   4'@
 $;@
 #Tk@
 ell*@
 +,@
 
#@
  @
r3   r  )r  ra  rJ  )r    )r   )Nr6   N)Jcollections.abcr   typingr   r+   torch.nn.functionalr   r   r    r   rR  activationsr   cache_utilsr	   r
   
generationr   integrationsr   r   masking_utilsr   r   modeling_flash_attention_utilsr   modeling_layersr   modeling_outputsr   r   modeling_rope_utilsr   r   modeling_utilsr   r   processing_utilsr   utilsr   r   utils.genericr   r   r   utils.output_capturingr   r   configuration_lagunar!   Moduler$   rN   r   r   r   r   r   r   rJ   rs   r  rI   r  r  r9  rJ  ra  rC   r  r  __all__rE  r3   r2   <module>r     so  * %      & ! . ) S R B 9 Q K F & 5 [ [ E . Y'JBII J (J(M<BII M<`		  @ryy @> $#BII $# $#N299 .(#L	UU\\ 	U# 	U%,, 	U& %II%<<% 
% <<	%
 LL4'% % % '(%2U)bii U)p)3 )X $^O $^ $^N P
' P
 P
j #
*.	O&ell 33d:O&tO& LL4'	O&
 \\CO&d S
- S
 S
l Hr3   