
    i              
          d Z 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	m
Z
mZm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 ddlmZmZ ddl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-m.Z. ddl/m0Z0m1Z1 ddl2m3Z3  e       rddlm4Z4  e.jj                  e6      Z7 G d dejp                        Z9d Z:dAdZ; G d dejx                        Z=dej|                  de?d ej                  d!ej|                  fd"ZAd#ej|                  d$ej|                  d%eBd&eCd!ej|                  f
d'ZD G d( d)ejx                        ZE G d* d+eE      ZF G d, d-ejx                        ZGeEeEeFd.ZH G d/ d0e       ZIe- G d1 d2e+             ZJe- G d3 d4eJ             ZK e-d56       G d7 d8eJe             ZL e-d96       G d: d;eJ             ZMe- G d< d=eJ             ZNe- G d> d?eJ             ZOg d@ZPy)BzPyTorch Falcon model.    N)Callable)Optional)nn)BCEWithLogitsLossCrossEntropyLoss	LayerNormMSELoss)
functional   )initialization)get_activation)CacheDynamicCacheStaticCache)GenerationMixin)AttentionMaskConverter)!flash_attn_supports_top_left_maskis_flash_attn_available)GradientCheckpointingLayer))BaseModelOutputWithPastAndCrossAttentions!CausalLMOutputWithCrossAttentionsQuestionAnsweringModelOutput SequenceClassifierOutputWithPastTokenClassifierOutput)ROPE_INIT_FUNCTIONSdynamic_rope_update)PreTrainedModel)auto_docstringlogging)is_flash_attention_requestedmaybe_autocast   )FalconConfig)_flash_attention_forwardc                   D    e Zd Zdej                  dej                  fdZy)FalconLinearinputreturnc                 n    || j                   j                  z  }| j                  |S || j                  z   S N)weightTbias)selfr'   hidden_statess      t/home/obispo/Crisostomo_bridge/mision_env/lib/python3.12/site-packages/transformers/models/falcon/modeling_falcon.pyforwardzFalconLinear.forward?   s3    -99  tyy((    N)__name__
__module____qualname__torchTensorr1    r2   r0   r&   r&   >   s    )U\\ )ell )r2   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)shaper6   cat)xx1x2s      r0   rotate_halfrC   G   sZ    	
3"!''"+"""	#B	
3q ""	#B99rc2YB''r2   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.
        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.
    )	unsqueezerC   )qkcossinunsqueeze_dimq_embedk_embeds          r0   apply_rotary_pos_embrM   O   sY    $ --
&C
--
&C3w;q>C/0G3w;q>C/0GGr2   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 )FalconRotaryEmbeddinginv_freqNconfigc                    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defaultrP   F)
persistentoriginal_inv_freq)super__init__max_position_embeddingsmax_seq_len_cachedoriginal_max_seq_lenrQ   rope_parametersrS   compute_default_rope_parametersr   attention_scalingregister_bufferclone)r.   rQ   devicerope_init_fnrP   	__class__s        r0   rX   zFalconRotaryEmbedding.__init__l   s    "("@"@$*$B$B!44[A!%!E!E>>Y&.t~~>L+7V+L($(ZeD0(..2BuUr2   ra   ztorch.deviceseq_lenr(   z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_dimN      ?r   r;   dtypera   rj   )	r\   getattrhidden_sizenum_attention_headsr6   arangeint64tofloat)rQ   ra   rd   baser=   attention_factorrP   s          r0   r]   z5FalconRotaryEmbedding.compute_default_rope_parameters|   s    & %%l3fj$/c63E3EIcIc3c U\\!S!5;;?BB&X]XcXcBdgjjk
 )))r2   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:   r"   mpscpuF)device_typeenabledr;   r<   ri   )rP   rr   expandr>   rq   ra   
isinstancetypestrr!   	transposer6   r?   rH   r^   rI   rj   )
r.   r@   position_idsinv_freq_expandedposition_ids_expandedrx   freqsembrH   rI   s
             r0   r1   zFalconRotaryEmbedding.forward   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)r3   r4   r5   r6   r7   __annotations__r#   rX   staticmethodr   inttuplerr   r]   no_gradr   r1   __classcell__rc   s   @r0   rO   rO   i   s    llV| V  &*+/"*t#*(* t* 
~u$	%	* *: U]]_<  <r2   rO   attention_mask	num_headsrj   r(   c                    | j                   \  }}dt        j                  t        j                  |            z  }t	        j
                  ddt        j                  |      dz
   z   z  | j                  t        j                        }t	        j                  dd|z   | j                  t        j                        }t	        j                  ||      }||k7  rt	        j
                  ddt        j                  d|z        dz
   z   z  | j                  t        j                        }	t        |||z
        }
t	        j                  ddd|
z  z   d| j                  t        j                        }t	        j                  |t	        j                  |	|      gd      }| j                  d      dz
  | z  d d d d d f   }|d   j                         |z  }|j                  ||z  d|      j!                  |      S )	Nr;   r   rk   r"   r   r<   r:   ).N)r>   mathfloorlog2r6   tensorra   float32ro   int32powminr?   cumsumbfloat16reshaperq   )r   r   rj   
batch_size
seq_lengthclosest_power_of_2rs   powersslopes
extra_basenum_remaining_headsextra_powersarange_tensoralibis                 r0   build_alibi_tensorr      s   +11J
djj9)=>><<	tyy!34q899:;NDYDYafananD \\!Q!33N<Q<QY^YdYdeFYYtV$FY&\\A499Q);%;<q@AABCNLaLainiviv

 ""4iBT6TU||Aq1/B+B'BAnNcNckpkvkvwFEIIj,$GHaP %+++3a7>I1dTU:VM9&&(=8E==i/J?BB5IIr2   r@   residualprobtrainingc                 @    t        j                  | ||      }||z   }|S )a
  
    Dropout add function

    Args:
        x (`torch.tensor`):
            input tensor
        residual (`torch.tensor`):
            residual tensor
        prob (`float`):
            dropout probability
        training (`bool`):
            training mode
    )pr   )Fdropout)r@   r   r   r   outs        r0   dropout_addr      s$     ))A
1C
S.CJr2   c                       e Zd Zddef fdZdej                  deej                  ej                  ej                  f   fdZdej                  dej                  fdZ		 	 	 	 	 	 dd	ej                  d
ej                  dz  dej                  dej                  dz  dedz  dededej                  dz  deej                  ej                  f   dz  fdZ xZS )FalconAttentionNrQ   c                    t         |           || _        |j                  | _        |j                  | _        | j                  | j
                  z  | _        | j                  | _        |j                  | _        |j                  | _	        d| _
        || _        |-t        j                  d| j                  j                   d       | j                  | j
                  z  | j                  k7  r&t!        d| j                   d| j
                   d      dt#        j$                  | j                        z  | _        | j&                  | _        |j*                  r*|j,                  dz  |j                  z   | j                  z  }n8|j.                  r| j                  d| j                  z  z   }nd	| j                  z  }t1        | j                  ||j2                  
      | _        |j*                  | _        |j.                  | _        t1        | j                  | j                  |j2                  
      | _        t9        j:                  |j<                        | _        | j*                  s| j.                  s|j,                  | _        y d| _        y )NTz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.zA`hidden_size` must be divisible by num_heads (got `hidden_size`: z and `num_heads`: z).rh   r;   r   r-   r"   )rW   rX   rQ   rm   rn   r   rg   
split_sizehidden_dropoutrY   	is_causal	layer_idxloggerwarning_oncerc   r3   
ValueErrorr   sqrtinv_norm_factorbetanew_decoder_architecturenum_kv_headsmulti_queryr&   r-   query_key_valuedenser   Dropoutattention_dropout)r.   rQ   r   qkv_out_dimrc   s       r0   rX   zFalconAttention.__init__   s    !--33((DNN:**$33'-'E'E$" !8!8 9 :, , ==4>>)T-=-==STXTdTdSe fNN#2'   #TYYt}}%==((	**!..2V5O5OOSWS`S``K**Q->>Kd...K+D,<,<kPVP[P[\(.(G(G%!--!$"2"2D4D4D6;;W
!#F,D,D!E484Q4QY]YiYiF//pqr2   	fused_qkvr(   c                 l   | j                   r|j                  \  }}}|j                  ||d| j                  | j                  z  dz   | j
                        }|ddddddddf   }|dddddddgf   }|dddddddgf   }t        j                  ||j                        }t        j                  ||j                        }|||fD 	cg c]  }	|	j                  dd       c}	\  }}}|||fS | j                  sV|j                  \  }
}}|j                  |
|| j                  d| j
                        }|ddddf   |ddddf   |ddddf   fS |j                  \  }
}}|j                  |
|| j                  dz   | j
                        }|dddddf   |ddgddf   |ddgddf   fS c c}	w )	a  
        Split the last dimension into (num_heads, head_dim), results share same memory storage as `fused_qkv`

        Args:
            fused_qkv (`torch.tensor`): [batch_size, seq_length, num_heads * 3 * head_dim]

        Returns:
            query: [batch_size, seq_length, num_heads, head_dim] key: [batch_size, seq_length, num_heads, head_dim]
            value: [batch_size, seq_length, num_heads, head_dim]
        r:   r;   Nr   .r   r"   )
r   r>   viewr   r   rg   r6   broadcast_toflattenr   )r.   r   batchrd   _qkvquerykeyvaluer@   r   r   three_times_hidden_sizes                r0   _split_headszFalconAttention._split_heads  s    (( )E7A..T^^tGXGX5X[\5\^b^k^klC1a"%EaAtm$C1a"&E$$S%++6C&&uekk:E;@#u:M NQ1a NE3#u$$!!>Goo;J
$;!z:t~~qRVR_R_`IS!QY'319)=yaQR?SSS>Goo;J
$;!z:t~~PQ?QSWS`S`aIS#2#q[)9S2$\+BIcTVSWYZlD[[[ !Os   F1r@   c                    |j                   \  }}}|| j                  z  }|j                  || j                  || j                        }|j	                  dddd      }|j                  ||| j                  | j                  z        S )z
        Merge heads together over the last dimension

        Args:
            x (`torch.tensor`): [batch_size * num_heads, seq_length, head_dim]

        Returns:
            torch.tensor: [batch_size, seq_length, num_heads * head_dim]
        r   r;   r"   r   )r>   r   r   rg   permuter   )r.   r@   batch_size_and_num_headsr   r   r   s         r0   _merge_headszFalconAttention._merge_heads%  sy     34''/ *a-?
 FF:t~~z4==I IIaAq! yyZ$--1OPPr2   r/   r   r   r   
layer_past	use_cacheoutput_attentionscache_positionposition_embeddingsc
                 p
   | j                  |      }
| j                  r| j                  n| j                  }| j	                  |
      \  }}}|j
                  \  }}}}|j                  dd      j                  || j                  || j                        }|j                  dd      j                  |||| j                        }|j                  dd      j                  |||| j                        }||	\  }}t        ||||      \  }}|;d|i}||j                  d       |j                  ||| j                  |      \  }}|j
                  d   }| j                  j                  dk(  rK|j                  j                  dk(  r2|0|j!                         }|j!                         }|j!                         }||d d d d d d d |j
                  d   f   }|B| j                  j                  dk(  rM|sK| j"                  xr |d u xr |dkD  }t$        j&                  j(                  j+                  ||||d|	      }d }na||j                  d
d      z  }|t-        j.                  | j                        z  }t1        j2                  ||z   d
|j4                        }||z  }|j7                  || j                  || j                        }|j9                  dddd      }|j                  ||| j                  | j                  z        }| j;                  |      }||fS | j                  j                  dk(  r|s| j"                  xr |d u xr |dkD  }t$        j&                  j(                  j+                  ||||| j<                  r| j>                  j@                  nd|	      }d }|j                  dd      }|j                  ||| j                  | j                  z        }| j;                  |      }||fS ||j                  d
d      z  }|j7                  || j                  ||      }|j4                  }|t$        jB                  k(  s|t$        jD                  k(  r|jG                  t$        jH                        }||j7                  || j                  dd
      z   }|| jJ                  z  }t1        j2                  ||z   d
|j4                        }| j?                  |      }|j7                  || j                  ||      }||z  jM                  dd      }| jO                  |      }| j;                  |      }||fS )Nr"   r;   r   rI   rH   r   sdpacuda        )	attn_mask	dropout_pr   r:   )r=   rj   r   r   )(r   r   r   r   r   r>   r~   r   rg   rM   updater   rQ   _attn_implementationra   r|   
contiguousr   r6   r   r
   scaled_dot_product_attentionr   r   r   softmaxrj   r   r   r   r   r   r   float16r   rq   r   r   r   r   )r.   r/   r   r   r   r   r   r   r   r   r   r   query_layer	key_layervalue_layerr   query_lengthr   rH   rI   cache_kwargs	kv_lengthr   attn_outputattention_scoresattention_probsmatmul_resultinput_dtypeattention_logitsattention_probs_reshapeds                                 r0   r1   zFalconAttention.forward>  s'    ((7	)-)F)Ft~~DL]L]040A0A)0L-i)4):):&
L!Q!++Aq199*dnnVbdhdqdqr''1-55j,P\^b^k^kl	!++Aq199*lT`bfbobop=*HC%9+yRUWZ%["K!,n=L}##C$<=%/%6%6y+t~~_k%l"I{OOB'	KK,,6""''61* &002K!,,.I%002K%+Aq!5Jyr7J5J,JKN={{//69BS
 !NNZ~/EZ,YZJZ	#hh11NN,!' O  $( #.1D1DR1L#L  DIIdmm$<< #$99-=-NTV^k^q^q#r .<%**:t~~|UYUbUbcK%--aAq9K%--j,Y]YfYfHfgK**[1K 000 {{//69BS !NNZ~/EZ,YZJZ	#hh11NN,:>--d4466S' O  #')33Aq9)11*lDNN]a]j]jLjk"jj5< //9 !,i.A.A"b.I I $1#5#5j$..R^`i#j  /44%--/;%..3P'7':':5=='I$#3ejjT^^]^`b6c#c  D$8$88 "#)),<~,MSU]j]p]p"q"&"8"8"I ,;+?+?
DNN\hjs+t(  8+ENNqRST #//<"jj5//r2   r*   NNFFNN)r3   r4   r5   r#   rX   r6   r7   r   r   r   
LongTensorr   boolr1   r   r   s   @r0   r   r      s#   (r| (rT\ell \uU\\5<<Y^YeYe=e7f \@Qell Qu|| Q< 15#'"'26HL0||0 ||d"0 	0
 &&-0 DL0 0  0 ((4/0 #5<<#=>E0r2   r   c                       e Zd ZdZ fdZ	 	 	 	 	 	 ddej                  dej                  dz  dej                  dej                  dz  dedz  d	e	d
e	dej                  dz  de
ej                  ej                  f   dz  fdZ xZS )FalconFlashAttention2aH  
    Falcon flash attention module. This module inherits from `FalconAttention` 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*   )rW   rX   r   _flash_attn_uses_top_left_mask)r.   argskwargsrc   s      r0   rX   zFalconFlashAttention2.__init__  s#    $)&)
 /P.Q+r2   Nr/   r   r   r   r   r   r   r   r   c
                 T   | j                  |      }
| j                  r| j                  n| j                  }| j	                  |
      \  }}}|j
                  \  }}}}|j                  dd      j                  || j                  || j                        }|j                  dd      j                  |||| j                        }|j                  dd      j                  |||| j                        }||	\  }}t        ||||      \  }}|;d|i}||j                  d       |j                  ||| j                  |      \  }}|j                  dd      }|j                  dd      }|j                  dd      }|t        d      | j                  r| j                  j                  nd}|j                   }|j"                  j$                  dk7  r|j"                  j$                  nd}|t&        j(                  k(  rt'        j*                         rt'        j,                  |      }nMt/        | j                  d	      r| j                  j                   }n | j                   j0                  j                   }t2        j5                  d
| d       |j7                  |      }|j7                  |      }|j7                  |      }t9        |||||||| j:                  | j<                  	      }|j                  ||| j                  | j                  z        }| j?                  |      }|sd }||fS )Nr"   r;   r   r   z6`alibi` is not supported when `use_flash_attn` is Truer   rv   rw   _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 .)r   r   r   use_top_left_mask) r   r   r   r   r   r>   r~   r   rg   rM   r   r   r   r   rQ   r   rj   ra   r|   r6   r   is_autocast_enabledget_autocast_dtypehasattrr+   r   r   rq   r$   r   r   r   )r.   r/   r   r   r   r   r   r   r   r   r   r   r   r   r   r   r   r   rH   rI   r   attn_dropoutr   rx   target_dtyper   attn_weightss                              r0   r1   zFalconFlashAttention2.forward  s    ((7	)-)F)Ft~~DL]L]040A0A)0L-i)4):):&
L!Q!++Aq199*dnnVbdhdqdqr''1-55j,P\^b^k^kl	!++Aq199*lT`bfbobop=*HC%9+yRUWZ%["K!,n=L}##C$<=%/%6%6y+t~~_k%l"I{ "++Aq1''1-	!++Aq1UVV8<t{{443
 "''1<1C1C1H1HE1Qk((--W\%--'((*$77Do6#{{00#33::@@ >$ &..6K!\2I%..6K.% nn"AA

 #**:|T^^VZVcVcEcdjj. LL((r2   r   )r3   r4   r5   __doc__rX   r6   r7   r   r   r   r   r1   r   r   s   @r0   r   r     s    R 15#'"'26HLV)||V) ||d"V) 	V)
 &&-V) DLV) V)  V) ((4/V) #5<<#=>EV)r2   r   c                   \     e Zd Zdef fdZdej                  dej                  fdZ xZS )	FalconMLPrQ   c                 ,   t         |           |j                  }t        ||j                  |j
                        | _        t        |j                        | _	        t        |j                  ||j
                        | _
        |j                  | _        y )Nr   )rW   rX   rm   r&   ffn_hidden_sizer-   dense_h_to_4hr   
activationactdense_4h_to_hr   )r.   rQ   rm   rc   s      r0   rX   zFalconMLP.__init__)  su    (()+v7M7MTZT_T_`!&"3"34)&*@*@+TZT_T_`$33r2   r@   r(   c                 h    | j                  | j                  |            }| j                  |      }|S r*   )r  r  r  )r.   r@   s     r0   r1   zFalconMLP.forward2  s0    HHT''*+q!r2   )	r3   r4   r5   r#   rX   r6   r7   r1   r   r   s   @r0   r	  r	  (  s*    4| 4 %,, r2   r	  )eagerr   flash_attention_2c                   L    e Zd Zddef fdZ	 	 	 	 	 	 ddej                  dej                  dz  dej                  dej                  dz  dee	ej                  ej                  f   z  dz  d	e
d
e
dej                  dz  de	ej                  ej                  f   dz  fdZ xZS )FalconDecoderLayerNrQ   c                 x   t         |           |j                  }|j                  | _        t        |j                     ||      | _        t        |      | _	        |j                  | _
        || _        |j                  |j                  rd|_        |j                  s9t        ||j                         | _        t        ||j                         | _        y |j                  dk(  r9t        ||j                         | _        t        ||j                         | _        y t        ||j                         | _        y )Nr;   eps)rW   rX   rm   rn   r   FALCON_ATTENTION_CLASSESr   self_attentionr	  mlpr   rQ   num_ln_in_parallel_attnr   parallel_attnr   layer_norm_epsilonpost_attention_layernorminput_layernormln_attnln_mlp)r.   rQ   r   rm   rc   s       r0   rX   zFalconDecoderLayer.__init__@  s    ((336v7R7RSTZ\efV$$33))1f6U6U-.F*##,5kvG`G`,aD)#,[f>W>W#XD --2(&:S:ST'9R9RS'0&B[B['\$r2   r/   r   r   r   r   r   r   r   r   c
                 T   |}| j                   j                  r<| j                   j                  dk(  r#| j                  |      }| j	                  |      }n| j                  |      }| j                  |||||||||		      \  }}| j                   j                  sW| j                   j                  r|}n>t        ||| j                   j                  | j                        }| j                  |      }| j                   j                  r1| j                   j                  r| j                   j                  dk(  r|}| j                        }| j                   j                  s| j                   j                  r||z  }t        ||| j                   j                  | j                        }||fS )Nr;   )r   r   r   r   r   r   r   r   )r   r"   )rQ   r   r  r   r!  r  r  r  r   r   r   r  r  r   )r.   r/   r   r   r   r   r   r   r   r   r   r   attention_layernorm_outmlp_layernorm_outattention_outputr  
mlp_outputoutputs                     r0   r1   zFalconDecoderLayer.forwardY  s}    !;;//DKK4W4W[\4\&*ll=&A# $M :&*&:&:=&I# *.)<)<#!)%/) 3 *= 
*
&, {{33{{(($;!&$h0M0MX\XeXe %)$A$A($K! KK00))33q8 7 XX/0
;;//4;;3L3L**JZ4;;3M3MX\XeXef|##r2   r*   r   )r3   r4   r5   r#   rX   r6   r7   r   r   r   r   r1   r   r   s   @r0   r  r  ?  s    ]| ]< 15GK"'26HL:$||:$ ||d":$ 	:$
 &&-:$ E%,,"<==D:$ :$  :$ ((4/:$ #5<<#=>E:$r2   r  c                        e Zd ZU eed<   dZdZdgZdZdZ	dZ
 ej                         dej                  f fd       Zed	defd       Z xZS )
FalconPreTrainedModelrQ   transformerTr  modulec                 
   t         |   |       t        |t              rct	        j
                  |j                  d| j                  j                         |j                   t	        j                  |j                         yyy)zInitialize the weights.r   )meanstdN)rW   _init_weightsr{   r&   initnormal_r+   rQ   initializer_ranger-   zeros_)r.   r+  rc   s     r0   r/  z#FalconPreTrainedModel._init_weights  s^     	f%fl+LLSdkk6S6ST{{&FKK( ' ,r2   hard_check_onlyc                 :    t        | dd      }|r|S |sd|_        |S )Nuse_bettertransformerFr   )rl   r   )clsrQ   r4  _is_bettertransformers       r0   _check_and_enable_sdpaz,FalconPreTrainedModel._check_and_enable_sdpa  s*     '-De L M*0F'r2   )F)r3   r4   r5   r#   r   base_model_prefixsupports_gradient_checkpointing_no_split_modules_supports_flash_attn_supports_sdpa_can_compile_fullgraphr6   r   r   Moduler/  classmethodr   r9  r   r   s   @r0   r)  r)    so    %&*#-.N!U]]_)BII ) ) T  r2   r)  c                   8    e Zd Zdef fdZd Zdej                  fdZe		 	 	 	 	 	 	 	 	 	 ddej                  dz  dedz  d	ej                  dz  d
ej                  dz  dej                  dz  dedz  dedz  dedz  dedz  dej                  dz  deej                  df   ez  fd       Zd	ej                  dej                  dej                  dededej                  fdZed	ej                  dededej&                  dej                  defd       Z xZS )FalconModelrQ   c           	         t         |   |       |j                  | _        |j                  | _        |j                  | _        t        j                  |j                  | j                        | _        t        j                  t        |j                        D cg c]  }t        ||       c}      | _        t#        | j                  |j$                        | _        d| _        t+        |      | _        | j/                          y c c}w )N)r   r  FrQ   )rW   rX   rm   	embed_dimrn   r   r   	use_alibir   	Embedding
vocab_sizeword_embeddings
ModuleListrangenum_hidden_layersr  hr   r  ln_fgradient_checkpointingrO   
rotary_emb	post_init)r.   rQ   irc   s      r0   rX   zFalconModel.__init__  s     ++33  "||F,=,=t~~N QVW]WoWoQpqA 26Q Gqr dnn&2K2KL	&+#/v> 	  rs   Dc                     | j                   S r*   rJ  )r.   s    r0   get_input_embeddingsz FalconModel.get_input_embeddings  s    ###r2   new_embeddingsc                     || _         y r*   rU  r.   rW  s     r0   set_input_embeddingsz FalconModel.set_input_embeddings  s
    -r2   N	input_idspast_key_valuesr   r   inputs_embedsr   r   output_hidden_statesreturn_dictr   r(   .c                    ||n| j                   j                  }||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}|| j                  |      }|r|t        | j                         }d}||j                         nd}|j                  \  }}}| j                  r[|5t        j                   |||z   f|j"                  t        j$                        n|}t'        || j(                  |j*                        }|
%t        j,                  |||z   |j"                  	      }
||
j/                  d      }| j1                  |||
|||      }|}| j3                  ||
      }|rdnd}|rdnd}t5        | j6                        D ]/  \  }}|r||fz   } |||||||||
|	      }|d   }|s'||d   fz   }1 | j9                  |      }|r||fz   }|	st;        d ||||fD              S t=        ||||      S )  
        input_ids (`torch.LongTensor` of shape `(batch_size, input_ids_length)`):
            `input_ids_length` = `sequence_length` if `past_key_values` is `None` else `past_key_values.get_seq_length()`
            (`sequence_length` of input past key value states). Indices of input sequence tokens in the vocabulary.

            If `past_key_values` is used, only `input_ids` that do not have their past calculated should be passed as
            `input_ids`.

            Indices can be obtained using [`AutoTokenizer`]. See [`PreTrainedTokenizer.encode`] and
            [`PreTrainedTokenizer.__call__`] for details.

            [What are input IDs?](../glossary#input-ids)
        Nz:You must specify exactly one of input_ids or inputs_embedszZ`use_cache=True` is incompatible with gradient checkpointing. Setting `use_cache=False`...FrE  r   rk   ri   ra   )r   r8   )r   r   r   r   r   r   r   r   r"   c              3   &   K   | ]	  }||  y wr*   r8   ).0vs     r0   	<genexpr>z&FalconModel.forward.<locals>.<genexpr>@  s      ghgts   )last_hidden_stater\  r/   
attentions)rQ   r   r^  r   use_return_dictr   rP  r   r   r   rJ  r   get_seq_lengthr>   rG  r6   onesra   longr   r   rj   ro   rE   _update_causal_maskrQ  	enumeraterN  rO  r   r   )r.   r[  r\  r   r   r]  r   r   r^  r_  r   r   r   past_key_values_lengthr   r   r   maskcausal_maskr/   r   all_self_attentionsall_hidden_statesrS  blockoutputss                             r0   r1   zFalconModel.forward  s   8 2C1N-TXT_T_TqTq$8$D $++JjJj 	 "+!6IDKK<Q<Q	%0%<k$++B]B]-t";<YZZ&&4==##p "	  00;M0*$++>O ETE`!?!?!Afg$1$7$7!
J>>
 ") 

.D!DEmNbNbjojtjt $  'tT^^=CVCVWE!"\\&(>(KTaThThN )33A6L..M>?L]_d
 &"oom,oW$5b4"6BD!$&&) 	JHAu#$58H$H!**)#"3-$7
G $AJM &9WQZM&I#%	J* 		-0 1]4D D )?<MObc   9+++*	
 	
r2   input_tensorr   c           
         t        | j                        r	|d|v r|S y ||j                         nd}t        |t              }| j                  j
                  dk(  r*|s(|s&|$t        j                  |||| j                        ry |j                  |j                  }
}	t        j                  |	      j                  }|j                  \  }}}|r|j                         }n.t        |t        j                         r|j                  d   n||z   }| j#                  ||||	|
||j                  d         }|r |j$                  |dg|j                  dd   }t        j&                  |t)        j*                  | j                  j,                  | j.                  z        z  |dk  |      }| j                  j
                  dk(  r2|0|j                  j0                  dv r|st        j2                  ||      }|S )	Nr   r   r   )r]  ro  is_trainingr:   )sequence_lengthtarget_lengthrj   ra   r   r   r"   )r   xpunpu)r    rQ   rj  r{   r   r   r   _ignore_causal_mask_sdpar   rj   ra   r6   finfor   r>   get_max_cache_shaper7   5_prepare_4d_causal_attention_mask_with_cache_positionr   masked_fillr   r   rm   r   r|   _unmask_unattended)r.   r   rv  r   r\  r   r   past_seen_tokensusing_static_cacherj   ra   	min_dtyper   ry  r   rz  rq  s                    r0   rm  zFalconModel._update_causal_maskK  s    (4)c^.C%%
 @O?Z?99;`a'E KK,,6&%%>>*'7 MM	 $**L,?,?vKK&**	)5););&
OQ+??AM nell; $$R(%7  PP+')#))!, Q 
 !EMM*bC5;;qr?CE++		$++"9"9T^^"KLLb K KK,,6*%%**.DD%
 1CCKQZ[Kr2   ry  rz  rj   r   c                    | | j                         dk(  r| }|S t        j                  |      j                  }t        j                  ||f|||j
                        }|dk7  rt        j                  |d      }|t        j                  ||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 )	aM  
        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.
            cache_position (`torch.Tensor`):
                Indices depicting the position of the input sequence tokens in the sequence.
            batch_size (`torch.Tensor`):
                Batch size.
        N   )
fill_valuerj   ra   r"   )diagonalrb  r:   r   )r=   r6   r~  r   fullra   triuro   r   rz   r`   r>   rq   r  )r   ry  rz  rj   r   r   r   rq  r  mask_lengthpadding_masks              r0   r  zAFalconModel._prepare_4d_causal_attention_mask_with_cache_position  s   > %.*<*<*>!*C(K* ' E*..I** -0Ye\j\q\qK !##jjqA5<<n>S>STWeWmWmnprsWtttK%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 r2   )
NNNNNNNNNN)r3   r4   r5   r#   rX   rV  r6   r7   rZ  r   r   r   r   r   r   r1   rm  r   r   rj   r  r   r   s   @r0   rC  rC    s   | *$.5<< .  .2(,.20415!%)-,0#'26v
##d*v
 v
 t+	v

 &&-v
 ''$.v
 $;v
  $;v
 #Tkv
 D[v
 ((4/v
 
u||S 	!$M	Mv
 v
pSS llS 	S
 S  S ||Sj 444 4 {{	4
 4 4 4r2   rC  z
    The Falcon Model transformer with a language modeling head on top (linear layer with weights tied to the input embeddings).
    )custom_introc                       e Zd ZddiZdef fdZdej                  fdZe		 	 	 	 	 	 	 	 	 	 	 	 ddej                  dz  d	edz  d
ej                  dz  dej                  dz  dej                  dz  dej                  dz  dedz  dedz  dedz  dedz  dej                  dz  deej                  z  deej                     ez  fd       Z xZS )FalconForCausalLMzlm_head.weightz"transformer.word_embeddings.weightrQ   c                     t         |   |       t        |      | _        t	        j
                  |j                  |j                  d      | _        | j                          y NFr   )
rW   rX   rC  r*  r   Linearrm   rI  lm_headrR  r.   rQ   rc   s     r0   rX   zFalconForCausalLM.__init__  sI     &v.yy!3!3V5F5FUS 	r2   rW  c                     || _         y r*   )r  rY  s     r0   set_output_embeddingsz'FalconForCausalLM.set_output_embeddings  s	    %r2   Nr[  r\  r   r   r]  labelsr   r   r^  r_  r   logits_to_keepr(   c                    |
|
n| j                   j                  }
| j                  ||||||||	|
|
      }|d   }t        |t              rt        | d      n|}| j                  |dd|ddf         }d}|* | j                  ||fd| j                   j                  i|}|
s|f|dd z   }||f|z   S |S t        |||j                  |j                  |j                        S )a\  
        input_ids (`torch.LongTensor` of shape `(batch_size, input_ids_length)`):
            `input_ids_length` = `sequence_length` if `past_key_values` is `None` else `past_key_values.get_seq_length()`
            (`sequence_length` of input past key value states). Indices of input sequence tokens in the vocabulary.

            If `past_key_values` is used, only `input_ids` that do not have their past calculated should be passed as
            `input_ids`.

            Indices can be obtained using [`AutoTokenizer`]. See [`PreTrainedTokenizer.encode`] and
            [`PreTrainedTokenizer.__call__`] for details.

            [What are input IDs?](../glossary#input-ids)
        labels (`torch.LongTensor` of shape `(batch_size, sequence_length)`, *optional*):
            Labels for language modeling. Note that the labels **are shifted** inside the model, i.e. you can set
            `labels = input_ids` Indices are selected in `[-100, 0, ..., config.vocab_size]` All labels set to `-100`
            are ignored (masked), the loss is only computed for labels in `[0, ..., config.vocab_size]`
        N)	r\  r   r   r]  r   r   r^  r_  r   r   rI  r"   losslogitsr\  r/   rh  )rQ   ri  r*  r{   r   slicer  loss_functionrI  r   r\  r/   rh  )r.   r[  r\  r   r   r]  r  r   r   r^  r_  r   r  r   transformer_outputsr/   slice_indices	lm_logitsr  r'  s                       r0   r1   zFalconForCausalLM.forward  s/   F &1%<k$++B]B]"..+)%'/!5#) / 
 ,A.8B>SV8W~ot4]kLLq-/B!CD	%4%%  ;;11 	D \$7$;;F)-)9TGf$EvE0/??-;;*55
 	
r2   )NNNNNNNNNNNr   )r3   r4   r5   _tied_weights_keysr#   rX   r6   r7   r  r   r   r   r   r   r   r   r1   r   r   s   @r0   r  r    s^    +,PQ| &ELL &  .2(,.204-1&*!%)-,0#'26-.H
##d*H
 H
 t+	H

 &&-H
 ||d*H
 t#H
 $;H
  $;H
 #TkH
 D[H
 ((4/H
 ell*H
 
u||	@	@H
 H
r2   r  a  
    The Falcon Model transformer with a sequence classification head on top (linear layer).

    [`FalconForSequenceClassification`] uses the last token in order to do the classification, as other causal models
    (e.g. GPT-1) 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def fdZe	 	 	 	 	 	 	 	 	 ddej                  dz  dedz  dej                  dz  dej                  dz  dej                  dz  d	e
dz  d
e
dz  de
dz  de
dz  deej                     ez  fd       Z xZS )FalconForSequenceClassificationrQ   c                     t         |   |       |j                  | _        t        |      | _        t        j                  |j                  |j                  d      | _        | j                          y r  )
rW   rX   
num_labelsrC  r*  r   r  rm   scorerR  r  s     r0   rX   z(FalconForSequenceClassification.__init__G  sV      ++&v.YYv1163D3D5Q
 	r2   Nr[  r\  r   r]  r  r   r   r^  r_  r(   c
           
      r   |	|	n| j                   j                  }	| j                  ||||||||	      }|d   }| 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"                  | j$                  dk(  rd
| j                   _        nl| j$                  dkD  rL|j&                  t        j(                  k(  s|j&                  t        j*                  k(  rd| j                   _        nd| j                   _        | j                   j"                  d
k(  rIt-               }| j$                  dk(  r& ||j/                         |j/                               }nc |||      }nY| j                   j"                  dk(  rt1               } |||      }n,| j                   j"                  dk(  rt3               } |||      }|	s|f|dd z   }||f|z   S |S t5        |||j6                  |j8                  |j:                        S )6  
        input_ids (`torch.LongTensor` of shape `(batch_size, input_ids_length)`):
            `input_ids_length` = `sequence_length` if `past_key_values` is `None` else `past_key_values.get_seq_length()`
            (`sequence_length` of input past key value states). Indices of input sequence tokens in the vocabulary.

            If `past_key_values` is used, only `input_ids` that do not have their past calculated should be passed as
            `input_ids`.

            Indices can be obtained using [`AutoTokenizer`]. See [`PreTrainedTokenizer.encode`] and
            [`PreTrainedTokenizer.__call__`] for details.

            [What are input IDs?](../glossary#input-ids)
        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).
        Nr\  r   r]  r   r   r^  r_  r   r"   z=Cannot handle batch sizes > 1 if no padding token is defined.r:   rk   z will not detect padding tokens in `inputs_embeds`. Results may be unexpected if using padding tokens in conjunction with `inputs_embeds.`rb  
regressionsingle_label_classificationmulti_label_classificationr  )rQ   ri  r*  r  r>   pad_token_idr   rq   ra   r6   r   ro   argmaxr   r   rc   r3   problem_typer  rj   rl  r   r	   squeezer   r   r   r\  r/   rh  )r.   r[  r\  r   r]  r  r   r   r^  r_  r   r  r/   r  r   last_non_pad_tokennon_pad_masktoken_indicespooled_logitsr  loss_fctr'  s                         r0   r1   z'FalconForSequenceClassification.forwardP  s   @ &1%<k$++B]B]"..+)'/!5# / 	
 ,A.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{{''/??a'/;DKK,__q(fllejj.HFLL\a\e\eLe/LDKK,/KDKK,{{''<7"9??a'#M$9$9$;V^^=MND#M6:D))-JJ+-v6))-II,.v6#%(;AB(??F)-)9TGf$EvE/ /??-;;*55
 	
r2   	NNNNNNNNN)r3   r4   r5   r#   rX   r   r6   r   r   r7   r   r   r   r1   r   r   s   @r0   r  r  8  s    |   .2(,.2-1&*!%)-,0#'f
##d*f
 f
 t+	f

 ||d*f
 t#f
 $;f
  $;f
 #Tkf
 D[f
 
u||	?	?f
 f
r2   r  c                       e Zd Zdef fdZe	 	 	 	 	 	 	 	 	 ddej                  dz  dedz  dej                  dz  dej                  dz  dej                  dz  d	e
dz  d
e
dz  de
dz  de
dz  deej                     ez  fd       Z xZS )FalconForTokenClassificationrQ   c                    t         |   |       |j                  | _        t        |      | _        t        |dd       |j                  }nt        |dd       |j                  }nd}t        j                  |      | _
        t        j                  |j                  |j                        | _        | j                          y )Nclassifier_dropoutr   g?)rW   rX   r  rC  r*  rl   r  r   r   r   r   r  rm   
classifierrR  )r.   rQ   r  rc   s      r0   rX   z%FalconForTokenClassification.__init__  s      ++&v.6/6B!'!:!:V-t4@!'!6!6!$zz"45))F$6$68I8IJ 	r2   Nr[  r\  r   r]  r  r   r   r^  r_  r(   c
           
         |	|	n| j                   j                  }	| j                  ||||||||	      }|d   }| j                  |      }| j	                  |      }d}|Q|j
                  \  }}t               } ||j                  ||z  | j                        |j                  ||z              }|	s|f|dd z   }||f|z   S |S t        |||j                  |j                        S )r  Nr  r   r;   )r  r  r/   rh  )rQ   ri  r*  r   r  r>   r   r   r  r   r/   rh  )r.   r[  r\  r   r]  r  r   r   r^  r_  r   r  r/   r  r  r   r   r  r'  s                      r0   r1   z$FalconForTokenClassification.forward  s   @ &1%<k$++B]B]"..+)'/!5# / 	
 ,A.]3/%+\\"J
')HJ3T__Ev{{S]`jSjGkD Y!4QR!88F)-)9TGf$EvE$-;;*55	
 	
r2   r  )r3   r4   r5   r#   rX   r   r6   r   r   r7   r   r   r   r1   r   r   s   @r0   r  r    s    | "  .2(,.2-1&*!%)-,0#'A
##d*A
 A
 t+	A

 ||d*A
 t#A
 $;A
  $;A
 #TkA
 D[A
 
u||	4	4A
 A
r2   r  c                        e Zd Z fdZe	 	 	 	 	 	 	 	 ddej                  dz  dej                  dz  dej                  dz  dej                  dz  dej                  dz  dedz  d	edz  d
edz  de	e
z  fd       Z xZS )FalconForQuestionAnsweringc                     t         |   |       t        |      | _        t	        j
                  |j                  d      | _        | j                          y )Nr;   )	rW   rX   rC  r*  r   r  rm   
qa_outputsrR  r  s     r0   rX   z#FalconForQuestionAnswering.__init__  sA     &v.))F$6$6: 	r2   Nr[  r   r]  start_positionsend_positionsr   r^  r_  r(   c	                 "   ||n| j                   j                  }| j                  ||||||      }
|
d   }| j                  |      }|j	                  dd      \  }}|j                  d      j                         }|j                  d      j                         }d}||t        |j                               dkD  r|j                  d      }t        |j                               dkD  r|j                  d      }|j                  d      }|j                  d|      }|j                  d|      }t        |      } |||      } |||      }||z   dz  }|s||f|
dd z   }||f|z   S |S t        ||||
j                  |
j                  	      S )
ra  N)r   r]  r   r^  r_  r   r"   r:   r<   )ignore_indexr;   )r  start_logits
end_logitsr/   rh  )rQ   ri  r*  r  splitr  r   lensizeclampr   r   r/   rh  )r.   r[  r   r]  r  r  r   r^  r_  r   ru  sequence_outputr  r  r  
total_lossignored_indexr  
start_lossend_lossr'  s                        r0   r1   z"FalconForQuestionAnswering.forward  s   4 &1%<k$++B]B]"")'/!5# # 
 "!*1#)<<r<#: j#++B/::<''+668

&=+D?'')*Q."1"9"9""==%%'(1, - 5 5b 9(--a0M-33A}EO)//=AM']CH!,@J
M:H$x/14J"J/'!"+=F/9/EZMF*Q6Q+%!!//))
 	
r2   )NNNNNNNN)r3   r4   r5   rX   r   r6   r   FloatTensorr   r   r   r1   r   r   s   @r0   r  r    s      .237263715)-,0#'F
##d*F
 ))D0F
 ((4/	F

 ))D0F
 ''$.F
  $;F
 #TkF
 D[F
 
-	-F
 F
r2   r  )r  rC  r)  r  r  r  )r"   )Qr  r   collections.abcr   typingr   r6   r   torch.nnr   r   r   r	   r
   r    r   r0  activationsr   cache_utilsr   r   r   
generationr   modeling_attn_mask_utilsr   modeling_flash_attention_utilsr   r   modeling_layersr   modeling_outputsr   r   r   r   r   modeling_rope_utilsr   r   modeling_utilsr   utilsr   r   utils.genericr    r!   configuration_falconr#   r$   
get_loggerr3   r   r  r&   rC   rM   r@  rO   r7   r   rj   r   rr   r   r   r   r   r	  r  r  r)  rC  r  r  r  r  __all__r8   r2   r0   <module>r     sC     $    L L $ & ) ; ; ) i 9  . J . J			H	%
)299 )(4><BII ><BJu|| J JEKK J\a\h\h J:5<< 5<< u PT Y^YeYe &c0bii c0Le)O e)P		 " . T$3 T$n O  < `' ` `F	 
W
- W

W
t q
&; q
q
h T
#8 T
 T
n P
!6 P
 P
fr2   