
    i                     h   d dl Z d dlmZ d dlm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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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( ddl)m*Z*m+Z+m,Z,m-Z- ddl.m/Z/m0Z0 ddl1m2Z2  e-jf                  e4      Z5 G d dejl                        Z7 G d dejl                        Z8d Z9 ed      d;d       Z:dejv                  de<dejv                  fd Z=d! Z> G d" d#ejl                        Z? G d$ d%e?      Z@ G d& d'e?      ZA ed(       G d) d*ejl                               ZBe?e@eAd+ZC G d, d-e      ZDe+ G d. d/e&             ZEe+ G d0 d1eE             ZFe+ G d2 d3eEe             ZG G d4 d5eeE      ZH G d6 d7eeE      ZI G d8 d9eeE      ZJg d:ZKy)<    N)Callable)Optional)nn   )initialization)ACT2FN)CacheDynamicCacheStaticCache)GenerationMixin)use_kernel_forward_from_hubuse_kernel_func_from_hub)create_causal_mask)_flash_attention_forward!flash_attn_supports_top_left_mask)GenericForQuestionAnswering GenericForSequenceClassificationGenericForTokenClassificationGradientCheckpointingLayer)BaseModelOutputWithPastCausalLMOutputWithPast)ROPE_INIT_FUNCTIONSdynamic_rope_update)PreTrainedModel)Unpack)TransformersKwargsauto_docstringcan_return_tuplelogging)check_model_inputsmaybe_autocast   )DiffLlamaConfigc                   $     e Zd Z fdZd Z xZS )DiffLlamaMLPc                    t         |           || _        |j                  | _        |j                  | _        t        j                  | j                  | j                  d      | _        t        j                  | j                  | j                  d      | _        t        j                  | j                  | j                  d      | _	        t        |j                     | _        y NFbias)super__init__confighidden_sizeintermediate_sizer   Linear	gate_projup_proj	down_projr   
hidden_actact_fnselfr,   	__class__s     z/home/obispo/Crisostomo_bridge/mision_env/lib/python3.12/site-packages/transformers/models/diffllama/modeling_diffllama.pyr+   zDiffLlamaMLP.__init__8   s    !--!'!9!94#3#3T5K5KRWXyy!1!143I3IPUV4#9#94;K;KRWXV../    c                     | j                  | j                  | j                  |            | j                  |      z        }|S N)r2   r4   r0   r1   )r6   xr2   s      r8   forwardzDiffLlamaMLP.forwardB   s6    NN4;;t~~a/@#ADLLQRO#ST	r9   )__name__
__module____qualname__r+   r=   __classcell__r7   s   @r8   r%   r%   7   s    0r9   r%   c                        e Zd ZU ej                  ed<   ddef fdZe	 	 	 ddedz  de	d   de
dz  ded	ef   fd
       Z ej                         ed               Z xZS )DiffLlamaRotaryEmbeddinginv_freqNr,   c                    t         |           |j                  | _        |j                  | _        || _        | j
                  j                  d   | _        | j                  }| j                  dk7  rt        | j                     } || j
                  |      \  }| _
        | j                  d|d       | j                  d|j                         d       y )N	rope_typedefaultrE   F)
persistentoriginal_inv_freq)r*   r+   max_position_embeddingsmax_seq_len_cachedoriginal_max_seq_lenr,   rope_parametersrG   compute_default_rope_parametersr   attention_scalingregister_bufferclone)r6   r,   devicerope_init_fnrE   r7   s        r8   r+   z!DiffLlamaRotaryEmbedding.__init__J   s    "("@"@$*$B$B!44[A!%!E!E>>Y&.t~~>L+7V+L($(ZeD0(..2BuUr9   rS   ztorch.deviceseq_lenreturnztorch.Tensorc                    | j                   d   }t        | dd      xs | j                  | j                  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.
        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head_dimNg      ?r      dtype)rS   r\   )	rN   getattrr-   num_attention_headstorcharangeint64tofloat)r,   rS   rU   basedimattention_factorrE   s          r8   rO   z8DiffLlamaRotaryEmbedding.compute_default_rope_parametersZ   s    & %%l3fj$/c63E3EIcIc3c U\\!S!5;;?BB&X]XcXcBdgjjk
 )))r9   c                 N   | j                   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                         | j                  z  }|j                         | j                  z  }	d d d        j	                  |j                   
      	j	                  |j                   
      fS # 1 sw Y   AxY w)Nr   r"   mpscpuF)device_typeenabledrZ   re   r[   )rE   rc   expandshaperb   rS   
isinstancetypestrr!   	transposer_   catcosrP   sinr\   )
r6   r<   position_idsinv_freq_expandedposition_ids_expandedrk   freqsembru   rv   s
             r8   r=   z DiffLlamaRotaryEmbedding.forwardx   sR    !MM$4-8>>@GGHZHZ[\H]_acdehhijiqiqr ,QaZ 8 > > @'1!((--'E!((--[`J`ahhmmfkUC 	5&,,.1F1L1L1NNYYZ[]^_E))UEN3C'')d444C'')d444C		5 vvAGGv$cff177f&;;;	5 	5s   BFF$r;   )NNN)r>   r?   r@   r_   Tensor__annotations__r#   r+   staticmethodr   inttuplerc   rO   no_gradr   r=   rA   rB   s   @r8   rD   rD   G   s    llV V  )-+/"*$&*(* t* 
~u$	%	* *: U]]_<  <r9   rD   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..Nrh   rZ   rm   )ro   r_   rt   )r<   x1x2s      r8   rotate_halfr      sZ    	
3"!''"+"""	#B	
3q ""	#B99rc2YB''r9   rotary_pos_embc                     |j                  |      }|j                  |      }| |z  t        |       |z  z   }||z  t        |      |z  z   }||fS )a  Applies Rotary Position Embedding to the query and key tensors.

    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.
    )	unsqueezer   )qkru   rv   unsqueeze_dimq_embedk_embeds          r8   apply_rotary_pos_embr      sY    & --
&C
--
&C3w;q>C/0G3w;q>C/0GGr9   hidden_statesn_reprV   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)ro   rn   reshape)r   r   batchnum_key_value_headsslenrY   s         r8   	repeat_kvr      so    
 2?1D1D.Ehz!!Qa"23::5BUW\^bdlmM  (;e(CT8TTr9   c                 >    ddt        j                  d| z        z  z
  S )Ng?g333333?g333333ӿ)mathexp)	layer_idxs    r8   lambda_init_fnr      s     txxy 01111r9   c                   \    e Zd ZdZddededz  f fdZ	 	 	 	 	 ddej                  de	ej                  ej                  f   dej                  dz  d	ej                  dz  d
edz  dedej                  dz  de	ej                  ej                  dz  e	ej                     dz  f   fdZ xZS )DiffLlamaAttentionz=Multi-headed attention from 'Attention Is All You Need' paperNr,   r   c                    t         |           || _        || _        |-t        j                  d| j                  j                   d       |j                  | _        |j                  | _	        |j                  | _        t        |d| j                  | j                  z        | _        |j                  | _        | j                  | j                  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(                        | _        t3        |      | _        t%        j6                  t9        j:                  d|j<                  | j                  f            | _        t%        j6                  t9        j:                  d|j<                  | j                  f            | _         t%        j6                  t9        j:                  d|j<                  | j                  f            | _!        t%        j6                  t9        j:                  d|j<                  | j                  f            | _"        t%        jF                  d| j                  z  |jH                  d	
      | _%        y )NzInstantiating z without passing a `layer_idx` is not recommended and will lead to errors during the forward call if caching is used. Please make sure to provide a `layer_idx` when creating this class.rY   Tr(   r   )sizerZ   F)epselementwise_affine)&r*   r+   r,   r   loggerwarning_oncer7   r>   attention_dropoutr-   r^   	num_headsr]   rY   r   num_key_value_groupsrK   	is_causalr   r/   attention_biasq_projk_projv_projo_projr   lambda_init	Parameterr_   normallambda_std_dev	lambda_q1	lambda_k1	lambda_q2	lambda_k2RMSNormrms_norm_eps	groupnormr6   r,   r   r7   s      r8   r+   zDiffLlamaAttention.__init__   sq   " !8!8 9 :, , "(!9!9!--33
D4D4D4VW#)#=#= $(NNd6N6N$N!'-'E'E$ii 0 0$..4==2PW]WlWlmii 0 0$2J2JT]]2Zagavavwii 0 0$2J2JT]]2Zagavavwii >@P@PW]WlWlm))4ell1f6K6KSWS`S`Rb&cdell1f6K6KSWS`S`Rb&cdell1f6K6KSWS`S`Rb&cdell1f6K6KSWS`S`Rb&cdA$56;N;Nchir9   r   position_embeddingsattention_maskrw   past_key_values	use_cachecache_positionrV   c                    |j                         \  }	}
}|
}| j                  |      }| j                  |      }| j                  |      }|j	                  |	|| j
                  | j                        j                  dd      }|j	                  |	|| j                  | j                        j                  dd      }|j	                  |	|| j                  | j                        j                  dd      }|\  }}t        ||||      \  }}|'|||d}|j                  ||| j                  |      \  }}t        || j                        }t        || j                        }t        j                  t        j                   |dd      d      }|j#                  dddd      }t        j$                  ||j                  dd            t'        j(                  | j                        z  }|#|d d d d d d d |j*                  d   f   }||z   }t,        j.                  j1                  |dt        j2                        j5                  |j6                        }t,        j.                  j9                  || j:                  | j<                  	      }t        j>                  t        j@                  | jB                  | jD                  z  dt        j2                              j5                  |j6                        }t        j>                  t        j@                  | jF                  | jH                  z  dt        j2                              j5                  |j6                        }||z
  | jJ                  z   }t        j$                  ||      }t        j                   |dd      \  }}|||z  z
  }d| jJ                  z
  | jM                  |      z  }|j                  dd      jO                         }|jQ                  |	|d      }| jS                  |      }||fS )
Nr"   rZ   rv   ru   r   rm   rh   r   re   r\   )ptraining)*r   r   r   r   viewr   rY   rs   r   r   updater   r   r   r_   rt   chunkrepeatmatmulr   sqrtro   r   
functionalsoftmaxfloat32rb   r\   dropoutr   r   r   sumr   r   r   r   r   r   
contiguousr   r   )r6   r   r   r   rw   r   r   r   kwargsbsz
target_len_q_lenquery_states
key_statesvalue_statesru   rv   cache_kwargsattn_weightscausal_masklambda_1lambda_2lambda_fullattn_outputattn_output1attn_output2s                              r8   r=   zDiffLlamaAttention.forward   s|    +//1Z{{=1[[/
{{=1#((eT^^T]]S]]^_abc__S%1I1I4==Yccdeghi
#((eT5M5Mt}}]gghiklm&S#7jRUWZ#[ j&#&snUL'6'='=j,X\XfXfht'u$Jz4+D+DE
 t/H/HIyy\1!!D"M#**1aA6||L*2F2Fq!2LMPTPYPYZ^ZgZgPhh%(Aq2HJ4D4DR4H2H)HIK'+5L }},,\r,WZZ[g[m[mn}},,\T=S=S^b^k^k,l99UYYt~~'FBV[VcVcdehh
 99UYYt~~'FBV[VcVcdehh
 )D,<,<<ll<>%*[[aQ%G"l"[<%??4+++t~~k/JJ!++Aq1<<>!))#ub9kk+.L((r9   r;   NNNFN)r>   r?   r@   __doc__r#   r   r+   r_   r|   r   
LongTensorr	   boolr=   rA   rB   s   @r8   r   r      s    Gj j3: jJ /304(,26<)||<) #5<<#=><) t+	<)
 &&-<) <) <) ((4/<) 
u||U\\D0%2E2LL	M<)r9   r   c                       e Zd ZdZ fdZ	 	 	 	 	 ddej                  deej                  ej                  f   dej                  dz  dej                  dz  de	dz  d	e
d
ej                  dz  deej                  df   fdZ xZS )DiffLlamaFlashAttention2aN  
    DiffLlama flash attention module. This module inherits from `DiffLlamaAttention` as the weights of the module stays
    untouched. The only required change would be on the forward pass where it needs to correctly call the public API of
    flash attention and deal with padding tokens in case the input contains any of them.
    c                 B    t        |   |i | t               | _        y r;   )r*   r+   r   _flash_attn_uses_top_left_mask)r6   argsr   r7   s      r8   r+   z!DiffLlamaFlashAttention2.__init__#  s#    $)&)
 /P.Q+r9   Nr   r   r   rw   r   r   r   rV   c                 	   t        |t              rt        d      |j                         \  }}	}
| j	                  |      }| j                  |      }| j                  |      }|j                  ||	| j                  | j                        j                  dd      }|j                  ||	| j                  | j                        j                  dd      }|j                  ||	| j                  | j                        j                  dd      }|\  }}t        ||||      \  }}|'|||d}|j                  ||| j                  |      \  }}|j                  dd      }|j                  dd      }|j                  dd      }| j                  r| j                   nd}|j"                  }|j$                  j&                  dk7  r|j$                  j&                  nd}|t(        j*                  k(  rt)        j,                         rt)        j.                  |      }nMt1        | j2                  d      r| j2                  j"                  }n | j                  j4                  j"                  }t6        j9                  d	| d
       |j;                  |      }|j;                  |      }|j;                  |      }t)        j<                  |dd      \  }}|j?                  dddd      }|j?                  dddd      }tA        |||||	||tC        | dd       | jD                  | jF                  
      }tA        |||||	||tC        | dd       | jD                  | jF                  
      }t)        jH                  ||gd      }t)        j<                  |dd      \  }}t)        jJ                  t)        jL                  | jN                  | jP                  z  dt(        j*                              j;                  |j"                        }t)        jJ                  t)        jL                  | jR                  | jT                  z  dt(        j*                              j;                  |j"                        }||z
  | jV                  z   }|||z  z
  }d| jV                  z
  | jY                  |      z  }|j[                  ||	d      j]                         }| j_                  |      }|d fS )Nz`static` cache implementation is not compatible with `attn_implementation==flash_attention_2` make sure to use `sdpa` in the mean time, and open an issue at https://github.com/huggingface/transformersr"   rZ   r           ri   rj   _is_quantizedzThe input hidden states seems to be silently casted in float32, this might be related to the fact you have upcasted embedding or layer norm layers in float32. We will cast back the input in .rm   sliding_window)rw   r   r   use_top_left_maskr   rh   r   )0rp   r   
ValueErrorr   r   r   r   r   r   rY   rs   r   r   r   r   r   r   r\   rS   rq   r_   r   is_autocast_enabledget_autocast_dtypehasattrr,   weightr   r   rb   r   r   r   r]   r   r   rt   r   r   r   r   r   r   r   r   r   r   r   )r6   r   r   r   rw   r   r   r   r   r   r   r   r   r   ru   rv   r   dropout_rateinput_dtyperk   target_dtypevalue_states1value_states2r   r   r   r   r   r   s                                r8   r=   z DiffLlamaFlashAttention2.forward+  sR    o{3} 
 &**,UA{{=1[[/
{{=1
 $((eT^^T]]S]]^_abc__S%1I1I4==Yccdeghi
#((eT5M5Mt}}]gghiklm&S#7jRUWZ#[ j&#&snUL'6'='=j,X\XfXfht'u$J $--a3))!Q/
#--a315t--C #((2>2E2E2J2Je2Sl))..Y^%--'((*$77Do6#{{00#{{1177 >$ (??<8L#|4J'??<8L',{{<'J$}%,,Q1a8%,,Q1a8/% "4)94@"AAnn
 0% "4)94@"AAnn
 ii| <"E%*[[aQ%G"l99UYYt~~'FBV[VcVcdehh
 99UYYt~~'FBV[VcVcdehh
 )D,<,<<"[<%??4+++t~~k/JJ!))#ub9DDFkk+.D  r9   r   )r>   r?   r@   r   r+   r_   r|   r   r   r	   r   r=   rA   rB   s   @r8   r   r     s    R 3704(,26u!||u! #5<<#=>u! ((4/	u!
 &&-u! u! u! ((4/u! 
u||T!	"u!r9   r   c                   8   e Zd ZdZ	 	 	 	 	 ddej
                  deej
                  ej
                  f   dej
                  dz  dej                  dz  dedz  de	d	ej                  dz  d
eej
                  ej
                  dz  eej
                     dz  f   fdZ
y)DiffLlamaSdpaAttentiona   
    DiffLlama attention module using torch.nn.functional.scaled_dot_product_attention. This module inherits from
    `DiffLlamaAttention` as the weights of the module stays untouched. The only changes are on the forward pass to adapt to
    SDPA API.
    Nr   r   r   rw   r   r   r   rV   c                    |j                         \  }	}
}| j                  |      }| j                  |      }| j                  |      }|j	                  |	|
| j
                  | j                        j                  dd      }|j	                  |	|
| j                  | j                        j                  dd      }|j	                  |	|
| j                  | j                        j                  dd      }|\  }}t        ||||      \  }}|'|||d}|j                  ||| j                  |      \  }}t        || j                        }t        || j                        }t        j                  t        j                   |dd      d      }|j#                  dddd      }|}||d d d d d d d |j$                  d   f   }|j&                  j(                  dv r2|0|j+                         }|j+                         }|j+                         }|d u xr |
dkD  }t        j,                  j.                  j1                  ||||| j2                  r| j4                  nd|	      }t        j                   |dd      \  }}t        j6                  t        j8                  | j:                  | j<                  z  dt        j>                  
            jA                  |jB                        }t        j6                  t        j8                  | jD                  | jF                  z  dt        j>                  
            jA                  |jB                        }||z
  | jH                  z   }|||z  z
  }d| jH                  z
  | jK                  |      z  }|j                  dd      j+                         }|j	                  |	|
d      }| jM                  |      }|d fS )Nr"   rZ   r   rm   rh   r   )cudaxpur   )	attn_mask	dropout_pr   r   )'r   r   r   r   r   r   rY   rs   r   r   r   r   r   r   r_   rt   r   r   ro   rS   rq   r   r   r   scaled_dot_product_attentionr   r   r   r   r   r   r   rb   r\   r   r   r   r   r   )r6   r   r   r   rw   r   r   r   r   r   r   r   r   r   r   ru   rv   r   r   r   r   r   r   r   r   r   s                             r8   r=   zDiffLlamaSdpaAttention.forward  sm    &**,UA{{=1[[/
{{=1#((eT^^T]]S]]^_abc__S%1I1I4==Yccdeghi
#((eT5M5Mt}}]gghiklm&S#7jRUWZ#[ j&#&snUL'6'='=j,X\XfXfht'u$Jz4+D+DE
 t/H/HIyy\1!!D"M#**1aA6$%%aA/E1A1A"1E/E&EFK ##6;;R'224L#..0J'224L  4'5EAI	hh))FF!04d,,3 G 
 &+[[aQ%G"l99UYYt~~'FBV[VcVcdehh
 99UYYt~~'FBV[VcVcdehh
 )D,<,<<"[<%??4+++t~~k/JJ!++Aq1<<>!&&sE26kk+.D  r9   r   )r>   r?   r@   r   r_   r|   r   r   r	   r   r=    r9   r8   r   r     s     /304(,26I!||I! #5<<#=>I! t+	I!
 &&-I! I! I! ((4/I! 
u||U\\D0%2E2LL	MI!r9   r   r   c                   ,     e Zd Zd fd	Zd Zd Z xZS )DiffLlamaRMSNormc                     t         |           t        j                  t	        j
                  |            | _        || _        y)z?
        DiffLlamaRMSNorm is equivalent to T5LayerNorm
        N)r*   r+   r   r   r_   onesr   variance_epsilon)r6   r-   r   r7   s      r8   r+   zDiffLlamaRMSNorm.__init__  s1     	ll5::k#:; #r9   c                 "   |j                   }|j                  t        j                        }|j	                  d      j                  dd      }|t        j                  || j                  z         z  }| j                  |j                  |      z  S )NrZ   rh   T)keepdim)	r\   rb   r_   r   powmeanrsqrtr  r   )r6   r   r   variances       r8   r=   zDiffLlamaRMSNorm.forward  sy    #))%((7 $$Q',,R,>%Ht?T?T4T(UU{{]--k:::r9   c                 ^    t        | j                  j                         d| j                   S )Nz, eps=)r   r   ro   r  )r6   s    r8   
extra_reprzDiffLlamaRMSNorm.extra_repr  s*    ))*+6$2G2G1HIIr9   )gư>)r>   r?   r@   r+   r=   r  rA   rB   s   @r8   r  r    s    $;Jr9   r  )eagerflash_attention_2sdpac                   "    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j                  dz  deej                  ej                  f   dz  dee   dej                  fdZ xZS )DiffLlamaDecoderLayerr,   r   c                 :   t         |           |j                  | _        t        |j                     ||      | _        t        |      | _        t        |j                  |j                        | _
        t        |j                  |j                        | _        y )N)r,   r   r   )r*   r+   r-   DIFFLLAMA_ATTENTION_CLASSES_attn_implementation	self_attnr%   mlpr  r   input_layernormpost_attention_layernormr   s      r8   r+   zDiffLlamaDecoderLayer.__init__  sz    !--4V5P5PQY_ktu'/0B0BH[H[\(89K9KQWQdQd(e%r9   Nr   r   rw   r   r   r   r   r   rV   c                     |}	| j                  |      } | j                  d|||||||d|\  }}
|	|z   }|}	| j                  |      }| j                  |      }|	|z   }|S )N)r   r   rw   r   r   r   r   r  )r  r  r  r  )r6   r   r   rw   r   r   r   r   r   residualr   s              r8   r=   zDiffLlamaDecoderLayer.forward  s     !,,];)4>> 	
')%+) 3	
 	
q !=0 !55mD/ =0r9   )NNNFNN)r>   r?   r@   r#   r   r+   r_   r|   r   r	   r   r   r   r   r=   rA   rB   s   @r8   r  r    s    f f3 f /304(,!&26HL|| t+ &&-	
  $; ((4/ #5<<#=>E +, 
r9   r  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Z ej$                          fd       Z xZS )	DiffLlamaPreTrainedModelr,   modelTr  r   F)r   
attentionsc                    t         |   |       t        |t              rt	        j
                  |j                  d| j                  j                         t	        j
                  |j                  d| j                  j                         t	        j
                  |j                  d| j                  j                         t	        j
                  |j                  d| j                  j                         y y )Nr   )r*   _init_weightsrp   r   initnormal_r   r,   r   r   r   r   )r6   moduler7   s     r8   r$  z&DiffLlamaPreTrainedModel._init_weightsR  s    f%f01LL))1dkk.H.HILL))1dkk.H.HILL))1dkk.H.HILL))1dkk.H.HI	 2r9   )r>   r?   r@   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   _can_record_outputsr_   r   r$  rA   rB   s   @r8   r   r   @  sp    &*#01#4"5N!"'.(
 U]]_J Jr9   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   defd              Z xZS )DiffLlamaModelr,   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  r,   F)r*   r+   pad_token_idpadding_idx
vocab_sizer   	Embeddingr-   embed_tokens
ModuleListrangenum_hidden_layersr  layersr  r   normrD   
rotary_embgradient_checkpointing	post_initr   s      r8   r+   zDiffLlamaModel.__init__^  s     !.. ++LL):):F<N<NPTP`P`ammGLVMeMeGfg)"695g
 %V%7%7V=P=PQ	2&A&+# 	 hs   DN	input_idsr   rw   r   inputs_embedsr   r   r   rV   c                 D   |d u |d uz  rt        d      || j                  |      }|r|t        | j                        }|E||j	                         nd}	t        j                  |j                  d   |j                        |	z   }||j                  d      }t        | j                  |||||      }
|}| j                  ||      }| j                  d | j                  j                   D ]  } ||f|
|||||d|} | j                  |      }t        ||	      S )
Nz:You must specify exactly one of input_ids or inputs_embedsr5  r   r"   )rS   )r,   input_embedsr   r   r   rw   )rw   )r   r   rw   r   r   r   )last_hidden_stater   )r   r:  r
   r,   get_seq_lengthr_   r`   ro   rS   r   r   r@  r>  r=  r?  r   )r6   rC  r   rw   r   rD  r   r   r   past_seen_tokensr   r   r   decoder_layers                 r8   r=   zDiffLlamaModel.forwardn  s]    -t";<YZZ *.*;*;I*FM0*$++>O!CRC^==?de]003M<P<PQTdd  )33A6L(;;&))+%
 &"oom,oW![[)H4;;+H+HI 
	M)	*$7) /#-	 	M
	 		-0&++
 	
r9   )NNNNNNN)r>   r?   r@   r#   r+   r    r   r_   r   r|   r	   FloatTensorr   r   r   r   r=   rA   rB   s   @r8   r3  r3  \  s        .2.204(,2626!%9
##d*9
 t+9
 &&-	9

 9
 ((4/9
 ((4/9
 $;9
 +,9
 
!9
  9
r9   r3  c                   b    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	j                  dz  dee	j                  z  dee   defd              Z xZS )DiffLlamaForCausalLMzlm_head.weightzmodel.embed_tokens.weightlm_headcolwise_gather_outputr   logitsc                     t         |   |       t        |      | _        |j                  | _        t        j                  |j                  |j                  d      | _        | j                          y r'   )
r*   r+   r3  r!  r8  r   r/   r-   rN  rB  r5   s     r8   r+   zDiffLlamaForCausalLM.__init__  sU     #F+
 ++yy!3!3V5F5FUS 	r9   NrC  r   rw   r   rD  labelsr   r   logits_to_keepr   rV   c
                 z    | j                   d|||||||d|
}|j                  }t        |	t              rt	        |	 d      n|	}| j                  |dd|ddf         }d}|* | j                  d||| j                  j                  d|
}t        |||j                  |j                  |j                        S )a  
        Example:

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

        >>> model = DiffLlamaForCausalLM.from_pretrained("google/diffllama-7b")
        >>> tokenizer = AutoTokenizer.from_pretrained("google/diffllama-7b")

        >>> prompt = "What is your favorite condiment?"
        >>> 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]
        "What is your favorite condiment?"
        ```)rC  r   rw   r   rD  r   r   N)rP  rR  r8  )lossrP  r   r   r"  r  )r!  rG  rp   r   slicerN  loss_functionr,   r8  r   r   r   r"  )r6   rC  r   rw   r   rD  rR  r   r   rS  r   outputsr   slice_indicesrP  rU  s                   r8   r=   zDiffLlamaForCausalLM.forward  s    @ ,64:: 	,
)%+')	,
 	,
  118B>SV8W~ot4]kmA}a,?@A%4%%pVFt{{OeOepiopD%#33!//))
 	
r9   )	NNNNNNNNr   )r>   r?   r@   _tied_weights_keys_tp_plan_pp_planr+   r   r   r_   r   r|   r	   rK  r   r   r   r   r   r=   rA   rB   s   @r8   rM  rM    s/   *,GH23H_-z:;H  .2.204(,26*.!%26-.8
##d*8
 t+8
 &&-	8

 8
 ((4/8
   4'8
 $;8
 ((4/8
 ell*8
 +,8
 
 8
  8
r9   rM  c                       e Zd Zy)"DiffLlamaForSequenceClassificationNr>   r?   r@   r  r9   r8   r^  r^        r9   r^  c                       e Zd ZdZy)DiffLlamaForQuestionAnsweringtransformerN)r>   r?   r@   r(  r  r9   r8   rb  rb    s    %r9   rb  c                       e Zd Zy)DiffLlamaForTokenClassificationNr_  r  r9   r8   re  re     r`  r9   re  )r   r3  rM  r^  rb  re  )r"   )Lr   collections.abcr   typingr   r_   r    r   r%  activationsr   cache_utilsr	   r
   r   
generationr   integrationsr   r   masking_utilsr   modeling_flash_attention_utilsr   r   modeling_layersr   r   r   r   modeling_outputsr   r   modeling_rope_utilsr   r   modeling_utilsr   processing_utilsr   utilsr   r   r   r   utils.genericr    r!   configuration_diffllamar#   
get_loggerr>   r   Moduler%   rD   r   r   r|   r   r   r   r   r   r   r  r  r  r   r3  rM  r^  rb  re  __all__r  r9   r8   <module>rz     s  .  $    & ! ; ; ) Q / i  P K - & R R ? 4 
		H	%299  ><ryy ><B( *+ ,2	UU\\ 	U# 	U%,, 	U2`) `)FD!1 D!NQ!/ Q!h Y'Jryy J (J*  1" *6 *Z J J J6 L
- L
 L
^ H
3_ H
 H
V	)IKc 	&$?AY &	&CE] 	r9   