
    i$                     t   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 ddl3m4Z4  e-jj                  e6      Z7 G d dejp                        Z9 G d dejp                        Z:d Z; ed      d<d       Z<dejz                  de>d ejz                  fd!Z?d" Z@ G d# d$ejp                        ZA G d% d&eA      ZB G d' d(eA      ZC ed)       G d* d+ejp                               ZDeAeBeCd,ZE G d- d.e      ZFe+ G d/ d0e&             ZGe+ G d1 d2eG             ZHe+ G d3 d4eGe             ZI G d5 d6eeG      ZJ G d7 d8eeG      ZK G d9 d:eeG      ZLg d;ZMy)=    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)maybe_autocastmerge_with_config_defaults)capture_outputs   )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     l/mnt/e/genesis-system/.venv/lib/python3.12/site-packages/transformers/models/diffllama/modeling_diffllama.pyr,   zDiffLlamaMLP.__init__9   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)r3   r5   r1   r2   )r7   xr3   s      r9   forwardzDiffLlamaMLP.forwardC   s6    NN4;;t~~a/@#ADLLQRO#ST	r:   )__name__
__module____qualname__r,   r>   __classcell__r8   s   @r9   r&   r&   8   s    0r:   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defaultrF   F)
persistentoriginal_inv_freq)r+   r,   max_position_embeddingsmax_seq_len_cachedoriginal_max_seq_lenr-   rope_parametersrH   compute_default_rope_parametersr   attention_scalingregister_bufferclone)r7   r-   devicerope_init_fnrF   r8   s        r9   r,   z!DiffLlamaRotaryEmbedding.__init__K   s    "("@"@$*$B$B!44[A!%!E!E>>Y&.t~~>L+7V+L($(ZeD0(..2BuUr:   rT   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)rT   r]   )	rO   getattrr.   num_attention_headstorcharangeint64tofloat)r-   rT   rV   basedimattention_factorrF   s          r9   rP   z8DiffLlamaRotaryEmbedding.compute_default_rope_parameters[   s    & %%l3fj$/c63E3EIcIc3c U\\!S!5;;?BB&X]XcXcBdgjjk
 )))r:   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enabledr[   rf   r\   )rF   rd   expandshaperc   rT   
isinstancetypestrr    	transposer`   catcosrQ   sinr]   )
r7   r=   position_idsinv_freq_expandedposition_ids_expandedrl   freqsembrv   rw   s
             r9   r>   z DiffLlamaRotaryEmbedding.forwardy   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@   rA   r`   Tensor__annotations__r$   r,   staticmethodr   inttuplerd   rP   no_gradr   r>   rB   rC   s   @r9   rE   rE   H   s    llV V  )-+/"*$&*(* t* 
~u$	%	* *: U]]_<  <r:   rE   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..Nri   r[   rn   )rp   r`   ru   )r=   x1x2s      r9   rotate_halfr      sZ    	
3"!''"+"""	#B	
3q ""	#B99rc2YB''r:   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krv   rw   unsqueeze_dimq_embedk_embeds          r9   apply_rotary_pos_embr      sY    & --
&C
--
&C3w;q>C/0G3w;q>C/0GGr:   hidden_statesn_reprW   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)rp   ro   reshape)r   r   batchnum_key_value_headsslenrZ   s         r9   	repeat_kvr      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    r9   lambda_init_fnr      s     txxy 01111r:   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.rZ   Tr)   r   )sizer[   F)epselementwise_affine)&r+   r,   r-   r   loggerwarning_oncer8   r?   attention_dropoutr.   r_   	num_headsr^   rZ   r   num_key_value_groupsrL   	is_causalr   r0   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r7   r-   r   r8   s      r9   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r:   r   position_embeddingsattention_maskrx   past_key_values	use_cachecache_positionrW   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  }|||z   }t*        j,                  j/                  |dt        j0                        j3                  |j4                        }t*        j,                  j7                  || j8                  | j:                        }t        j<                  t        j>                  | j@                  | jB                  z  dt        j0                              j3                  |j4                        }t        j<                  t        j>                  | jD                  | jF                  z  dt        j0                              j3                  |j4                        }||z
  | jH                  z   }t        j$                  ||      }t        j                   |dd      \  }}|||z  z
  }d| jH                  z
  | jK                  |      z  }|j                  dd      jM                         }|jO                  |	|d      }| jQ                  |      }||fS )	Nr#   r[   rw   rv   r   rn   ri   r   rf   r]   )ptraining))r   r   r   r   viewr   rZ   rt   r   r   updater   r   r   r`   ru   chunkrepeatmatmulr   sqrtr   
functionalsoftmaxfloat32rc   r]   dropoutr   r   r   sumr   r   r   r   r   r   
contiguousr   r   )r7   r   r   r   rx   r   r   r   kwargsbsz
target_len_q_lenquery_states
key_statesvalue_statesrv   rw   cache_kwargsattn_weightslambda_1lambda_2lambda_fullattn_outputattn_output1attn_output2s                             r9   r>   zDiffLlamaAttention.forward   sX    +//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%'.8L }},,\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((r:   r<   NNNFN)r?   r@   rA   __doc__r$   r   r,   r`   r}   r   
LongTensorr	   boolr>   rB   rC   s   @r9   r   r      s    Gj j3: jJ /304(,26;)||;) #5<<#=>;) t+	;)
 &&-;) ;) ;) ((4/;) 
u||U\\D0%2E2LL	M;)r:   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)r7   argsr   r8   s      r9   r,   z!DiffLlamaFlashAttention2.__init__#  s#    $)&)
 /P.Q+r:   Nr   r   r   rx   r   r   r   rW   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#   r[   r           rj   rk   _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 .rn   sliding_window)rx   r   r   use_top_left_maskr   ri   r   )0rq   r   
ValueErrorr   r   r   r   r   r   rZ   rt   r   r   r   r   r   r   r]   rT   rr   r`   r   is_autocast_enabledget_autocast_dtypehasattrr-   weightr   r   rc   r   r   r   r^   r   r   ru   r   r   r   r   r   r   r   r   r   r   r   )r7   r   r   r   rx   r   r   r   r   r   r   r   r   r   rv   rw   r   dropout_rateinput_dtyperl   target_dtypevalue_states1value_states2r   r   r   r   r   r   s                                r9   r>   z DiffLlamaFlashAttention2.forward+  sT    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^%--'((5$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  r:   r   )r?   r@   rA   r   r,   r`   r}   r   r   r	   r   r>   rB   rC   s   @r9   r   r     s    R 3704(,26u!||u! #5<<#=>u! ((4/	u!
 &&-u! u! u! ((4/u! 
u||T!	"u!r:   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   rx   r   r   r   rW   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   }|d u xr |
dkD  }t        j&                  j(                  j+                  ||||| j,                  r| j.                  nd|      }t        j                   |dd      \  }}t        j0                  t        j2                  | j4                  | j6                  z  dt        j8                  	            j;                  |j<                        }t        j0                  t        j2                  | j>                  | j@                  z  dt        j8                  	            j;                  |j<                        }||z
  | jB                  z   }|||z  z
  }d| jB                  z
  | jE                  |      z  }|j                  dd      jG                         }|j	                  |	|
d      }| jI                  |      }|d fS )
Nr#   r[   r   rn   ri   r   )	attn_mask	dropout_pr   r   )%r   r   r   r   r   r   rZ   rt   r   r   r   r   r   r   r`   ru   r   r   rp   r   r   scaled_dot_product_attentionr   r   r   r   r   r   r   rc   r]   r   r   r   r   r   r   )r7   r   r   r   rx   r   r   r   r   r   r   r   r   r   r   rv   rw   r   causal_maskr   r   r   r   r   r   r   s                             r9   r>   zDiffLlamaSdpaAttention.forward  s(    &**,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  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  r:   r   )r?   r@   rA   r   r`   r}   r   r   r	   r   r>    r:   r9   r   r     s     /304(,26B!||B! #5<<#=>B! t+	B!
 &&-B! B! B! ((4/B! 
u||U\\D0%2E2LL	MB!r:   r   r   c                   h     e Zd Zddeddf fdZdej                  dej                  fdZd Z xZ	S )	DiffLlamaRMSNormr   rW   Nc                     t         |           t        j                  t	        j
                  |            | _        || _        y)z?
        DiffLlamaRMSNorm is equivalent to T5LayerNorm
        N)r+   r,   r   r   r`   onesr   variance_epsilon)r7   r.   r   r8   s      r9   r,   zDiffLlamaRMSNorm.__init__  s1     	ll5::k#:; #r:   r   c                 "   |j                   }|j                  t        j                        }|j	                  d      j                  dd      }|t        j                  || j                  z         z  }| j                  |j                  |      z  S )Nr[   ri   T)keepdim)	r]   rc   r`   r   powmeanrsqrtr  r   )r7   r   r   variances       r9   r>   zDiffLlamaRMSNorm.forward  sy    #))%((7 $$Q',,R,>%Ht?T?T4T(UU{{]--k:::r:   c                 ^    t        | j                  j                         d| j                   S )Nz, eps=)r   r   rp   r  )r7   s    r9   
extra_reprzDiffLlamaRMSNorm.extra_repr  s*    ))*+6$2G2G1HIIr:   )gư>)
r?   r@   rA   rd   r,   r`   r}   r>   r  rB   rC   s   @r9   r  r    s7    $ $$ $;U\\ ;ell ;Jr:   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      r9   r,   zDiffLlamaDecoderLayer.__init__  sz    !--4V5P5PQY_ktu'/0B0BH[H[\(89K9KQWQdQd(e%r:   Nr   r   rx   r   r   r   r   r   rW   c                     |}	| j                  |      } | j                  d|||||||d|\  }}
|	|z   }|}	| j                  |      }| j                  |      }|	|z   }|S )N)r   r   rx   r   r   r   r   r  )r  r  r  r  )r7   r   r   rx   r   r   r   r   r   residualr   s              r9   r>   zDiffLlamaDecoderLayer.forward  s     !,,];)4>> 	
')%+) 3	
 	
q !=0 !55mD/ =0r:   )NNNFNN)r?   r@   rA   r$   r   r,   r`   r}   r   r	   r   r   r   r   r>   rB   rC   s   @r9   r  r    s    f f3 f /304(,!&26HL|| t+ &&-	
  $; ((4/ #5<<#=>E +, 
r:   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_weightsrq   r   initnormal_r   r-   r   r   r   r   )r7   moduler8   s     r9   r#  z&DiffLlamaPreTrainedModel._init_weightsK  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	 2r:   )r?   r@   rA   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#  rB   rC   s   @r9   r  r  9  sp    &*#01#4"5N!"'.(
 U]]_J Jr:   r  c                       e Zd Zdef fdZeee	 	 	 	 	 	 	 ddej                  dz  dej                  dz  dej                  dz  dedz  dej                  dz  d	e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   normrE   
rotary_embgradient_checkpointing	post_initr   s      r9   r,   zDiffLlamaModel.__init__W  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   rx   r   inputs_embedsr   r   r   rW   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_embedsr4  r   r#   )rT   )r-   rC  r   r   r   rx   )rx   )r   r   rx   r   r   r   )last_hidden_stater   )r   r9  r
   r-   get_seq_lengthr`   ra   rp   rT   r   r   r?  r=  r<  r>  r   )r7   rB  r   rx   r   rC  r   r   r   past_seen_tokensr   r   r   decoder_layers                 r9   r>   zDiffLlamaModel.forwardg  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&++
 	
r:   )NNNNNNN)r?   r@   rA   r$   r,   r!   r"   r   r`   r   r}   r	   FloatTensorr   r   r   r   r>   rB   rC   s   @r9   r2  r2  U  s         .2.204(,2626!%9
##d*9
 t+9
 &&-	9

 9
 ((4/9
 ((4/9
 $;9
 +,9
 
!9
    9
r:   r2  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,   r2  r   r7  r   r0   r.   rL  rA  r6   s     r9   r,   zDiffLlamaForCausalLM.__init__  sU     #F+
 ++yy!3!3V5F5FUS 	r:   NrB  r   rx   r   rC  labelsr   r   logits_to_keepr   rW   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?"
        ```)rB  r   rx   r   rC  r   r   N)rN  rP  r7  )lossrN  r   r   r!  r  )r   rE  rq   r   slicerL  loss_functionr-   r7  r   r   r   r!  )r7   rB  r   rx   r   rC  rP  r   r   rQ  r   outputsr   slice_indicesrN  rS  s                   r9   r>   zDiffLlamaForCausalLM.forward  s    @ ,64:: 	,
)%+')	,
 	,
  118B>SV8W~ot4]kmA}a,?@A%4%%pVFt{{OeOepiopD%#33!//))
 	
r:   )	NNNNNNNNr   )r?   r@   rA   _tied_weights_keys_tp_plan_pp_planr,   r   r   r`   r   r}   r	   rI  r   r   r   r   r   r>   rB   rC   s   @r9   rK  rK    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
r:   rK  c                       e Zd Zy)"DiffLlamaForSequenceClassificationNr?   r@   rA   r  r:   r9   r\  r\        r:   r\  c                       e Zd ZdZy)DiffLlamaForQuestionAnsweringtransformerN)r?   r@   rA   r'  r  r:   r9   r`  r`    s    %r:   r`  c                       e Zd Zy)DiffLlamaForTokenClassificationNr]  r  r:   r9   rc  rc    r^  r:   rc  )r  r2  rK  r\  r`  rc  )r#   )Nr   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!   utils.output_capturingr"   configuration_diffllamar$   
get_loggerr?   r   Moduler&   rE   r   r   r}   r   r   r   r   r   r   r  r  r  r  r2  rK  r\  r`  rc  __all__r  r:   r9   <module>ry     s  .  $    & ! ; ; ) Q / i  P K - & R R G 5 4 
		H	%299  ><ryy ><B( *+ ,2	UU\\ 	U# 	U%,, 	U2_) _)DD!1 D!NJ!/ J!Z Y'Jryy J (J*  1" *6 *Z J J J6 M
- M
 M
` H
3_ H
 H
V	)IKc 	&$?AY &	&CE] 	r:   