
    g.             
       h   d Z ddlZddlmZmZmZmZ ddl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mZmZ dd
lmZ ddlmZ ddlmZmZmZmZm Z  ddl!m"Z" ddl#m$Z$ ddl%m&Z& ddl'm(Z(m)Z)m*Z*m+Z+m,Z,m-Z- ddl.m/Z/ erddl0m1Z1  e+            rddl2m3Z3  e-j4        e5          Z6dZ7dZ8 G d de	j9                  Z:d Z;dGdZ< G d de	j=                  Z> G d de>          Z? G d d e>          Z@d!ejA        d"eBd#ejC        d$ejA        fd%ZDd&ejA        d'ejA        d(eEd)eFd$ejA        f
d*ZG G d+ d,e	j=                  ZH G d- d.eH          ZI G d/ d0e	j=                  ZJeHeHeId1ZK G d2 d3e	j=                  ZLd4ZMd5ZN G d6 d7e$          ZO e)d8eM           G d9 d:eO                      ZP e)d;eM           G d< d=eOe                      ZQ e)d>eM           G d? d@eO                      ZR e)dAeM           G dB dCeO                      ZS e)dDeM           G dE dFeO                      ZTdS )HzPyTorch Falcon model.    N)TYPE_CHECKINGOptionalTupleUnion)nn)BCEWithLogitsLossCrossEntropyLoss	LayerNormMSELoss)
functional   )get_activation)CacheDynamicCacheStaticCache)GenerationMixin)AttentionMaskConverter))BaseModelOutputWithPastAndCrossAttentions!CausalLMOutputWithCrossAttentionsQuestionAnsweringModelOutput SequenceClassifierOutputWithPastTokenClassifierOutput)ROPE_INIT_FUNCTIONS)PreTrainedModel)"is_torch_greater_or_equal_than_2_0)add_code_sample_docstringsadd_start_docstrings%add_start_docstrings_to_model_forwardis_flash_attn_2_available#is_flash_attn_greater_or_equal_2_10logging   )FalconConfig)PretrainedConfig)_flash_attention_forwardzRocketknight1/falcon-rw-1br#   c                   2    e Zd Zdej        dej        fdZdS )FalconLinearinputreturnc                 F    || j         j        z  }| j        |S || j        z   S N)weightTbias)selfr(   hidden_statess      f/var/www/html/ai-engine/env/lib/python3.11/site-packages/transformers/models/falcon/modeling_falcon.pyforwardzFalconLinear.forwardE   s+    -9  ty((    N)__name__
__module____qualname__torchTensorr2    r3   r1   r'   r'   D   s:        )U\ )el ) ) ) ) ) )r3   r'   c                     | dd| j         d         dz  f         }| d| j         d         dz  df         }t          j        | |fd          S )z*Rotates half the hidden dims of the input..N   dim)shaper7   cat)xx1x2s      r1   rotate_halfrD   M   s]    	
3"!'"+"""	#B	
3q """	#B9rc2YB''''r3   c                     |                     |          }|                     |          }| |z  t          |           |z  z   }||z  t          |          |z  z   }||fS )a  Applies Rotary Position Embedding to the query and key tensors.

    Args:
        q (`torch.Tensor`): The query tensor.
        k (`torch.Tensor`): The key tensor.
        cos (`torch.Tensor`): The cosine part of the rotary embedding.
        sin (`torch.Tensor`): The sine part of the rotary embedding.
        position_ids (`torch.Tensor`, *optional*):
            Deprecated and unused.
        unsqueeze_dim (`int`, *optional*, defaults to 1):
            The 'unsqueeze_dim' argument specifies the dimension along which to unsqueeze cos[position_ids] and
            sin[position_ids] so that they can be properly broadcasted to the dimensions of q and k. For example, note
            that cos[position_ids] and sin[position_ids] have the shape [batch_size, seq_len, head_dim]. Then, if q and
            k have the shape [batch_size, heads, seq_len, head_dim], then setting unsqueeze_dim=1 makes
            cos[position_ids] and sin[position_ids] broadcastable to the shapes of q and k. Similarly, if q and k have
            the shape [batch_size, seq_len, heads, head_dim], then set unsqueeze_dim=2.
    Returns:
        `tuple(torch.Tensor)` comprising of the query and key tensors rotated using the Rotary Position Embedding.
    )	unsqueezerD   )qkcossinposition_idsunsqueeze_dimq_embedk_embeds           r1   apply_rotary_pos_embrO   U   sc    ( --
&
&C
--
&
&C3w;q>>C/0G3w;q>>C/0GGr3   c                   v     e Zd Z	 	 	 	 	 	 	 d
dee         f fdZd Z ej                    d	             Z	 xZ
S )FalconRotaryEmbeddingN   '        ?defaultconfigc                 X   t                                                       i | _        |=t                              d           |||||d| _        || _        || _        || _        n_|j        9|j        	                    d|j        	                    d                    | _        nd| _        |j
        | _        |j
        | _        || _        t          | j                 | _         | j        | j        |fi | j        \  }| _        |                     d|d           | j        | _        d S )	Nz`FalconRotaryEmbedding` can now be fully parameterized by passing the model config through the `config` argument. All other arguments will be removed in v4.46)	rope_typefactorr>   basemax_position_embeddingsrX   typerU   inv_freqF
persistent)super__init__rope_kwargsloggerwarning_oncerX   max_seq_len_cachedoriginal_max_seq_lenrope_scalinggetr[   rV   r   rope_init_fnattention_scalingregister_bufferr]   original_inv_freq)
r/   r>   r[   rZ   devicescaling_factorrX   rV   r]   	__class__s
            r1   ra   zFalconRotaryEmbedding.__init__r   sC    	>R  
 '(+B   D 'DN&=D#(?D%% ".!'!4!8!8fFYF]F]^dFeFe!f!f!*&,&DD#(.(FD%/?+<4+<T[&+e+eTXTd+e+e($(ZeDDD!%r3   c                 ^   t          j        |          dz   }|| j        k    rB | j        | j        |fd|i| j        \  }| _        |                     d|d           || _        || j        k     r;| j        | j        k    r-|                     d| j	        d           | j        | _        dS dS dS )a  
        dynamic RoPE layers should recompute `inv_freq` in the following situations:
        1 - growing beyond the cached sequence length (allow scaling)
        2 - the current sequence length is in the original scale (avoid losing precision with small sequences)
        r"   seq_lenr]   Fr^   N)
r7   maxre   ri   rV   rb   rj   rk   rf   rl   )r/   rK   rm   rq   r]   s        r1   _dynamic_frequency_updatez/FalconRotaryEmbedding._dynamic_frequency_update   s     )L))A-T,,,/@t/@V0 0-408<8H0 0,Hd,   X% HHH&-D#T...43JTMf3f3f  T-CPU VVV&*&?D### /.3f3fr3   c                 V   d| j         v r|                     ||j                   | j        d d d d f                                                             |j        d         dd          }|d d d d d f                                         }|j        j        }t          |t                    r|dk    r|nd}t          j        |d	          5  |                                |                                z                      dd
          }t          j        ||fd          }|                                }|                                }	d d d            n# 1 swxY w Y   || j        z  }|	| j        z  }	|                    |j                  |	                    |j                  fS )Ndynamicrm   r   r;   r"   mpscpuF)device_typeenabledr<   r=   dtype)rX   rs   rm   r]   floatexpandr?   r\   
isinstancestrr7   autocast	transposer@   rI   rJ   rj   tor|   )
r/   rA   rK   inv_freq_expandedposition_ids_expandedry   freqsembrI   rJ   s
             r1   r2   zFalconRotaryEmbedding.forward   s   &&**<*III !M$4-8>>@@GGHZ[\H]_acdee ,QQQaaaZ 8 > > @ @hm%/S%A%AekUZFZFZkk`e^UCCC 	 	&,,..1F1L1L1N1NNYYZ[]^__E)UEN333C''))C''))C		 	 	 	 	 	 	 	 	 	 	 	 	 	 	 D**D**vvAGv$$cff17f&;&;;;s   A>EEE)NrR   rS   NrT   rU   N)r4   r5   r6   r   r#   ra   rs   r7   no_gradr2   __classcell__ro   s   @r1   rQ   rQ   q   s          $)-*/ */ &*/ */ */ */ */ */X@ @ @$ U]__< < _< < < < <r3   rQ   c                   "     e Zd ZdZ fdZ xZS )"FalconLinearScalingRotaryEmbeddingz\FalconRotaryEmbedding extended with linear scaling. Credits to the Reddit user /u/kaiokendevc                 x    t                               d           d|d<    t                      j        |i | d S )Nz`FalconLinearScalingRotaryEmbedding` is deprecated an will be removed in v4.46. Please use `FalconRotaryEmbedding`, which now also does linear scaling (simply pass the model config to __init__).linearrX   rc   rd   r`   ra   r/   argskwargsro   s      r1   ra   z+FalconLinearScalingRotaryEmbedding.__init__   sO    v	
 	
 	
 '{$)&)))))r3   r4   r5   r6   __doc__ra   r   r   s   @r1   r   r      s>        ff* * * * * * * * *r3   r   c                   "     e Zd ZdZ fdZ xZS )&FalconDynamicNTKScalingRotaryEmbeddingznFalconRotaryEmbedding extended with Dynamic NTK scaling. Credits to the Reddit users /u/bloc97 and /u/emozillac                 x    t                               d           d|d<    t                      j        |i | d S )Nz`FalconDynamicNTKScalingRotaryEmbedding` is deprecated an will be removed in v4.46. Please use `FalconRotaryEmbedding`, which now also does dynamic ntk scaling (simply pass the model config to __init__).ru   rX   r   r   s      r1   ra   z/FalconDynamicNTKScalingRotaryEmbedding.__init__   sN    	
 	
 	

 ({$)&)))))r3   r   r   s   @r1   r   r      s>        xx* * * * * * * * *r3   r   attention_mask	num_headsr|   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
        ||          }||k    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          }|                     d          dz
  | z  d d d d d f         }|d                                         |z  }|                    ||z  d|                              |          S )	Nr<   r   rm   r|   r"   r   r=   r;   ).N)r?   mathfloorlog2r7   tensorrm   float32arangeint32powminr@   cumsumbfloat16reshaper   )r   r   r|   
batch_size
seq_lengthclosest_power_of_2rZ   powersslopes
extra_basenum_remaining_headsextra_powersarange_tensoralibis                 r1   build_alibi_tensorr      s   +1J
dj9)=)=>>><	ty!344q899:;NDYafan  D \!Q!33N<QY^YdeeeFYtV$$FY&&\A49Q);%;<<q@AABCNLainiv
 
 

 ""4iBT6TUU|Aq1/B+B'BAnNckpkvwwwFEIj,$G$GHaPPP %+++33a7>I111dTUTUTU:VM9&&((=8E==i/J??BB5IIIr3   rA   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)rA   r   r   r   outs        r1   dropout_addr      s(     )A
1
1
1C
S.CJr3   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
ej                 dej        de
ej                 de
e         de
ej                 dedede
ej                 de
eej        ej        f                  fdZ xZS )FalconAttentionNrV   c                 l   t                                                       || _        |j        | _        |j        | _        | j        | j        z  | _        | j        | _        |j        | _        |j	        | _	        |j
        | _
        d| _        |j        dk    | _        || _        |(t                              d| j        j         d           | j        | j        z  | j        k    r t'          d| j         d| j         d          dt)          j        | j                  z  | _        | j        | _        |j        r|j        d	z  |j        z   | j        z  }n$|j        r| j        d	| j        z  z   }n
d
| j        z  }t7          | j        ||j                  | _        |j        | _        |j        | _        t7          | j        | j        |j                  | _        t?          j         |j!                  | _!        | j        s| j        s|j        nd| _        |j"        rtG          | j                  | _$        d S d S )NTsdpaz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).rT   r<   r   r.   r"   rV   )%r`   ra   rV   hidden_sizenum_attention_headsr   head_dim
split_sizehidden_dropoutr[   
rope_theta	is_causal_attn_implementation	_use_sdpa	layer_idxrc   rd   ro   r4   
ValueErrorr   sqrtinv_norm_factorbetanew_decoder_architecturenum_kv_headsmulti_queryr'   r.   query_key_valuedenser   Dropoutattention_dropoutrotaryrQ   
rotary_emb)r/   rV   r   qkv_out_dimro   s       r1   ra   zFalconAttention.__init__  sR   !-3(DN:*$3'-'E$ +4>",!8 , , ,   =4>)T-==='TXTd ' 'N' ' '    #TYt}%=%==(	* 	/!.2V5OOSWS``KK 	/*Q->>KKd..K+D,<kPVP[\\\(.(G%!-!$"2D4D6;WWW
!#F,D!E!E484QqY]YiqF//pq = 	H34;GGGDOOO	H 	Hr3   	fused_qkvr)   c                    | j         r|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                  }d |||fD             \  }}}|||fS | j        sT|j        \  }	}
}|                    |	|
| j        d| j                  }|ddddf         |dd	ddf         |ddddf         fS |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 )
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<   Nc                 :    g | ]}|                     d d          S )r<   r   )flatten).0rA   s     r1   
<listcomp>z0FalconAttention._split_heads.<locals>.<listcomp>W  s$     N N NQ1a N N Nr3   r   .r   r"   )	r   r?   viewr   r   r   r7   broadcast_tor   )r/   r   batchrq   _qkvquerykeyvaluer   r   three_times_hidden_sizes               r1   _split_headszFalconAttention._split_headsC  s    ( 	\ )E7A..T^tGX5X[\5\^b^kllC111aaa"%EaaaAAAtm$C111aaa"&E$S%+66C&uek::E N N5#u:M N N NE3#u$$! 	\>Go;J
$;!z:t~qRVR_``IS!QQQY'31119)=yaQRQRQR?SSS>Go;J
$;!z:t~PQ?QSWS`aaIS#2#qqq[)9S2$\+BIcTVSWYZYZYZlD[[[r3   rA   c                     |j         \  }}}|| j        z  }|                    || j        || j                  }|                    dddd          }|                    ||| 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   r   permuter   )r/   rA   batch_size_and_num_headsr   r   r   s         r1   _merge_headszFalconAttention._merge_headsc  sv     34'/ *a-?
 FF:t~z4=II IIaAq!! yyZ$-1OPPPr3   Fr0   r   r   rK   
layer_past	head_mask	use_cacheoutput_attentionscache_positionposition_embeddingsc                 0
   |                      |          }| j        r| j        n| j        }|                     |          \  }}}|j        \  }}}}|                    dd                              || j        || j                  }|                    dd                              |||| j                  }|                    dd                              |||| j                  }|P|
4t          
                    d           |                     ||          \  }}n|
\  }}t          ||||          \  }}|>d|	i}||                    ||d           |                    ||| j        |          \  }}|j        d         }| j        rN|j        j        dk    r>|<|                                }|                                }|                                }||d d d d d d d |j        d         f         }| | j        rB|s@| j        r
||dk    rdnd	}t(          j        j                            ||||d
|          }d }nY||                    dd          z  }|t1          j        | j                  z  }t5          j        ||z   d|j                  }||z  }|                    || j        || j                  }|                    dddd          }|                    ||| j        | j        z            }|                     |          }|r|||fS ||fS | j        r|s|| j        r
||dk    rdnd	}t(          j        j                            ||||| j         r| j!        j"        nd
|          }|                    dd          }|                    ||| j        | j        z            }|                     |          }nA||                    dd          z  }|                    || j        ||          }|j        }|t(          j#        k    s|t(          j$        k    r|%                    t(          j&                  }||                    || j        dd          z   }|| j'        z  }t5          j        ||z   d|j                  }| !                    |          }|||z  }|                    || j        ||          }||z  (                    dd          }| )                    |          }|                     |          }|r|||fS ||fS )Nr"   r<   Y  The attention layers in this model are transitioning from computing the RoPE embeddings internally through `position_ids` (2D tensor with the indexes of the tokens), to using externally computed `position_embeddings` (Tuple of tensors, containing cos and sin). In v4.46 `position_ids` will be removed and `position_embeddings` will be mandatory.r   rJ   rI   r   cudaTF        )	attn_mask	dropout_pr   r;   )r>   r|   r   r   )*r   r   r   r   r   r?   r   r   r   rc   rd   r   rO   updater   r   rm   r\   
contiguousr   r7   r   r   scaled_dot_product_attentionr   r   r   softmaxr|   r   r   r   r   r   r   float16r   r   r   r   r   r   )r/   r0   r   r   rK   r   r   r   r   r   r   r   r   query_layer	key_layervalue_layerr   query_lengthr   rI   rJ   cache_kwargs	kv_lengthr   attn_outputattention_scoresmatmul_resultinput_dtypeattention_logitsattention_probsattention_probs_reshapeds                                  r1   r2   zFalconAttention.forward|  s    ((77	)-)F]t~~DL]040A0A)0L0L-i)4):&
L!Q!++Aq1199*dnVbdhdqrr''1--55j,P\^b^kll	!++Aq1199*lT`bfbopp="*##K    ??;EESS.S%9+yRUWZ%[%["K!,n=L}##C$<$<===%/%6%6y+t~_k%l%l"I{OB'	> 	3k05??ND^ &0022K!,,..I%0022K%+AAAqqq!!!5Jyr7J5J,JKN=~ =&7 =
 %)Nm~7MR^abRbRbDDhm	#h1NN,!' O   $(  #.1D1DR1L1L#L  DIdm$<$<< #$9-=-NTV^k^q#r#r#r .<%**:t~|UYUbccK%--aAq99K%--j,Y]YfHfggK**[11K  /"J0@@@"J.. ~ .6&7 .6I<M %)Nm~7MR^abRbRbDDhm	#h1NN,:>-Pd466S' O   *33Aq99)11*lDN]a]jLjkk"jj55 +i.A.A"b.I.I I $1#5#5j$.R^`i#j#j  /4%-//;%.3P3P'7':':5='I'I$#3ejjT^]^`b6c6c#c  D$88 "#),<~,MSU]j]p"q"q"q"&"8"8"I"I(&5	&AO ,;+?+?
DN\hjs+t+t(  8+ENNqRSTT #//<<"jj55  /"J??"J..r3   r+   NNNFFNN)r4   r5   r6   r#   ra   r7   r8   r   r   r   r   
LongTensorr   boolr2   r   r   s   @r1   r   r     s       -H -H| -H -H -H -H -H -H^\el \uU\5<Y^Ye=e7f \ \ \ \@Qel Qu| Q Q Q Q< 48&*,0"'59KOM/ M/|M/ %M/ 	M/
 u/0M/ UOM/ EL)M/ M/  M/ !!12M/ &eEL%,,F&GHM/ M/ M/ M/ M/ M/ M/ M/r3   r   c                   
    e Zd ZdZ fdZ	 	 	 	 	 	 	 ddej        deej                 dej        deej                 d	ee	         d
eej                 de
de
deej                 deeej        ej        f                  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                      j        |i | t                       | _        d S r+   )r`   ra   r    _flash_attn_uses_top_left_maskr   s      r1   ra   zFalconFlashAttention2.__init__  s9    $)&)))
 3V2W2W.W+++r3   NFr0   r   r   rK   r   r   r   r   r   r   c                 (   |                      |          }| j        r| j        n| j        }|                     |          \  }}}|j        \  }}}}|                    dd                              || j        || j                  }|                    dd                              |||| j                  }|                    dd                              |||| j                  }|P|
4t          
                    d           |                     ||          \  }}n|
\  }}t          ||||          \  }}|>d|	i}||                    ||d           |                    ||| j        |          \  }}|                    dd          }|                    dd          }|                    dd          }|t          d          | j        r| j        j        nd}|j        }|t(          j        k    rt)          j                    rt)          j                    }n3t1          | j        d          r| j        j        }n| j         j        j        }t          
                    d	| d
           |                    |          }|                    |          }|                    |          }t9          |||||||| j        | j        	  	        }|                    ||| j        | j        z            }|                     |          }|sd }|||fS )Nr"   r<   r   r   r   z6`alibi` is not supported when `use_flash_attn` is Truer   _pre_quantization_dtypezThe input hidden states seems to be silently casted in float32, this might be related to the fact you have upcasted embedding or layer norm layers in float32. We will cast back the input in .)rK   r   r   use_top_left_mask) r   r   r   r   r   r?   r   r   r   rc   rd   r   rO   r   r   r   r   rV   r   r|   r7   r   is_autocast_enabledget_autocast_gpu_dtypehasattrr  r,   r   r%   r   r  r   )r/   r0   r   r   rK   r   r   r   r   r   r   r   r   r  r  r  r   r  r   rI   rJ   r  attn_dropoutr
  target_dtyper  attn_weightss                              r1   r2   zFalconFlashAttention2.forward  sY    ((77	)-)F]t~~DL]040A0A)0L0L-i)4):&
L!Q!++Aq1199*dnVbdhdqrr''1--55j,P\^b^kll	!++Aq1199*lT`bfbopp="*##K    ??;EESS.S%9+yRUWZ%[%["K!,n=L}##C$<$<===%/%6%6y+t~_k%l%l"I{ "++Aq11''1--	!++Aq11UVVV8<Nt{443
 "'%-''(** A$;==&?@@ A#{B#3:@$ $ $ $   &..66K!\22I%..66K.% n"A

 

 

 #**:|T^VZVcEcddjj..  	 LJ44r3   r  )r4   r5   r6   r   ra   r7   r8   r   r  r   r  r   r2   r   r   s   @r1   r  r    s%        X X X X X 48&*,0"'59KO_5 _5|_5 %_5 	_5
 u/0_5 UO_5 EL)_5 _5  _5 !!12_5 &eEL%,,F&GH_5 _5 _5 _5 _5 _5 _5 _5r3   r  c                   H     e Zd Zdef fdZdej        dej        fdZ xZS )	FalconMLPrV   c                 $   t                                                       |j        }t          ||j        |j                  | _        t          |j                  | _	        t          |j        ||j                  | _
        |j        | _        d S )Nr   )r`   ra   r   r'   ffn_hidden_sizer.   dense_h_to_4hr   
activationactdense_4h_to_hr   )r/   rV   r   ro   s      r1   ra   zFalconMLP.__init__  s    ()+v7MTZT_```!&"344)&*@+TZT_```$3r3   rA   r)   c                     |                      |                     |                    }|                     |          }|S r+   )r%  r#  r&  )r/   rA   s     r1   r2   zFalconMLP.forward  s9    HHT''**++q!!r3   )	r4   r5   r6   r#   ra   r7   r8   r2   r   r   s   @r1   r   r   ~  sj        4| 4 4 4 4 4 4 %,        r3   r   )eagerr   flash_attention_2c                   B    e Zd Zddef fdZ	 	 	 	 	 	 	 ddej        deej                 dej        deej                 d	ee	e
eej        ej        f         f                  d
eej                 dededeej                 deeej        ej        f                  fdZ xZS )FalconDecoderLayerNrV   c                 `   t                                                       |j        }|j        | _        t          |j                 ||          | _        t          |          | _	        |j
        | _
        || _        |j        |j        rd|_        |j        s8t          ||j                  | _        t          ||j                  | _        d S |j        dk    r8t          ||j                  | _        t          ||j                  | _        d S t          ||j                  | _        d S )Nr<   eps)r`   ra   r   r   r   FALCON_ATTENTION_CLASSESr   self_attentionr   mlpr   rV   num_ln_in_parallel_attnr   parallel_attnr
   layer_norm_epsilonpost_attention_layernorminput_layernormln_attnln_mlp)r/   rV   r   r   ro   s       r1   ra   zFalconDecoderLayer.__init__  s!   (36v7RSTZ\effV$$$3)1f6U1-.F*# 
	],5kvG`,a,a,aD)#,[f>W#X#X#XD   -22(&:STTT'9RSSS'0&B['\'\'\$$$r3   Fr0   r   r   rK   r   r   r   r   r   r   c                    |}| j         j        r;| j         j        dk    r+|                     |          }|                     |          }n|                     |          }|                     |||||||||	|

  
        }|d         }| j         j        sF| j         j        r|}n7t          ||| j         j	        | j
                  }|                     |          }| j         j        r| j         j        r| j         j        dk    r|}|dd          }|                     |          }| j         j        s| j         j        r||z  }t          ||| j         j        | j
                  }|r|f|z   }n|f|dd          z   }|S )Nr<   )	r   r   rK   r   r   r   r   r   r   r   )r   r"   )rV   r   r2  r7  r8  r6  r0  r3  r   r   r   r5  r1  r   )r/   r0   r   r   rK   r   r   r   r   r   r   r   r   attention_layernorm_outmlp_layernorm_outattn_outputsattention_outputoutputs
mlp_outputoutputs                       r1   r2   zFalconDecoderLayer.forward  s    !;/ 	JDK4W[\4\4\&*ll=&A&A# $M : :&*&:&:=&I&I# **#!)%/) 3 + 
 
 (?{3 	L{( L$;!!&$h0MX\Xe   %)$A$A($K$K! K0	8)	8 3q88 7qrr" XX/00
;/ 	+4;3L 	+**JZ4;3MX\Xefff 	.i')GGi'!""+-Gr3   r+   r  )r4   r5   r6   r#   ra   r7   r8   r   r  r   r   r   r  r2   r   r   s   @r1   r+  r+    sH       ] ]| ] ] ] ] ] ]< 48PT,0"'59KOE E|E %E 	E
 u/0E U5%el0J*K#KLME EL)E E  E !!12E &eEL%,,F&GHE E E E E E E Er3   r+  a-  

    This model inherits from [`PreTrainedModel`]. Check the superclass documentation for the generic methods the
    library implements for all its model (such as downloading or saving, resizing the input embeddings etc.)

    This model is also a PyTorch [torch.nn.Module](https://pytorch.org/docs/stable/nn.html#torch.nn.Module) subclass.
    Use it as a regular PyTorch Module and refer to the PyTorch documentation for all matter related to general usage
    and behavior.

    Parameters:
        config ([`FalconConfig`]): Model configuration class with all the parameters of the model.
            Initializing with a config file does not load the weights associated with the model, only the
            configuration. Check out the [`~PreTrainedModel.from_pretrained`] method to load the model weights.
a7  
    Args:
        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[0][0].shape[2]`
            (`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)
        past_key_values (`Cache` or `tuple(tuple(torch.FloatTensor))`, *optional*):
            Pre-computed hidden-states (key and values in the self-attention blocks and in the cross-attention
            blocks) that can be used to speed up sequential decoding. This typically consists in the `past_key_values`
            returned by the model at a previous stage of decoding, when `use_cache=True` or `config.use_cache=True`.

            Two formats are allowed:
            - a [`~cache_utils.Cache`] instance, see our
            [kv cache guide](https://huggingface.co/docs/transformers/en/kv_cache);
            - Tuple of `tuple(torch.FloatTensor)` of length `config.n_layers`, with each tuple having 2 tensors of
            shape `(batch_size, num_heads, sequence_length, embed_size_per_head)`). This is also known as the legacy
            cache format.

            The model will output the same cache format that is fed as input. If no `past_key_values` are passed, the
            legacy cache format will be returned.

            If `past_key_values` are used, the user can optionally input only the last `input_ids` (those that don't
            have their past key value states given to this model) of shape `(batch_size, 1)` instead of all `input_ids`
            of shape `(batch_size, sequence_length)`.
        attention_mask (`torch.FloatTensor` of shape `(batch_size, sequence_length)`, *optional*):
            Mask to avoid performing attention on padding token indices. Mask values selected in `[0, 1]`:

            - 1 for tokens that are **not masked**,
            - 0 for tokens that are **masked**.

            [What are attention masks?](../glossary#attention-mask)
        position_ids (`torch.LongTensor` of shape `(batch_size, sequence_length)`, *optional*):
            Indices of positions of each input sequence tokens in the position embeddings. Selected in the range `[0,
            config.n_positions - 1]`.

            [What are position IDs?](../glossary#position-ids)
        head_mask (`torch.FloatTensor` of shape `(num_heads,)` or `(num_layers, num_heads)`, *optional*):
            Mask to nullify selected heads of the self-attention modules. Mask values selected in `[0, 1]`:

            - 1 indicates the head is **not masked**,
            - 0 indicates the head is **masked**.

        inputs_embeds (`torch.FloatTensor` of shape `(batch_size, sequence_length, hidden_size)`, *optional*):
            Optionally, instead of passing `input_ids` you can choose to directly pass an embedded representation. This
            is useful if you want more control over how to convert `input_ids` indices into associated vectors than the
            model's internal embedding lookup matrix.

            If `past_key_values` is used, optionally only the last `inputs_embeds` have to be input (see
            `past_key_values`).
        use_cache (`bool`, *optional*):
            If set to `True`, `past_key_values` key value states are returned and can be used to speed up decoding (see
            `past_key_values`).
        output_attentions (`bool`, *optional*):
            Whether or not to return the attentions tensors of all attention layers. See `attentions` under returned
            tensors for more detail.
        output_hidden_states (`bool`, *optional*):
            Whether or not to return the hidden states of all layers. See `hidden_states` under returned tensors for
            more detail.
        return_dict (`bool`, *optional*):
            Whether or not to return a [`~file_utils.ModelOutput`] instead of a plain tuple.
        cache_position (`torch.LongTensor` of shape `(sequence_length)`, *optional*):
            Indices depicting the position of the input sequence tokens in the sequence. Contrarily to `position_ids`,
            this tensor is not affected by padding. It is used to update the cache in the correct position and to infer
            the complete sequence length.
c                        e Zd ZdZeZdZdZdgZdZ	dZ
dZdZdZ fdZdej        fdZedd	ed
dfd            Z xZS )FalconPreTrainedModelz
    An abstract class to handle weights initialization and a simple interface for downloading and loading pretrained
    models.
    transformerTr+  c                 :     t                      j        |i | d S r+   )r`   ra   )r/   inputsr   ro   s      r1   ra   zFalconPreTrainedModel.__init__`  s%    &+F+++++r3   modulec                    t          |t          j                  st          |t                    rT|j        j                            d| j        j                   |j	         |j	        j        
                                 dS dS t          |t          j                  r_|j        j                            d| j        j                   |j        +|j        j        |j                 
                                 dS dS t          |t                    r?|j	        j        
                                 |j        j                            d           dS dS )zInitialize the weights.r   )meanstdNrT   )r   r   Linearr'   r,   datanormal_rV   initializer_ranger.   zero_	Embeddingpadding_idxr
   fill_)r/   rF  s     r1   _init_weightsz#FalconPreTrainedModel._init_weightsc  s8   fbi(( 	*Jv|,L,L 	* M&&CT[5R&SSS{& &&((((( '&-- 	*M&&CT[5R&SSS!-"6#56<<>>>>> .-	** 	*K""$$$M$$S)))))	* 	*r3   Fhard_check_onlyr)   r$   c                     |rt           st          d          t           s|S t          | dd          }|r|S |sd|_        |S )NzQPyTorch SDPA requirements in Transformers are not met. Please install torch>=2.0.use_bettertransformerFr   )r   ImportErrorgetattrr   )clsrV   rS  _is_bettertransformers       r1   _check_and_enable_sdpaz,FalconPreTrainedModel._check_and_enable_sdpat  sg      	w5 w!"uvvv1 	M '-De L L  	M 	1*0F'r3   )F)r4   r5   r6   r   r#   config_classbase_model_prefixsupports_gradient_checkpointing_no_split_modules_supports_flash_attn_2_supports_sdpa_supports_cache_class_supports_quantized_cache_supports_static_cachera   r   ModulerR  classmethodr  rZ  r   r   s   @r1   rB  rB  P  s         
  L%&*#-.!N  $!, , , , ,*BI * * * *"  T N`    [    r3   rB  z`The bare Falcon Model transformer outputting raw hidden-states without any specific head on top.c                       e Zd Zdef fdZd Zdej        fdZ e	e
           eeee          	 	 	 	 	 	 	 	 	 	 	 ddeej                 d	eeeeeej        ej        f         d
f         f                  deej                 deej                 deej                 deej                 dee         dee         dee         dee         deej                 deeej        d
f         ef         fd                        Zdej        dej        dej        d	ededej        dej        fdZedej        dededej        dej        dej        defd            Z xZS ) FalconModelrV   c                 *   t                                                     j        | _        j        | _        j        | _        t          j	        j
        | j                  | _        t          j        fdt          j                  D                       | _        j        dk    | _        j        dk    | _        t'          | j        j                  | _        t-                    | _        d| _        |                                  d S )Nc                 2    g | ]}t          |           S ))r   )r+  )r   irV   s     r1   r   z(FalconModel.__init__.<locals>.<listcomp>  s'    qqqA 26Q G G Gqqqr3   r)  r   r-  r   F)r`   ra   r   	embed_dimr   r   r   	use_alibir   rO  
vocab_sizeword_embeddings
ModuleListrangenum_hidden_layershr   _use_flash_attention_2r   r
   r4  ln_frQ   r   gradient_checkpointing	post_initr/   rV   ro   s    `r1   ra   zFalconModel.__init__  s       +3  "|F,=t~NN qqqqQVW]WoQpQpqqqrr&,&AEX&X#4> dn&2KLLL	/v>>>&+# 	r3   c                     | j         S r+   rn  r/   s    r1   get_input_embeddingsz FalconModel.get_input_embeddings  s    ##r3   new_embeddingsc                     || _         d S r+   ry  r/   r|  s     r1   set_input_embeddingsz FalconModel.set_input_embeddings  s    -r3   
checkpointoutput_typer[  N	input_idspast_key_values.r   rK   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          	                    d           d}|| 
                    |          }d}|rVt          |t                    sAd}|t                      }n.t          j        |          }t          	                    d           d }||                                nd}|j        \  }}}| j        rK|+t%          j        |||z   f|j        t$          j                  n|}t-          || j        |j                  }|t%          j        |||z   |j        	          }||                    d          }|                     |||||||          }|                     || j         j                  }|}|                     ||          }d }|rd
nd }|	rd
nd }t?          | j                   D ]\  }}|	r||fz   }| j        r2| j        r+| !                    |j"        ||||||         |||||          }n |||||||         |||||
  
        }|d         }|du r|d         }|r|||rdnd         fz   }| #                    |          }|	r||fz   }|r|nd }|r|$                                }|
stK          d ||||fD                       S tM          ||||          S )Nz:You must specify exactly one of input_ids or inputs_embedszZ`use_cache=True` is incompatible with gradient checkpointing. Setting `use_cache=False`...FTzWe detected that you are passing `past_key_values` as a tuple of tuples. This is deprecated and will be removed in v4.47. Please convert your cache or use an appropriate `Cache` class (https://huggingface.co/docs/transformers/kv_cache#legacy-cache-format)r   r   r{   rv   r9   )	r   r   rK   r   r   r   r   r   r   r"   r<   c              3      K   | ]}||V  	d S r+   r9   )r   vs     r1   	<genexpr>z&FalconModel.forward.<locals>.<genexpr>;  s1        bcbobobobobo r3   )last_hidden_stater  r0   
attentions)'rV   r   r  r   use_return_dictr   ru  r   rc   rd   rn  r   r   r   from_legacy_cacheget_seq_lengthr?   rl  r7   onesrm   longr   r   r|   r   rF   _update_causal_maskget_head_maskrq  r   	enumeraterr  _gradient_checkpointing_func__call__rt  to_legacy_cachetupler   )r/   r  r  r   rK   r   r  r   r   r  r  r   return_legacy_cacher   past_key_values_lengthr   r   r   maskcausal_maskr0   r   next_decoder_cacheall_self_attentionsall_hidden_statesrj  blockr>  
next_caches                                r1   r2   zFalconModel.forward  sl   ( 2C1N--TXT_Tq$8$D  $+Jj 	 "+!6IIDK<Q	%0%<kk$+B]-t";< 	[YZZZ& 	"4= 	" "##p   "	  00;;M $ 
	Z?? 
	"&&"..."."@"Q"Q##^   ETE`!?!?!A!A!Afg$1$7!
J> 	X
 ") 
.D!DEmNbjojt    $  'tT^=CVWWWE!"\&(>(KTaTh  N )33A66L..M>?L]_hjo
 
 &&y$+2OPP	% #oom\JJ!$5?bb4"6@BBD!$&)) %	^ %	^HAu# I$58H$H!* t} ;;N! aL#%"'   %!.#.!-'l'&7#1(;   $AJMD  %,QZ"  ^&9W)EZQQYZ=[<]&]# 		-00 	E 1]4D D+4>''$
 	6#3355J 	  ):7HJ]^      9+&+*	
 
 
 	
r3   input_tensorr   c           
      n   | j         j        dk    r
|d|v r|S d S ||                                nd}t          |t                    }	| j         j        dk    r'|	s%|s#|!|t          j        |||| j                  rd S |j        |j	        }}
t          j        |
          j        }|j        \  }}}|	r|                                }n,t          |t          j                  r|j        d         n||z   }|                     ||||
|||j        d                   }|_|] |j        |dg|j        dd          R  }t          j        |t'          j        | j         j        | j        z            z  |dk     |          }| j         j        dk    r)|'|j	        j        d	k    r|st          j        ||          }|S )
Nr)  r   r   r   )r  r  is_trainingr;   )sequence_lengthtarget_lengthr|   rm   r   r   r"   r   )rV   r   r  r   r   r   _ignore_causal_mask_sdpar   r|   rm   r7   finfor   r?   get_max_cache_shaper8   5_prepare_4d_causal_attention_mask_with_cache_positionr   masked_fillr   r   r   r   r\   _unmask_unattended)r/   r   r  r   r  r   r   r   past_seen_tokensusing_static_cacher|   rm   	min_dtyper   r  r   r  r  s                     r1   r  zFalconModel._update_causal_maskF  s-    ;+/BBB)c^.C.C%%4
 @O?Z?99;;;`a'EE K,66& 7% 7 !%>*'7 M	    t$*L,?vK&&*	)5);&
OQ 	+??AAMM nel;;8$R((%7  PP+')#)!, Q 
 
 !2!EM*bC5;qrr?CCCE+	$+"9T^"KLLLb  K K,66*%*f44% 5 1CKQZ[[Kr3   r  r  r|   rm   r   c                    | |                                  dk    r| }n+t          j        |          j        }	t          j        ||f|	||          }|dk    rt          j        |d          }|t          j        ||          |                    dd          k    z  }|ddddddf                             |ddd          }| |	                                }| j
        d         }
|ddddddd|
f         | ddddddf         z   }|dk    }|ddddddd|
f                             ||	          |ddddddd|
f<   |S )	a  
        Creates a causal 4D mask of shape `(batch_size, 1, query_length, key_value_length)` from a 2D mask of shape
        `(batch_size, key_value_length)`, or if the input `attention_mask` is already 4D, do nothing.

        Args:
            attention_mask (`torch.Tensor`):
                A 2D attention mask of shape `(batch_size, key_value_length)` or a 4D attention mask of shape
                `(batch_size, 1, query_length, key_value_length)`.
            sequence_length (`int`):
                The sequence length being processed.
            target_length (`int`):
                The target length: when generating with static cache, the mask should be as long as the static cache,
                to account for the 0 padding, the part of the cache that is not filled yet.
            dtype (`torch.dtype`):
                The dtype to use for the 4D attention mask.
            device (`torch.device`):
                The device to plcae the 4D attention mask on.
            cache_position (`torch.Tensor`):
                Indices depicting the position of the input sequence tokens in the sequence.
            batch_size (`torch.Tensor`):
                Batch size.
        N   )
fill_valuer|   rm   r"   )diagonalrv   r;   r   )r>   r7   r  r   fulltriur   r   r~   cloner?   r  )r   r  r  r|   rm   r   r   r   r  r  mask_lengthpadding_masks               r1   r  zAFalconModel._prepare_4d_causal_attention_mask_with_cache_position  s   D %.*<*<*>*>!*C*C(KKE**.I* -0Ye\b  K !###jqAAA5<fEEEH^H^_acdHeHeeeK%dD!!!QQQ&67>>z1bRTUUK))//11,226*111aaaL[L+@ANSTSTSTVZ\`bcbcbcScDdd+q05@AAAqqq,;,AV5W5c5c )6 6AAAqqq!!!\k\12 r3   )NNNNNNNNNNN)r4   r5   r6   r#   ra   r{  r7   r8   r  r   FALCON_INPUTS_DOCSTRINGr   _CHECKPOINT_FOR_DOCr   _CONFIG_FOR_DOCr   r  r   r   r   r  r2   r  staticmethodintr|   rm   r  r   r   s   @r1   rg  rg    s       
|      2$ $ $.5< . . . . +*+BCC&=$   15ae15370448$(,0/3&*59S
 S
E,-S
 "%uU5<;U5VX[5[/\(\"]^S
 !.	S

 u/0S
 E,-S
   01S
 D>S
 $D>S
 'tnS
 d^S
 !!12S
 
uU\3&')RR	SS
 S
 S
  DCS
jUU lU 	U
 U  U <U |U U U Un 555 5 {	5
 5 5 5 5 5 \5 5 5 5 5r3   rg  z{The Falcon Model transformer with a language modeling head on top (linear layer with weights tied to the input embeddings).c                       e Zd ZdgZdef fdZd Zdej        fdZ	 e
e           eeee          	 	 	 	 	 	 	 	 	 	 	 	 dd	eej                 d
eeeeeej        ej        f         df         f                  deej                 deej                 deej                 deej                 deej                 dee         dee         dee         dee         deej                 deeej                 ef         fd                        Zdeeej        ej        f         df         dej        deeej        ej        f         df         fdZ xZS )FalconForCausalLMzlm_head.weightrV   c                     t                                          |           t          |          | _        t	          j        |j        |j        d          | _        | 	                                 d S NFr   )
r`   ra   rg  rC  r   rJ  r   rm  lm_headrv  rw  s     r1   ra   zFalconForCausalLM.__init__  sa       &v..y!3V5FUSSS 	r3   c                     | j         S r+   r  rz  s    r1   get_output_embeddingsz'FalconForCausalLM.get_output_embeddings  s
    |r3   r|  c                     || _         d S r+   r  r~  s     r1   set_output_embeddingsz'FalconForCausalLM.set_output_embeddings  s    %r3   r  Nr  r  .r   rK   r   r  labelsr   r   r  r  r   r)   c                 @   ||n| j         j        }|                     ||||||||	|
||          }|d         }|                     |          }d}||dddddf                                         }|dddf                                         }|j        \  }}}t                      } ||                    ||z  |          |                    ||z                      }|s|f|dd         z   }||f|z   n|S t          |||j	        |j
        |j                  S )a  
        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   rK   r   r  r   r   r  r  r   r   .r;   r"   losslogitsr  r0   r  )rV   r  rC  r  r   r?   r	   r   r   r  r0   r  )r/   r  r  r   rK   r   r  r  r   r   r  r  r   transformer_outputsr0   	lm_logitsr  shift_logitsshift_labelsr   r   rm  loss_fctr@  s                           r1   r2   zFalconForCausalLM.forward  s}   8 &1%<kk$+B]"..+)%'/!5#) / 
 
 ,A.LL//	$S#2#qqq[1<<>>L!#qrr'?5577L1=1C.J
J'))H8!!*z"9:FFHYHYZdgqZqHrHr D  	F\$7$;;F)-)9TGf$$vE0/?-;*5
 
 
 	
r3   pastbeam_idxc                 \    fd|D             t          fd|D                       }|S )aL  
        This function is used to re-order the `past_key_values` cache if [`~PreTrainedModel.beam_search`] or
        [`~PreTrainedModel.beam_sample`] is called. This is required to match `past_key_values` with the correct
        beam_idx at every generation step.

        Output shares the same memory storage as `past`.
        c                 Z    i | ]'}|D ]"}|j                             |j                   #(S r9   )rm   r   )r   r   
past_stater  s      r1   
<dictcomp>z4FalconForCausalLM._reorder_cache.<locals>.<dictcomp>?  sO     
 
 
BLgq
 
YcJx{{:+<==
 
 
 
r3   c              3      K   | ]^}|d                               d |d          j                           |d                              d |d          j                           fV  _dS )r   r"   N)index_selectrm   )r   r   device_to_beam_idxs     r1   r  z3FalconForCausalLM._reorder_cache.<locals>.<genexpr>B  s       
 

  1**1.@AAU.VWW1**1.@AAU.VWW
 
 
 
 
 
r3   )r  )r/   r  r  reordered_pastr  s     ` @r1   _reorder_cachez FalconForCausalLM._reorder_cache3  sn    
 
 
 
PT
 
 
  
 
 
 

 #
 
 
 
 
 r3   )NNNNNNNNNNNN)r4   r5   r6   _tied_weights_keysr#   ra   r  r7   r8   r  r   r  r   r  r   r  r   r  r   r   r   r  r2   r  r   r   s   @r1   r  r    sZ       
 ++|        &EL & & & & +*+BCC&5$   15ae1537,004)-$(,0/3&*59?
 ?
E,-?
 "%uU5<;U5VX[5[/\(\"]^?
 !.	?

 u/0?
 EL)?
  -?
 &?
 D>?
 $D>?
 'tn?
 d^?
 !!12?
 
uU\"$EE	F?
 ?
 ?
  DC?
B%el :;S@AMRM]	uU\5</0#5	6       r3   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e           eee	e
          	 	 	 	 	 	 	 	 	 	 ddeej                 deeeej        ej        f         df                  deej                 d	eej                 d
eej                 deej                 dee         dee         dee         dee         deeej                 e	f         fd                        Z xZS )FalconForSequenceClassificationrV   c                     t                                          |           |j        | _        t          |          | _        t          j        |j        |j        d          | _        | 	                                 d S r  )
r`   ra   
num_labelsrg  rC  r   rJ  r   scorerv  rw  s     r1   ra   z(FalconForSequenceClassification.__init__\  sk        +&v..Yv163D5QQQ
 	r3   r  Nr  r  .r   r   r  r  r   r   r  r  r)   c                    |
|
n| j         j        }
|                     ||||||||	|
	  	        }|d         }|                     |          }||j        d         }n|j        d         }| j         j        |dk    rt          d          | j         j        d}n|rt          j        || j         j                  	                                
                    d          dz
  }||j        d         z  }|                    |j                  }n)d}t                              | j        j         d           |t          j        ||j                  |f         }d}|.| j         j        f| j        dk    rd	| j         _        nN| j        dk    r7|j        t          j        k    s|j        t          j	        k    rd
| j         _        nd| j         _        | j         j        d	k    rWt-                      }| j        dk    r1 ||                                |                                          }nb |||          }nU| j         j        d
k    rt1                      } |||          }n*| j         j        dk    rt3                      } |||          }|
s|f|dd         z   }||f|z   n|S t5          |||j        |j        |j                  S )  
        labels (`torch.LongTensor` of shape `(batch_size,)`, *optional*):
            Labels for computing the sequence classification/regression loss. Indices should be in `[0, ...,
            config.num_labels - 1]`. If `config.num_labels == 1` a regression loss is computed (Mean-Square loss), If
            `config.num_labels > 1` a classification loss is computed (Cross-Entropy).
        Nr  r   r   r  r   r   r  r  r   r"   z=Cannot handle batch sizes > 1 if no padding token is defined.r;   z will not detect padding tokens in `inputs_embeds`. Results may be unexpected if using padding tokens in conjunction with `inputs_embeds.`rv   
regressionsingle_label_classificationmulti_label_classificationr  )rV   r  rC  r  r?   pad_token_idr   r7   eqr  argmaxr   rm   rc   rd   ro   r4   r   problem_typer  r|   r  r   squeezer	   r   r   r  r0   r  )r/   r  r  r   r   r  r  r   r   r  r  r  r0   r  r   sequence_lengthspooled_logitsr  r  r@  s                       r1   r2   z'FalconForSequenceClassification.forwarde  s   4 &1%<kk$+B]"..+)'/!5# / 

 

 ,A.M** "+JJ&,Q/J;#+
a\]]];#+!$#(8It{7O#P#P#T#T#V#V#]#]^`#a#ade#e #3iob6I#I #3#6#6v}#E#E  #% ##~. ^ ^ ^  
 u|Jv}MMMO__`{'/?a''/;DK,,_q((flej.H.HFL\a\eLeLe/LDK,,/KDK,{'<77"99?a''#8M$9$9$;$;V^^=M=MNNDD#8M6::DD)-JJJ+--xv66)-III,..xv66 	F#%(;ABB(??F)-)9TGf$$vE/ /?-;*5
 
 
 	
r3   
NNNNNNNNNN)r4   r5   r6   r#   ra   r   r  r   r  r   r  r   r7   r  r   r8   r  r   r2   r   r   s   @r1   r  r  L  s        |       +*+BCC&4$   15SW15,004)-$(,0/3&*]
 ]
E,-]
 "%elEL.H(I3(N"OP]
 !.	]

 EL)]
  -]
 &]
 D>]
 $D>]
 'tn]
 d^]
 
uU\"$DD	E]
 ]
 ]
  DC]
 ]
 ]
 ]
 ]
r3   r  z
    Falcon Model with a token classification head on top (a linear layer on top of the hidden-states output) e.g. for
    Named-Entity-Recognition (NER) tasks.
    c                       e Zd Zdef fdZ ee           eee	e
          	 	 	 	 	 	 	 	 	 	 ddeej                 deeeej        ej        f         df                  deej                 d	eej                 d
eej                 deej                 dee         dee         dee         dee         deeej                 e	f         fd                        Z xZS )FalconForTokenClassificationrV   c                    t                                          |           |j        | _        t          |          | _        t          |dd           |j        }nt          |dd           |j        }nd}t          j	        |          | _
        t          j        |j        |j                  | _        |                                  d S )Nclassifier_dropoutr   g?)r`   ra   r  rg  rC  rW  r  r   r   r   r   rJ  r   
classifierrv  )r/   rV   r  ro   s      r1   ra   z%FalconForTokenClassification.__init__  s        +&v..6/66B!'!:V-t44@!'!6!$z"455)F$68IJJ 	r3   r  Nr  r  .r   r   r  r  r   r   r  r  r)   c                    |
|
n| j         j        }
|                     ||||||||	|
	  	        }|d         }|                     |          }|                     |          }d}|V|j        \  }}t                      } ||                    ||z  | j                  |                    ||z                      }|
s|f|dd         z   }||f|z   n|S t          |||j
        |j                  S )r  Nr  r   r<   )r  r  r0   r  )rV   r  rC  r   r  r?   r	   r   r  r   r0   r  )r/   r  r  r   r   r  r  r   r   r  r  r  r0   r  r  r   r   r  r@  s                      r1   r2   z$FalconForTokenClassification.forward  s<   4 &1%<kk$+B]"..+)'/!5# / 

 

 ,A.]33//%+\"J
'))H8J3T_EEv{{S]`jSjGkGk D  	FY!4QRR!88F)-)9TGf$$vE$-;*5	
 
 
 	
r3   r  )r4   r5   r6   r#   ra   r   r  r   r  r   r  r   r7   r  r   r8   r  r   r2   r   r   s   @r1   r  r    s       |      " +*+BCC&)$   15SW15,004)-$(,0/3&*7
 7
E,-7
 "%elEL.H(I3(N"OP7
 !.	7

 EL)7
  -7
 &7
 D>7
 $D>7
 'tn7
 d^7
 
uU\"$99	:7
 7
 7
  DC7
 7
 7
 7
 7
r3   r  z
    The Falcon Model transformer with a span classification head on top for extractive question-answering tasks like
    SQuAD (a linear layers on top of the hidden-states output to compute `span start logits` and `span end logits`).
    c                   <    e Zd Z fdZ ee          	 	 	 	 	 	 	 	 	 ddeej                 deej	                 deej	                 deej	                 deej                 deej                 d	ee
         d
ee
         dee
         deeef         fd            Z xZS )FalconForQuestionAnsweringc                     t                                          |           t          |          | _        t	          j        |j        d          | _        |                                  d S )Nr<   )	r`   ra   rg  rC  r   rJ  r   
qa_outputsrv  rw  s     r1   ra   z#FalconForQuestionAnswering.__init__,  sY       &v..)F$6:: 	r3   Nr  r   r   r  start_positionsend_positionsr   r  r  r)   c
           	         |	|	n| j         j        }	|                     |||||||	          }
|
d         }|                     |          }|                    dd          \  }}|                    d                                          }|                    d                                          }d}||t          |                                          dk    r|                    d          }t          |                                          dk    r|                    d          }|                    d          }|	                    d|          }|	                    d|          }t          |          } |||          } |||          }||z   dz  }|	s||f|
dd         z   }||f|z   n|S t          ||||
j        |
j        	          S )
a  
        start_positions (`torch.LongTensor` of shape `(batch_size,)`, *optional*):
            Labels for position (index) of the start of the labelled span for computing the token classification loss.
            Positions are clamped to the length of the sequence (`sequence_length`). Position outside of the sequence
            are not taken into account for computing the loss.
        end_positions (`torch.LongTensor` of shape `(batch_size,)`, *optional*):
            Labels for position (index) of the end of the labelled span for computing the token classification loss.
            Positions are clamped to the length of the sequence (`sequence_length`). Position outside of the sequence
            are not taken into account for computing the loss.
        N)r   r   r  r   r  r  r   r"   r;   r=   )ignore_indexr<   )r  start_logits
end_logitsr0   r  )rV   r  rC  r  splitr  r   lensizeclampr	   r   r0   r  )r/   r  r   r   r  r  r  r   r  r  r>  sequence_outputr  r   r  
total_lossignored_indexr  
start_lossend_lossr@  s                        r1   r2   z"FalconForQuestionAnswering.forward4  s   . &1%<kk$+B]"")'/!5# # 
 
 "!*11#)<<r<#:#: j#++B//::<<''++6688

&=+D?''))**Q.."1"9"9""="==%%''((1,, - 5 5b 9 9(--a00M-33A}EEO)//=AAM']CCCH!,@@Jx
M::H$x/14J 	R"J/'!""+=F/9/EZMF**6Q+%!!/)
 
 
 	
r3   )	NNNNNNNNN)r4   r5   r6   ra   r   r  r   r7   r  FloatTensorr  r   r   r   r2   r   r   s   @r1   r  r  $  sD            +*+BCC 156:15596:48,0/3&*D
 D
E,-D
 !!23D
 E-.	D

   12D
 "%"23D
   01D
 $D>D
 'tnD
 d^D
 
u22	3D
 D
 D
 DCD
 D
 D
 D
 D
r3   r  )Nr"   )Ur   r   typingr   r   r   r   r7   torch.utils.checkpointr   torch.nnr   r	   r
   r   r   r   activationsr   cache_utilsr   r   r   
generationr   modeling_attn_mask_utilsr   modeling_outputsr   r   r   r   r   modeling_rope_utilsr   modeling_utilsr   pytorch_utilsr   utilsr   r   r   r   r    r!   configuration_falconr#   configuration_utilsr$   modeling_flash_attention_utilsr%   
get_loggerr4   rc   r  r  rJ  r'   rD   rO   rd  rQ   r   r   r8   r  r|   r   r}   r  r   r   r  r   r/  r+  FALCON_START_DOCSTRINGr  rB  rg  r  r  r  r  r9   r3   r1   <module>r     sz      8 8 8 8 8 8 8 8 8 8 8 8            L L L L L L L L L L L L $ $ $ $ $ $ ) ) ) ) ) ) ; ; ; ; ; ; ; ; ; ; ) ) ) ) ) )                   7 6 6 6 6 6 - - - - - - ? ? ? ? ? ?                / . . . . .  8777777 KJJJJJJ		H	%	% 3  
) ) ) ) )29 ) ) )( ( (   8T< T< T< T< T<BI T< T< T<p	* 	* 	* 	* 	*)> 	* 	* 	*
* 
* 
* 
* 
*-B 
* 
* 
*Ju| J JEK J\a\h J J J J:5< 5< u PT Y^Ye    &v/ v/ v/ v/ v/bi v/ v/ v/ro5 o5 o5 o5 o5O o5 o5 o5d    	   " .  _ _ _ _ _ _ _ _D G T4 4 4 4 4O 4 4 4n f I I I I I' I I	 IX
  B n n n n n- n n	 nb   m
 m
 m
 m
 m
&; m
 m
 m
`   O
 O
 O
 O
 O
#8 O
 O
 O
d   N
 N
 N
 N
 N
!6 N
 N
 N
 N
 N
r3   