
    %	&h                        d dl Z d dlmZ d dlmZmZmZ d dl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 dd
lmZmZmZ ddlmZmZmZ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(m)Z)m*Z*m+Z+m,Z, ddl-m.Z. ddl/m0Z0  e*       rd dl1m2Z2 ddl3m4Z4  e+jj                  e6      Z7dZ8dZ9 G d dejt                        Z;d Z<dBdZ=dej|                  de?dej|                  fdZ@d ZA G d  d!ejt                        ZB G d" d#eB      ZC G d$ d%eB      ZD G d& d'ejt                        ZEeBeCeDd(ZF G d) d*ejt                        ZGd+ZH e'd,eH       G d- d.e!             ZI G d/ d0ejt                        ZJd1ZK e'd,eH       G d2 d3eI             ZL G d4 d5ee%      ZM G d6 d7eIe      ZN e'd8eH       G d9 d:eI             ZO e'd;eH       G d< d=eI             ZP e'd>eH       G d? d@eI             ZQg dAZRy)C    N)partial)OptionalTupleUnion)nn   )ACT2FN)CacheDynamicCacheStaticCache)GenerationMixin)AttentionMaskConverter)FlashAttentionKwargs_flash_attention_forward!flash_attn_supports_top_left_mask)BaseModelOutputWithPastCausalLMOutputWithPastQuestionAnsweringModelOutput SequenceClassifierOutputWithPastTokenClassifierOutput)ROPE_INIT_FUNCTIONSdynamic_rope_update)PreTrainedModel)Unpack)
LossKwargsadd_code_sample_docstringsadd_start_docstrings%add_start_docstrings_to_model_forwardcan_return_tupleis_torch_flex_attn_availableloggingreplace_return_docstrings)deprecate_kwarg   )DiffLlamaConfig)	BlockMask)make_flex_block_causal_maskzkajuma/DiffLlama-0.3B-handcutr%   c                   $     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selfr0   	__class__s     /var/www/pru.catia.catastroantioquia-mas.com/valormas/lib/python3.12/site-packages/transformers/models/diffllama/modeling_diffllama.pyr/   zDiffLlamaMLP.__init__M   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)r6   r8   r4   r5   )r:   xr6   s      r<   forwardzDiffLlamaMLP.forwardW   s6    NN4;;t~~a/@#ADLLQRO#ST	r=   )__name__
__module____qualname__r/   rA   __classcell__r;   s   @r<   r)   r)   L   s    0r=   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..N   dim)shapetorchcat)r@   x1x2s      r<   rotate_halfrQ   \   sZ    	
3"!''"+"""	#B	
3q ""	#B99rc2YB''r=   c                     |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.
        position_ids (`torch.Tensor`, *optional*):
            Deprecated and unused.
        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.
    )	unsqueezerQ   )qkcossinposition_idsunsqueeze_dimq_embedk_embeds           r<   apply_rotary_pos_embr\   c   sY    ( --
&C
--
&C3w;q>C/0G3w;q>C/0GGr=   hidden_statesn_repreturnc                     | 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)rL   expandreshape)r]   r^   batchnum_key_value_headsslenhead_dims         r<   	repeat_kvrg   ~   so    
 2?1D1D.Ehz!!Qa"23::5BUW\^bdlmM  (;e(CT8TTr=   c                 >    ddt        j                  d| z        z  z
  S )Ng?g333333?g333333ӿ)mathexp)	layer_idxs    r<   lambda_init_fnrl      s     txxy 01111r=   c                   b    e Zd ZdZddedee   f fdZ	 	 	 	 	 	 ddej                  de
ej                  ej                  f   deej                     deej                     d	ee   d
ededeej                     de
ej                  eej                     ee
ej                        f   fdZ xZS )DiffLlamaAttentionz=Multi-headed attention from 'Attention Is All You Need' paperr0   rk   c                    t         |           || _        || _        |-t        j                  d| j                  j                   d       |j                  | _        |j                  | _	        |j                  | _        t        |d| j                  | j                  z        | _        |j                  | _        | j                  | j                  z  | _        |j                   | _        |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*                        | _        t5        |      | _        t'        j8                  t;        j<                  d|j>                  | j                  f            | _         t'        j8                  t;        j<                  d|j>                  | j                  f            | _!        t'        j8                  t;        j<                  d|j>                  | j                  f            | _"        t'        j8                  t;        j<                  d|j>                  | j                  f            | _#        t'        jH                  d| j                  z  |jJ                  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.rf   Tr,   r   )sizerI   F)epselementwise_affine)'r.   r/   r0   rk   loggerwarning_oncer;   rB   attention_dropoutr1   num_attention_heads	num_headsgetattrrf   rd   num_key_value_groupsmax_position_embeddings
rope_theta	is_causalr   r3   attention_biasq_projk_projv_projo_projrl   lambda_init	ParameterrM   normallambda_std_dev	lambda_q1	lambda_k1	lambda_q2	lambda_k2RMSNormrms_norm_eps	groupnormr:   r0   rk   r;   s      r<   r/   zDiffLlamaAttention.__init__   s~   " !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r=   r]   position_embeddingsattention_maskrX   past_key_valueoutput_attentions	use_cachecache_positionr_   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                  |      }|sd }||fS )
Nr$   rI   rW   rV   r   rJ   rH   r   rK   dtype)ptraining)*rp   r~   r   r   viewrw   rf   	transposerd   r\   updaterk   rg   ry   rM   rN   chunkrepeatmatmulri   sqrtrL   r   
functionalsoftmaxfloat32tor   dropoutru   r   rj   sumr   r   r   r   r   r   
contiguousrb   r   )r:   r]   r   r   rX   r   r   r   r   kwargsbsz
target_len_q_lenquery_states
key_statesvalue_statesrV   rW   cache_kwargsattn_weightscausal_masklambda_1lambda_2lambda_fullattn_outputattn_output1attn_output2s                               r<   rA   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'5'<'<ZW[WeWegs't$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L((r=   r?   NNNFFN)rB   rC   rD   __doc__r%   r   intr/   rM   Tensorr   
LongTensorr
   boolrA   rE   rF   s   @r<   rn   rn      s    G j  j8C=  jL 2637*."'59B)||B) #5<<#=>B) !.	B)
 u//0B) !B)  B) B) !!1!12B) 
u||Xell3XeELL>Q5RR	SB)r=   rn   c                   P    e Zd ZdZ fdZ	 	 	 	 	 	 ddej                  deej                  ej                  f   deej                     deej                     dee
   ded	ed
eej                     deej                  eej                     eeej                        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)r:   argsr   r;   s      r<   r/   z!DiffLlamaFlashAttention2.__init__   s#    $)&)
 /P.Q+r=   r]   r   r   rX   r   r   r   r   r_   c	                 	   t        |t              rt        d      d}|j                         \  }	}
}| j	                  |      }| j                  |      }| j                  |      }|j                  |	|
| j                  | j                        j                  dd      }|j                  |	|
| j                  | j                        j                  dd      }|j                  |	|
| j                  | j                        j                  dd      }|+t        j                  d       | j                  ||      \  }}n|\  }}t        ||||      \  }}|'|||d}|j!                  ||| j"                  |      \  }}|j                  dd      }|j                  dd      }|j                  dd      }| j$                  r| j&                  nd}|j(                  }|t*        j,                  k(  rt+        j.                         rt+        j0                         }nMt3        | j4                  d      r| j4                  j6                  }n | j                  j8                  j(                  }t        j                  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_                  |      }|s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/transformersFr$   rI   aY  The attention layers in this model are transitioning from computing the RoPE embeddings internally through `position_ids` (2D tensor with the indexes of the tokens), to using externally computed `position_embeddings` (Tuple of tensors, containing cos and sin). In v4.46 `position_ids` will be removed and `position_embeddings` will be mandatory.r           _pre_quantization_dtypezThe 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 .rJ   sliding_window)rX   r   r   use_top_left_maskr|   rH   r   )0
isinstancer   
ValueErrorrp   r~   r   r   r   rw   rf   r   rd   rs   rt   
rotary_embr\   r   rk   r   ru   r   rM   r   is_autocast_enabledget_autocast_gpu_dtypehasattrr0   r   weightr   r   r   r   rx   r   r|   rN   rj   r   r   r   r   r   r   r   rb   r   r   )r:   r]   r   r   rX   r   r   r   r   r   r   r   r   r   r   rV   rW   r   dropout_rateinput_dtypetarget_dtypevalue_states1value_states2r   r   r   r   r   r   r   s                                 r<   rA   z DiffLlamaFlashAttention2.forward  sh    nk2} 
 "%**,UA{{=1[[/
{{=1
 $((eT^^T]]S]]^_abc__S%1I1I4==Yccdeghi
#((eT5M5Mt}}]gghiklm&G |\BHC*HC#7jRUWZ#[ j%#&snUL'5'<'<ZW[WeWegs't$J $--a3))!Q/
#--a315t--C #((%--'((*$;;=&?@#{{BB#{{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+. LL((r=   r   )rB   rC   rD   r   r/   rM   r   r   r   r   r
   r   rA   rE   rF   s   @r<   r   r      s    R 6:37*."'59D)||D) #5<<#=>D) !!1!12	D)
 u//0D) !D)  D) D) !!1!12D) 
u||Xell3XeELL>Q5RR	SD)r=   r   c                   J    e Zd ZdZ	 	 	 	 	 	 ddej
                  deej
                  ej
                  f   deej
                     deej                     dee	   de
de
d	eej                     d
eej
                  eej
                     eeej
                        f   f fdZ xZS )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.
    r]   r   r   rX   r   r   r   r   r_   c	           
         |r,t         j                  d       t        |   ||||||||      S |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.                  j0                  d	k(  r2|0|j3                         }|j3                         }|j3                         }||dkD  rd
nd}t$        j4                  j6                  j9                  ||||| j:                  r| j<                  nd|      }t%        j(                  |dd      \  }}t%        j>                  t%        j@                  | jB                  | jD                  z  dt$        jF                              jI                  |jJ                        }t%        j>                  t%        j@                  | jL                  | jN                  z  dt$        jF                              jI                  |jJ                        }||z
  | jP                  z   }|||z  z
  }d| jP                  z
  | jS                  |      z  }|j                  dd      j3                         }|j                  |
|d      }| jU                  |      }|d fS )Na  DiffLlamaModel is using DiffLlamaSdpaAttention, but `torch.nn.functional.scaled_dot_product_attention` does not support `output_attentions=True`. Falling back to the manual attention implementation, but specifying the manual implementation will be required from Transformers version v5.0.0 onwards. This warning can be removed using the argument `attn_implementation="eager"` when loading the model.r]   r   rX   r   r   r   r   r   r$   rI   r   rJ   rH   r   cudaTFr   )	attn_mask	dropout_pr|   r   )+rs   rt   r.   rA   rp   r~   r   r   r   rw   rf   r   rd   r\   r   rk   rg   ry   rM   rN   r   r   rL   devicetyper   r   r   scaled_dot_product_attentionr   ru   rj   r   r   r   r   r   r   r   r   r   r   r   )r:   r]   r   r   rX   r   r   r   r   r   r   r   r   r   r   r   rV   rW   r   r   r|   r   r   r   r   r   r   r;   s                              r<   rA   zDiffLlamaSdpaAttention.forward  s    [ 7?+-)-"3#-$7 # 	 	 &**,UA{{=1[[/
{{=1#((eT^^T]]S]]^_abc__S%1I1I4==Yccdeghi
#((eT5M5Mt}}]gghiklm&S#7jRUWZ#[ j%#&snUL'5'<'<ZW[WeWegs't$Jz4+D+DE
 t/H/HIyy\1!!D"M#**1aA6$%%aA/E1A1A"1E/E&EFK ##v-+2I'224L#..0J'224L (/EAID5	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  r=   r   )rB   rC   rD   r   rM   r   r   r   r   r
   r   rA   rE   rF   s   @r<   r   r     s     2637*."'59\!||\! #5<<#=>\! !.	\!
 u//0\! !\!  \! \! !!1!12\! 
u||Xell3XeELL>Q5RR	S\! \!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   rM   onesr   variance_epsilon)r:   r1   rq   r;   s      r<   r/   zDiffLlamaRMSNorm.__init__  s1     	ll5::k#:; #r=   c                 "   |j                   }|j                  t        j                        }|j	                  d      j                  dd      }|t        j                  || j                  z         z  }| j                  |j                  |      z  S )NrI   rH   T)keepdim)	r   r   rM   r   powmeanrsqrtr   r   )r:   r]   r   variances       r<   rA   zDiffLlamaRMSNorm.forward  sy    #))%((7 $$Q',,R,>%Ht?T?T4T(UU{{]--k:::r=   c                 ^    t        | j                  j                         d| j                   S )Nz, eps=)tupler   rL   r   r:   s    r<   
extra_reprzDiffLlamaRMSNorm.extra_repr  s*    ))*+6$2G2G1HIIr=   )gư>)rB   rC   rD   r/   rA   r   rE   rF   s   @r<   r   r     s    $;Jr=   r   )eagerflash_attention_2sdpac                   p    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ej                  ej                  f      dee   deej                  eeej                  ej                  f      f   fdZ xZS )DiffLlamaDecoderLayerr0   rk   c                 :   t         |           |j                  | _        t        |j                     ||      | _        t        |      | _        t        |j                  |j                        | _
        t        |j                  |j                        | _        y )N)r0   rk   rq   )r.   r/   r1   DIFFLLAMA_ATTENTION_CLASSES_attn_implementation	self_attnr)   mlpr   r   input_layernormpost_attention_layernormr   s      r<   r/   zDiffLlamaDecoderLayer.__init__  sz    !--4V5P5PQY_ktu'/0B0BH[H[\(89K9KQWQdQd(e%r=   r]   r   rX   r   r   r   r   r   r   r_   c	                     |}
| j                  |      } | j                  d||||||||d|	\  }}|
|z   }|}
| j                  |      }| j                  |      }|
|z   }|f}|r||fz  }|S )Nr    )r   r   r   r   )r:   r]   r   rX   r   r   r   r   r   r   residualself_attn_weightsoutputss                r<   rA   zDiffLlamaDecoderLayer.forward  s     !,,]; ,:4>> 
,
')%)/) 3
,
 
,
(( !=0 !55mD/ =0 ")++Gr=   )NNNFFNN)rB   rC   rD   r%   r   r/   rM   r   r   r   r
   r   r   r   r   FloatTensorrA   rE   rF   s   @r<   r   r     s   f f3 f 2637*.,1$)59KO(||( !.( u//0	(
 !( $D>( D>( !!1!12( &eELL%,,,F&GH( -.( 
u  (51B1BEDUDU1U+V"WW	X(r=   r   aN  
    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 ([`DiffLlamaConfig`]):
            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.
zWThe bare DiffLlama Model outputting raw hidden-states without any specific head on top.c                   F    e Zd ZeZdZdZdgZdgZdZ	dZ
dZdZdZdZdZd Zy)DiffLlamaPreTrainedModelmodelTr   past_key_valuesFc                    | j                   j                  }t        |t        j                        rY|j
                  j                  j                  d|       |j                  %|j                  j                  j                          y y t        |t        j                        rf|j
                  j                  j                  d|       |j                  2|j
                  j                  |j                     j                          y y y )Nr   )r   std)r0   initializer_ranger   r   r3   r   datanormal_r-   zero_	Embeddingpadding_idx)r:   moduler  s      r<   _init_weightsz&DiffLlamaPreTrainedModel._init_weightsi  s    kk++fbii(MM&&CS&9{{&  &&( '-MM&&CS&9!!-""6#5#56<<> . .r=   N)rB   rC   rD   r%   config_classbase_model_prefixsupports_gradient_checkpointing_no_split_modules_skip_keys_device_placement_supports_flash_attn_2_supports_sdpa_supports_flex_attn_supports_cache_class_supports_quantized_cache_supports_static_cache_supports_attention_backendr  r   r=   r<   r  r  W  sU    
 #L&*#01#4"5!N  $!"'	?r=   r  c                   ^     e Zd Zddef fdZ ej                         ed               Z xZ	S )DiffLlamaRotaryEmbeddingr0   c                    t         |           t        |d      rG|j                  ;|j                  j	                  d|j                  j	                  d            | _        nd| _        |j                  | _        |j                  | _        || _	        t        | j
                     | _        | j                  | j                  |      \  }| _        | j                  d|d       | j                  | _        y )Nrope_scaling	rope_typer   defaultinv_freqF)
persistent)r.   r/   r   r   getr!  rz   max_seq_len_cachedoriginal_max_seq_lenr0   r   rope_init_fnattention_scalingregister_bufferr#  original_inv_freq)r:   r0   r   r#  r;   s       r<   r/   z!DiffLlamaRotaryEmbedding.__init__v  s    6>*v/B/B/N#0044[&BUBUBYBYZ`BabDN&DN"("@"@$*$B$B!/?+/+<+<T[[&+Q($(ZeD!%r=   c                 b   | 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        j                  |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   rH   r$   mpscpuF)device_typeenabledrI   rJ   )r   )r#  floatra   rL   r   r   r   r   strrM   autocastr   rN   rV   r)  rW   r   )
r:   r@   rX   inv_freq_expandedposition_ids_expandedr/  freqsembrV   rW   s
             r<   rA   z DiffLlamaRotaryEmbedding.forward  sV    !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?   )
rB   rC   rD   r%   r/   rM   no_gradr   rA   rE   rF   s   @r<   r  r  u  s3    / /" U]]_<  <r=   r  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`, *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`.

            It is a [`~cache_utils.Cache`] instance. For more details, see our [kv cache guide](https://huggingface.co/docs/transformers/en/kv_cache).

            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d Zd Ze e	e
      	 	 	 	 	 	 	 	 	 ddeej                     deej                     deej                     d	ee   d
eej                      dee   dee   dee   deej                     dee   defd              Z	 ddej                  dej                  dej                  d	edef
dZedej                  dededej2                  dej4                  dej                  defd       Z xZS )DiffLlamaModelz
    Transformer decoder consisting of *config.num_hidden_layers* layers. Each layer is a [`DiffLlamaDecoderLayer`]

    Args:
        config: DiffLlamaConfig
    r0   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   )r0   F)r.   r/   pad_token_idr  
vocab_sizer   r  r1   embed_tokens
ModuleListrangenum_hidden_layersr   layersr   r   normr  r   gradient_checkpointing	post_initr   s      r<   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c                     | j                   S r?   r>  r   s    r<   get_input_embeddingsz#DiffLlamaModel.get_input_embeddings  s       r=   c                     || _         y r?   rG  r:   values     r<   set_input_embeddingsz#DiffLlamaModel.set_input_embeddings  s
    !r=   	input_idsr   rX   r  inputs_embedsr   r   output_hidden_statesr   flash_attn_kwargsr_   c
                 ^   ||n| j                   j                  }||n| j                   j                  }||n| j                   j                  }|d u |d uz  rt	        d      | j
                  r%| j                  r|rt        j                  d       d}t        |t        d       t        f      st	        d      || j                  |      }|r|
t               }|	F||j                         nd}t        j                   |||j"                  d   z   |j$                        }	||	j'                  d      }| j)                  |||	||      }|}| j+                  ||      }|rdnd }|rdnd }| j,                  d | j                   j.                   D ]r  }|r||fz  }| j
                  r:| j                  r.| j1                  t3        |j4                  fi |
|||||||	|	      }n ||f||||||	|d	|
}|d   }|sj||d   fz  }t | j7                  |      }|r||fz  }t9        ||r|nd ||
      S )Nz:You must specify exactly one of input_ids or inputs_embedszX`use_cache=True` is incompatible with gradient checkpointing. Setting `use_cache=False`.FzBThe `past_key_values` should be either a `Cache` object or `None`.r   r$   r   r   )r   rX   r   r   r   r   r   )last_hidden_stater  r]   
attentions)r0   r   rO  r   r   rD  r   rs   rt   r   r   r
   r>  r   get_seq_lengthrM   arangerL   r   rS   _update_causal_maskr   rB  rA  _gradient_checkpointing_funcr   __call__rC  r   )r:   rM  r   rX   r  rN  r   r   rO  r   rP  past_seen_tokensr   r]   r   all_hidden_statesall_self_attnsdecoder_layerlayer_outputss                      r<   rA   zDiffLlamaModel.forward  s    2C1N-TXT_T_TqTq$8$D $++JjJj 	 "+!6IDKK<Q<Q	-t";<YZZ&&4==Yj I /DJ+>?abb  --i8M0*nO!CRC^==?de"\\ "2]5H5H5K"KTaThThN )33A6L..M>?L]
 & #oom\J #7BD0d![[)H4;;+H+HI  	6M#!m%55!**t}} $ A AM22H6GH! #%"'
! !.!
!#.!-#2&7'#1(;
! (
! *!,M =#3"55A 	6D 		-0  -!11&+/8Od+%	
 	
r=   input_tensorc           
         | j                   j                  dk(  r||dk(  j                         r|S y | j                   j                  dk(  r7t        |t        j
                        rt        |      }t        |t              r|S ||j                         nd}t        |t              }| j                   j                  dk(  r(|s&|s$t        j                  |||| j                        ry |j                  |j                  }	}|j                  d   }
|r|j!                         }n1t        |t        j
                        r|j                  d   n||
z   dz   }| j#                  ||
|||	||j                  d   	      }| j                   j                  dk(  rQ|O|j                  j$                  d
v r7|s5t	        j&                  |      j(                  }t        j*                  ||      }|S )Nr   r   flex_attentionr   r   )rN  past_key_values_lengthis_trainingr$   rH   )sequence_lengthtarget_lengthr   r   r   
batch_size)r   xpu)r0   r   anyr   rM   r   r'   r&   rU  r   r   _ignore_causal_mask_sdpar   r   r   rL   get_max_cache_shape5_prepare_4d_causal_attention_mask_with_cache_positionr   finfomin_unmask_unattended)r:   r   r_  r   r  r   rZ  using_static_cacher   r   rd  re  r   	min_dtypes                 r<   rW  z"DiffLlamaModel._update_causal_maski  s    ;;++/BB)~/D.I.I.K%%;;++/??.%,,7!<^!L.)4%%
 @O?Z?99;`a'E ;;++v5>PYj%>>*'7 MM	 $**L,?,?v&,,Q/+??AM nell; $$R(%7!;  PP+')#))!, Q 
 KK,,6*%%**o=%
 E*..I0CCKQZ[Kr=   rd  re  r   r   rf  c                    | | j                         dk(  r| }|S t        j                  |      j                  }	t        j                  ||f|	||      }|dk7  rt        j
                  |d      }|t        j                  ||      |j                  dd      kD  z  }|ddddddf   j                  |ddd      }| |j                         }| j                  d   }
|ddddddd|
f   | ddddddf   j                  |j                        z   }|dk(  }|ddddddd|
f   j                  ||	      |ddddddd|
f<   |S )	a  
        Creates a causal 4D mask of shape `(batch_size, 1, query_length, key_value_length)` from a 2D mask of shape
        `(batch_size, key_value_length)`, or if the input `attention_mask` is already 4D, do nothing.

        Args:
            attention_mask (`torch.Tensor`):
                A 2D attention mask of shape `(batch_size, key_value_length)` or a 4D attention mask of shape
                `(batch_size, 1, query_length, key_value_length)`.
            sequence_length (`int`):
                The sequence length being processed.
            target_length (`int`):
                The target length: when generating with static cache, the mask should be as long as the static cache,
                to account for the 0 padding, the part of the cache that is not filled yet.
            dtype (`torch.dtype`):
                The dtype to use for the 4D attention mask.
            device (`torch.device`):
                The device to place the 4D attention mask on.
            cache_position (`torch.Tensor`):
                Indices depicting the position of the input sequence tokens in the sequence.
            batch_size (`torch.Tensor`):
                Batch size.
        N   )
fill_valuer   r   r$   )diagonalrR  rH   r   )rK   rM   rl  rm  fulltriurV  rb   ra   clonerL   r   r   masked_fill)r   rd  re  r   r   r   rf  r   r   rp  mask_lengthpadding_masks               r<   rk  zDDiffLlamaModel._prepare_4d_causal_attention_mask_with_cache_position  sy   B %.*<*<*>!*C(K* ' E*..I** -0Ye\bK !##jjqA5<<fEH^H^_acdHeeeK%dD!Q&67>>z1bRTUK))//1,2226*1aL[L+@ANSTVZ\`bcScDdDgDg&&E    ,q05@Aq,;,AV5W5c5c )6Aq!\k\12 r=   	NNNNNNNNN)F)rB   rC   rD   r   r%   r/   rH  rL  r   r   DIFFLLAMA_INPUTS_DOCSTRINGr   rM   r   r   r
   r  r   r   r   r   rA   rW  staticmethodr   r   r   rk  rE   rF   s   @r<   r:  r:    s   
  !" *+EF 151537+/59$(,0/359i
E,,-i
 !.i
 u//0	i

 "%i
   1 12i
 D>i
 $D>i
 'tni
 !!1!12i
 $$89i
 
!i
 G i
b #(DD llD 	D
 D  DL 777 7 {{	7
 7 7 7 7r=   r:  c                       e Zd Zy)KwargsForCausalLMN)rB   rC   rD   r   r=   r<   r  r    s    r=   r  c                       e Zd ZdgZddiZddgdgfiZ fdZd Zd Zd	 Z	d
 Z
d Zd Ze eddd       ee       eee      	 	 	 	 	 	 	 	 	 	 	 ddeej,                     deej.                     deej,                     dee   deej2                     deej,                     dee   dee   dee   deej,                     deeej.                  f   dee   defd                            Z xZ S ) DiffLlamaForCausalLMzlm_head.weightlm_headcolwise_repr]   logitsc                     t         |   |       t        |      | _        |j                  | _        t        j                  |j                  |j                  d      | _        | j                          y r+   )
r.   r/   r:  r  r=  r   r3   r1   r  rE  r9   s     r<   r/   zDiffLlamaForCausalLM.__init__  sU     #F+
 ++yy!3!3V5F5FUS 	r=   c                 .    | j                   j                  S r?   r  r>  r   s    r<   rH  z)DiffLlamaForCausalLM.get_input_embeddings      zz&&&r=   c                 &    || j                   _        y r?   r  rJ  s     r<   rL  z)DiffLlamaForCausalLM.set_input_embeddings      "'

r=   c                     | j                   S r?   r  r   s    r<   get_output_embeddingsz*DiffLlamaForCausalLM.get_output_embeddings  s    ||r=   c                     || _         y r?   r  )r:   new_embeddingss     r<   set_output_embeddingsz*DiffLlamaForCausalLM.set_output_embeddings  s	    %r=   c                     || _         y r?   r  )r:   decoders     r<   set_decoderz DiffLlamaForCausalLM.set_decoder  s	    
r=   c                     | j                   S r?   r  r   s    r<   get_decoderz DiffLlamaForCausalLM.get_decoder
  s    zzr=   num_logits_to_keepz4.50logits_to_keep)versionnew_name)output_typer  rM  r   rX   r  rN  labelsr   r   rO  r   r   r_   c                    ||n| j                   j                  }|	|	n| j                   j                  }	 | 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  
            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]`.

            logits_to_keep (`int` or `torch.Tensor`, *optional*):
                If an `int`, compute logits for the last `logits_to_keep` tokens. If `0`, calculate logits for all
                `input_ids` (special case). Only last token logits are needed for generation, and calculating them only for that
                token can save memory, which becomes pretty significant for long sequences or large vocabulary size.
                If a `torch.Tensor`, must be 1D corresponding to the indices to keep in the sequence length dimension.
                This is useful when using packed tensor format (single dimension for batch and sequence length).

        Returns:

        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?"
        ```N)	rM  r   rX   r  rN  r   r   rO  r   )r  r  r=  lossr  r  r]   rT  r   )r0   r   rO  r  rS  r   r   slicer  loss_functionr=  r   r  r]   rT  )r:   rM  r   rX   r  rN  r  r   r   rO  r   r  r   r  r]   slice_indicesr  r  s                     r<   rA   zDiffLlamaForCausalLM.forward  s   d 2C1N-TXT_T_TqTq$8$D $++JjJj 	
 ,64:: ,
)%+'/!5),
 ,
  118B>SV8W~ot4]kmA}a,?@A%4%%pVFt{{OeOepiopD%#33!//))
 	
r=   )NNNNNNNNNNr   )!rB   rC   rD   _tied_weights_keys_tp_plan_pp_planr/   rH  rL  r  r  r  r  r   r#   r   r|  r"   r   _CONFIG_FOR_DOCr   rM   r   r   r
   r  r   r   r   r   r  rA   rE   rF   s   @r<   r  r    s   *+=)H_-z:;H'(& )6DTU*+EF+AP_` 151537+/59-1$(,0/35934P
E,,-P
 !.P
 u//0	P

 "%P
   1 12P
 ))*P
 D>P
 $D>P
 'tnP
 !!1!12P
 c5<</0P
 *+P
 
 P
 a G V P
r=   r  a  
    The DiffLlama Model transformer with a sequence classification head on top (linear layer).

    [`DiffLlamaForSequenceClassification`] uses the last token in order to do the classification, as other causal models
    (e.g. GPT-2) do.

    Since it does classification on the last token, it requires to know the position of the last token. If a
    `pad_token_id` is defined in the configuration, it finds the last token that is not a padding token in each row. If
    no `pad_token_id` is defined, it simply takes the last value in each row of the batch. Since it cannot guess the
    padding tokens when `inputs_embeds` are passed instead of `input_ids`, it does the same (take the last value in
    each row of the batch).
    c                   (    e Zd Z fdZd Zd Ze ee      	 	 	 	 	 	 	 	 	 dde	e
j                     de	e
j                     de	e
j                     de	e   de	e
j                     d	e	e
j                     d
e	e   de	e   de	e   defd              Z xZS )"DiffLlamaForSequenceClassificationc                     t         |   |       |j                  | _        t        |      | _        t        j                  |j                  | j                  d      | _        | j                          y r+   )
r.   r/   
num_labelsr:  r  r   r3   r1   scorerE  r9   s     r<   r/   z+DiffLlamaForSequenceClassification.__init__t  sS      ++#F+
YYv114??O
 	r=   c                 .    | j                   j                  S r?   r  r   s    r<   rH  z7DiffLlamaForSequenceClassification.get_input_embeddings}  r  r=   c                 &    || j                   _        y r?   r  rJ  s     r<   rL  z7DiffLlamaForSequenceClassification.set_input_embeddings  r  r=   rM  r   rX   r  rN  r  r   r   rO  r_   c
           
         | j                  ||||||||	      }
|
j                  }| j                  |      }||j                  d   }n|j                  d   }| j                  j
                  |dk7  rt        d      | j                  j
                  d}n||| j                  j
                  k7  j                  |j                  t        j                        }t        j                  |j                  d   |j                  t        j                        }||z  j                  d      }n.d}t        j                  | j                  j                    d       |t        j                  ||j                  	      |f   }d}|| j#                  |||| j                  
      }t%        |||
j&                  |
j(                  |
j*                        S )  
        labels (`torch.LongTensor` of shape `(batch_size,)`, *optional*):
            Labels for computing the sequence classification/regression loss. Indices should be in `[0, ...,
            config.num_labels - 1]`. If `config.num_labels == 1` a regression loss is computed (Mean-Square loss), If
            `config.num_labels > 1` a classification loss is computed (Cross-Entropy).
        r   rX   r  rN  r   r   rO  Nr   r$   z=Cannot handle batch sizes > 1 if no padding token is defined.rH   )r   r   z will not detect padding tokens in `inputs_embeds`. Results may be unexpected if using padding tokens in conjunction with `inputs_embeds.`rR  )r  r  pooled_logitsr0   r  )r  rS  r  rL   r0   r<  r   r   r   rM   int32rV  argmaxrs   rt   r;   rB   r  r   r  r]   rT  )r:   rM  r   rX   r  rN  r  r   r   rO  transformer_outputsr]   r  rf  last_non_pad_tokennon_pad_masktoken_indicesr  r  s                      r<   rA   z*DiffLlamaForSequenceClassification.forward  s   * 8<zz)%+'/!5 8B 	8
 ,==M* "+J&,,Q/J;;##+
a\]];;##+!#"%)A)AAEEfmmUZU`U`aL!LL)<V]]Z_ZeZefM"/,">!F!Fr!J!#>>**+ ,Z Z
 u||Jv}}MOaab%%VFR_hlhshs%tD/ /??-;;*55
 	
r=   r{  )rB   rC   rD   r/   rH  rL  r   r   r|  r   rM   r   r   r
   r  r   r   rA   rE   rF   s   @r<   r  r  d  s    '( *+EF 151537+/59-1$(,0/3A
E,,-A
 !.A
 u//0	A

 "%A
   1 12A
 ))*A
 D>A
 $D>A
 'tnA
 
*A
 G A
r=   r  z
The DiffLlama Model transformer with a span classification head on top for extractive question-answering tasks like
SQuAD (a linear layer on top of the hidden-states output to compute `span start logits` and `span end logits`).
    c                   @    e Zd ZdZ fdZd Zd Ze ee	      	 	 	 	 	 	 	 	 	 dde
ej                     de
ej                     de
ej                     de
e   d	e
ej                     d
e
ej                     de
ej                     de
e   de
e   defd              Z xZS )DiffLlamaForQuestionAnsweringtransformerc                     t         |   |       t        |      | _        t	        j
                  |j                  d      | _        | j                          y )NrI   )	r.   r/   r:  r  r   r3   r1   
qa_outputsrE  r9   s     r<   r/   z&DiffLlamaForQuestionAnswering.__init__  sA     )&1))F$6$6: 	r=   c                 .    | j                   j                  S r?   r  r>  r   s    r<   rH  z2DiffLlamaForQuestionAnswering.get_input_embeddings  s    ,,,r=   c                 &    || j                   _        y r?   r  rJ  s     r<   rL  z2DiffLlamaForQuestionAnswering.set_input_embeddings  s    (-%r=   rM  r   rX   r  rN  start_positionsend_positionsr   rO  r_   c
           	         | j                  |||||||	      }|j                  }| j                  |      }|j                  dd      \  }}|j	                  d      j                         }|j	                  d      j                         }d}|| | j                  ||||fi |
}t        ||||j                  |j                        S )a  
        start_positions (`torch.LongTensor` of shape `(batch_size,)`, *optional*):
            Labels for position (index) of the start of the labelled span for computing the token classification loss.
            Positions are clamped to the length of the sequence (`sequence_length`). Position outside of the sequence
            are not taken into account for computing the loss.
        end_positions (`torch.LongTensor` of shape `(batch_size,)`, *optional*):
            Labels for position (index) of the end of the labelled span for computing the token classification loss.
            Positions are clamped to the length of the sequence (`sequence_length`). Position outside of the sequence
            are not taken into account for computing the loss.
        )r   rX   r  rN  r   rO  r$   rH   rJ   N)r  start_logits
end_logitsr]   rT  )
r  rS  r  splitsqueezer   r  r   r]   rT  )r:   rM  r   rX   r  rN  r  r  r   rO  r   r  sequence_outputr  r  r  r  s                    r<   rA   z%DiffLlamaForQuestionAnswering.forward  s    4 ,0+;+;)%+'/!5 ,< ,
 "331#)<<r<#: j#++B/::<''+668
&=+D%4%%lJQ^ibhiD+%!!//))
 	
r=   r{  )rB   rC   rD   r  r/   rH  rL  r   r   r|  r   rM   r   r  r
   r   r   rA   rE   rF   s   @r<   r  r    s
    &-. *+EF 156:37+/596:48,0/33
E,,-3
 !!2!233
 u//0	3

 "%3
   1 123
 "%"2"233
   0 013
 $D>3
 'tn3
 
&3
 G 3
r=   r  z
    The DiffLlama Model transformer with a token classification head on top (a linear layer on top of the hidden-states
    output) e.g. for Named-Entity-Recognition (NER) tasks.
    c                   D    e Zd Z fdZd Zd Ze ee       e	e
ee      	 	 	 	 	 	 	 	 	 ddeej                     deej                      deej                     dee   d	eej$                     d
eej                     dee   dee   dee   defd                     Z xZS )DiffLlamaForTokenClassificationc                    t         |   |       |j                  | _        t        |      | _        t        |dd       |j                  }nt        |dd       |j                  }nd}t        j                  |      | _
        t        j                  |j                  |j                        | _        | j                          y )Nclassifier_dropouthidden_dropoutg?)r.   r/   r  r:  r  rx   r  r  r   Dropoutr   r3   r1   r  rE  )r:   r0   r  r;   s      r<   r/   z(DiffLlamaForTokenClassification.__init__!  s      ++#F+
6/6B!'!:!:V-t4@!'!6!6!$zz"45YYv1163D3DE
 	r=   c                 .    | j                   j                  S r?   r  r   s    r<   rH  z4DiffLlamaForTokenClassification.get_input_embeddings1  r  r=   c                 &    || j                   _        y r?   r  rJ  s     r<   rL  z4DiffLlamaForTokenClassification.set_input_embeddings4  r  r=   )
checkpointr  r  rM  r   rX   r  rN  r  r   r   rO  r_   c
           
         | j                  ||||||||	      }
|
j                  }| j                  |      }| j                  |      }d}|| j	                  ||| j
                        }t        |||
j                  |
j                        S )r  r  N)r  r  r]   rT  )	r  rS  r   r  r  r0   r   r]   rT  )r:   rM  r   rX   r  rN  r  r   r   rO  r  r  r  r  s                 r<   rA   z'DiffLlamaForTokenClassification.forward7  s    4 ,0::)%+'/!5 ,6 	,
 "33,,7O,%%ffdkkBD$!//))	
 	
r=   r{  )rB   rC   rD   r/   rH  rL  r   r   r|  r   _CHECKPOINT_FOR_DOCr   r  r   rM   r   r   r
   r  r   rA   rE   rF   s   @r<   r  r    s    '( *+EF&)$ 151537+/59-1$(,0/3*
E,,-*
 !.*
 u//0	*

 "%*
   1 12*
 ))**
 D>*
 $D>*
 'tn*
 
*
 G *
r=   r  )r  r:  r  r  r  r  )Nr$   )Sri   	functoolsr   typingr   r   r   rM   r   activationsr	   cache_utilsr
   r   r   
generationr   modeling_attn_mask_utilsr   modeling_flash_attention_utilsr   r   r   modeling_outputsr   r   r   r   r   modeling_rope_utilsr   r   modeling_utilsr   processing_utilsr   utilsr   r   r   r   r   r    r!   r"   utils.deprecationr#   configuration_diffllamar%   !torch.nn.attention.flex_attentionr&   integrations.flex_attentionr'   
get_loggerrB   rs   r  r  Moduler)   rQ   r\   r   r   rg   rl   rn   r   r   r   r   r   DIFFLLAMA_START_DOCSTRINGr  r  r|  r:  r  r  r  r  r  __all__r   r=   r<   <module>r     sa  0   ) )   ! ; ; ) > 
  L - &	 	 	 1 4  !;J 
		H	%5 #299  (6	UU\\ 	U# 	U%,, 	U2g) g)TS)1 S)ld!/ d!NJryy J*  1" 3BII 3l " ]? ?	?4<ryy <D@ F ]I- I	IX ?,j >t
3_ t
n  S
)A S
S
l  F
$< F
F
R  H
&> H
H
Vr=   