o
    h&                 
   @   s  d Z ddl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mZ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!m"Z"m#Z#m$Z$m%Z%m&Z& ddl'm(Z( erxddl)m*Z* e$ rddl+m,Z,m-Z- ddl.m/Z/m0Z0m1Z1 e&2e3Z4g dZ5dZ6dZ7G dd de
j8Z9dd Z:dOddZ;dd Z<G dd de
j=Z>G dd  d e>Z?G d!d" d"e>Z@d#ejAd$eBd%ejCfd&d'ZDd(ejAd)eBd*ejEd%ejAfd+d,ZFd-ejAd.ejAd/eGd0eHd%ejAf
d1d2ZIG d3d4 d4e
j=ZJG d5d6 d6eJZKG d7d8 d8e
j=ZLeJeJeKd9ZMG d:d; d;e
j=ZNd<ZOd=ZPG d>d? d?eZQe"d@eOG dAdB dBeQZRe"dCeOG dDdE dEeQZSe"dFeOG dGdH dHeQZTe"dIeOG dJdK dKeQZUe"dLeOG dMdN dNeQZVdS )PzPyTorch Falcon model.    N)TYPE_CHECKINGOptionalTupleUnion)nn)BCEWithLogitsLossCrossEntropyLoss	LayerNormMSELoss)
functional   )AttentionMaskConverter!_prepare_4d_causal_attention_mask*_prepare_4d_causal_attention_mask_for_sdpa))BaseModelOutputWithPastAndCrossAttentions!CausalLMOutputWithCrossAttentionsQuestionAnsweringModelOutput SequenceClassifierOutputWithPastTokenClassifierOutput)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_attn_funcflash_attn_varlen_func)index_first_axis	pad_inputunpad_input)ztiiuae/falcon-40bztiiuae/falcon-40b-instructztiiuae/falcon-7bztiiuae/falcon-7b-instructztiiuae/falcon-rw-7bztiiuae/falcon-rw-1bzRocketknight1/falcon-rw-1br   c                   @   s"   e Zd ZdejdejfddZdS )FalconLinearinputreturnc                 C   s$   || j j }| jd u r|S || j S N)weightTbias)selfr&   hidden_states r.   `/var/www/html/ai/venv/lib/python3.10/site-packages/transformers/models/falcon/modeling_falcon.pyforwardL   s   

zFalconLinear.forwardN)__name__
__module____qualname__torchTensorr0   r.   r.   r.   r/   r%   K   s    r%   c                 C   sH   | dd| j d d f }| d| j d d df }tj| |fddS )z*Rotates half the hidden dims of the input..N   dim)shaper4   cat)xx1x2r.   r.   r/   rotate_halfT   s   r?   c                 C   sL   ||  |}||  |}| | t| |  }|| t||  }||fS )an  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`):
            The position indices of the tokens corresponding to the query and key tensors. For example, this can be
            used to pass offsetted position ids when working with a KV-cache.
        unsqueeze_dim (`int`, *optional*, defaults to 1):
            The 'unsqueeze_dim' argument specifies the dimension along which to unsqueeze cos[position_ids] and
            sin[position_ids] so that they can be properly broadcasted to the dimensions of q and k. For example, note
            that cos[position_ids] and sin[position_ids] have the shape [batch_size, seq_len, head_dim]. Then, if q and
            k have the shape [batch_size, heads, seq_len, head_dim], then setting unsqueeze_dim=1 makes
            cos[position_ids] and sin[position_ids] broadcastable to the shapes of q and k. Similarly, if q and k have
            the shape [batch_size, seq_len, heads, head_dim], then set unsqueeze_dim=2.
    Returns:
        `tuple(torch.Tensor)` comprising of the query and key tensors rotated using the Rotary Position Embedding.
    )	unsqueezer?   )qkcossinposition_idsunsqueeze_dimq_embedk_embedr.   r.   r/   apply_rotary_pos_emb\   s
   rI   c                 C   sX   | j dtjd}tj|  dd }|  }ttj	|dtjjdd}|||fS )Nr6   r9   dtypeF)as_tupler   )r   r   )
sumr4   int32nonzeroflattenmaxitemFpadcumsum)attention_maskseqlens_in_batchindicesmax_seqlen_in_batch
cu_seqlensr.   r.   r/   _get_unpad_datay   s   r[   c                       s0   e Zd Zd
 fdd	Zdd Zddd	Z  ZS )FalconRotaryEmbedding   '  Nc                    sr   t    || _|| _|| _d| jtd| jd || j   }| j	d|dd | j
|| jjt d d S )N      ?r   r7   inv_freqF
persistentseq_lendevicerK   )super__init__r9   max_position_embeddingsbaser4   arangefloattoregister_buffer_set_cos_sin_cacher`   re   get_default_dtype)r,   r9   rh   ri   re   r`   	__class__r.   r/   rg      s   
*
zFalconRotaryEmbedding.__init__c                 C   st   || _ tj| j || jjd}t|| j}tj||fdd}| jd| 	|dd | jd|
 	|dd d S Nre   rK   r6   r8   
cos_cachedFra   
sin_cached)max_seq_len_cachedr4   rj   r`   rK   outerr;   rm   rC   rl   rD   r,   rd   re   rK   tfreqsembr.   r.   r/   rn      s   z(FalconRotaryEmbedding._set_cos_sin_cachec                 C   sN   || j kr| j||j|jd | jd | j|jd| jd | j|jdfS )Nrc   rK   )rv   rn   re   rK   rt   rl   ru   )r,   r<   rd   r.   r.   r/   r0      s
   
zFalconRotaryEmbedding.forward)r]   r^   Nr(   )r1   r2   r3   rg   rn   r0   __classcell__r.   r.   rp   r/   r\      s    
r\   c                       *   e Zd ZdZd
 fdd	Zdd	 Z  ZS )"FalconLinearScalingRotaryEmbeddingz\FalconRotaryEmbedding extended with linear scaling. Credits to the Reddit user /u/kaiokendevr]   r^   Nr_   c                       || _ t |||| d S r(   scaling_factorrf   rg   r,   r9   rh   ri   re   r   rp   r.   r/   rg         z+FalconLinearScalingRotaryEmbedding.__init__c                 C   s~   || _ tj| j || jjd}|| j }t|| j}tj||fdd}| jd|	 
|dd | jd| 
|dd d S rr   )rv   r4   rj   r`   rK   r   rw   r;   rm   rC   rl   rD   rx   r.   r.   r/   rn      s   
z5FalconLinearScalingRotaryEmbedding._set_cos_sin_cacher]   r^   Nr_   r1   r2   r3   __doc__rg   rn   r}   r.   r.   rp   r/   r          r   c                       r~   )&FalconDynamicNTKScalingRotaryEmbeddingznFalconRotaryEmbedding extended with Dynamic NTK scaling. Credits to the Reddit users /u/bloc97 and /u/emozillar]   r^   Nr_   c                    r   r(   r   r   rp   r.   r/   rg      r   z/FalconDynamicNTKScalingRotaryEmbedding.__init__c           	      C   s   || _ || jkr<| j| j| | j | jd  | j| jd    }d|td| jd || j   }| j	d|dd tj| j || j
jd}t|| j
}tj||fd	d
}| j	d| |dd | j	d| |dd d S )Nr   r7   r_   r   r`   Fra   rs   r6   r8   rt   ru   )rv   rh   ri   r   r9   r4   rj   rk   rl   rm   r`   rK   rw   r;   rC   rD   )	r,   rd   re   rK   ri   r`   ry   rz   r{   r.   r.   r/   rn      s   
(z9FalconDynamicNTKScalingRotaryEmbedding._set_cos_sin_cacher   r   r.   r.   rp   r/   r      r   r   maskpast_key_values_lengthr'   c                 C   sP   | j \}}|dur|| n|}| ddddddf tj }||d||S )z|
    Expands attention_mask from `[batch_size, seq_length]` to `[batch_size, 1, seq_length, seq_length + past_length]`.
    Nr   )r:   rl   r4   boolexpand)r   r   
batch_sizetotal_length
seq_lengthexpanded_maskr.   r.   r/   _prepare_4d_attention_mask   s   
"r   rV   	num_headsrK   c                 C   s:  | j \}}dtt| }tjddt|d     | jtjd}tjdd| | jtj	d}t
||}||krvtjddtd| d     | jtjd}	t||| }
tjddd|
  d| jtj	d}tj|t
|	|gdd}| jddd |  d d d d d f }|d  | }||| d||S )	Nr7   r   rs   r   r   r8   r6   ).N)r:   mathfloorlog2r4   tensorre   float32rj   rN   powminr;   rU   bfloat16reshaperl   )rV   r   rK   r   r   closest_power_of_2ri   powersslopes
extra_basenum_remaining_headsextra_powersarange_tensoralibir.   r.   r/   build_alibi_tensor   s"   
 $ &r   r<   residualprobtrainingc                 C   s   t j| ||d}|| }|S )a:  
    Dropout add function

    Args:
        x (`torch.tensor`, *required*):
            input tensor
        residual (`torch.tensor`, *required*):
            residual tensor
        prob (`float`, *required*):
            dropout probability
        training (`bool`, *required*):
            training mode
    )pr   )rS   dropout)r<   r   r   r   outr.   r.   r/   dropout_add  s   r   c                       s   e Zd Zdef fddZdd Zdejdeejejejf fdd	Z	d
ejdejfddZ
					ddejdeej dejdeej deeejejf  deej dedefddZ  ZS )FalconAttentionconfigc                    s^  t    || _|j| _|j| _| j| j | _| j| _|j| _|j	| _	|j
| _
d| _|jdk| _| j| j | jkrFtd| j d| j d|jrM|   dt| j | _| j| _|jri|jd |j | j }n|jru| jd| j  }nd| j }t| j||jd	| _|j| _|j| _t| j| j|jd	| _t|j| _| js| js|j| _d S d
| _d S )NTsdpazA`hidden_size` must be divisible by num_heads (got `hidden_size`: z and `num_heads`: z).r_   r7   r   r+   r   )rf   rg   r   hidden_sizenum_attention_headsr   head_dim
split_sizehidden_dropoutrh   
rope_theta	is_causal_attn_implementation	_use_sdpa
ValueErrorrotary
_init_roper   sqrtinv_norm_factorbetanew_decoder_architecturenum_kv_headsmulti_queryr%   r+   query_key_valuedenser   Dropoutattention_dropout)r,   r   qkv_out_dimrp   r.   r/   rg     s@   


"zFalconAttention.__init__c                 C   s   | j jd u rt| j| j| jd| _d S | j jd }| j jd }|dkr1t| j| j|| jd| _d S |dkrCt| j| j|| jd| _d S t	d| )N)rh   ri   typefactorlinear)rh   r   ri   dynamiczUnknown RoPE scaling type )
r   rope_scalingr\   r   rh   r   
rotary_embr   r   r   )r,   scaling_typer   r.   r.   r/   r   =  s.   zFalconAttention._init_rope	fused_qkvr'   c                 C   s  | j rg|j\}}}|||d| j| j d | 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}t||j}dd |||fD \}}}|||fS | js|j\}	}
}||	|
| jd| j}|dd	ddf |dd
ddf |ddddf fS |j\}	}
}||	|
| jd | 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`, *required*): [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]
        r6   r7   Nc                 S   s   g | ]}| d dqS )r7   r   )rP   ).0r<   r.   r.   r/   
<listcomp>l  s    z0FalconAttention._split_heads.<locals>.<listcomp>r   .r   r   )	r   r:   viewr   r   r   r4   broadcast_tor   )r,   r   batchrd   _qkvquerykeyvaluer   r   three_times_hidden_sizer.   r.   r/   _split_headsX  s"     
4<zFalconAttention._split_headsr<   c                 C   sP   |j \}}}|| j }||| j|| j}|dddd}|||| j| j S )a  
        Merge heads together over the last dimension

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

        Returns:
            torch.tensor: [batch_size, seq_length, num_heads * head_dim]
        r   r7   r   r   )r:   r   r   r   permuter   )r,   r<   batch_size_and_num_headsr   r   r   r.   r.   r/   _merge_headsx  s
   
zFalconAttention._merge_headsNFr-   r   rV   rE   
layer_past	head_mask	use_cacheoutput_attentionsc	                  K   s  d|	v r	t d | |}
| jr| jn| j}| |
\}}}|j\}}}}|dd	|| j|| j
}|dd	|||| j
}|dd	|||| j
}|jd }|d ur`||d jd 7 }|d u rw| j||d\}}t|||||\}}|d ur|\}}tj||fdd}tj||fdd}|jd }|r||f}nd }|d u r| jr|stj||||d	| jo|d u o|dkd
}d }n||dd }|t| j
 }tj|| d|jd}|| }||| j|| j
}|dddd}|	||| j| j
 }| |}|r	|||fS ||fS | jrN|sN|d u rNtj||||| jr'| jjnd	| jo4|d u o4|dkd}|dd}|	||| j| j
 }| |}nj||dd }||| j||}|j}|tjksn|tjkrt|tj }|||| jdd }|| j!9 }tj|| d|jd}| |}|d ur|| }||| j||}|| "dd}| #|}| |}|r|||fS ||fS )Npadding_maskrPassing `padding_mask` is deprecated and will be removed in v4.37. Please make sure use `attention_mask` instead.`r   r7   r   r   rd   r8           )r   r6   rJ   r   )	attn_mask	dropout_pr   )$warningswarnr   r   r   r   r   r:   	transposer   r   r   rI   r4   r;   r   rS   scaled_dot_product_attentionr   r   r   softmaxrK   r   r   r   r   r   r   float16r   rl   r   r   rP   r   ) r,   r-   r   rV   rE   r   r   r   r   kwargsr   r   query_layer	key_layervalue_layerr   query_lengthr   
kv_seq_lenrC   rD   past_key
past_value	kv_lengthpresentattn_outputattention_scoresmatmul_resultinput_dtypeattention_logitsattention_probsattention_probs_reshapedr.   r.   r/   r0     s   





	







zFalconAttention.forwardNNNFF)r1   r2   r3   r   rg   r   r4   r5   r   r   r   r   
LongTensorr   r0   r}   r.   r.   rp   r/   r     s6    ($ 	r   c                       s   e Zd ZdZ fddZ					ddejdeej dejd	eej d
ee	ejejf  deej de
de
fddZ	dddZdd Z  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                    s    t  j|i | t  | _d S r(   )rf   rg   r   _flash_attn_uses_top_left_mask)r,   argsr   rp   r.   r/   rg     s   zFalconFlashAttention2.__init__NFr-   r   rV   rE   r   r   r   r   c	                 K   s0  d|	v rt d |	d}| |}
| jr| jn| j}| |
\}}}|j\}}}}|	dd
|| j|| j}|	dd
|||| j}|	dd
|||| j}|jd }|d ure||d jd 7 }|d u r|| j||d\}}t|||||\}}|d ur|r|\}}tj||fdd}tj||fdd}|r||fnd }|	dd}|	dd}|	dd}|d urtd	| jr| jjnd
}|j}|tjkrt| jdr| jj}n| jjj}td| d ||}||}||}| j||||||d}|
||| j| j }| |}|sd }|||fS )Nr   r   r   r7   r   r   r   r8   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 .)r   )r   r   popr   r   r   r   r   r:   r   r   r   r   rI   r4   r;   r   r   r   r   rK   r   hasattrr  r)   loggerwarning_oncerl   _flash_attention_forwardr   )r,   r-   r   rV   rE   r   r   r   r   r   r   r   r   r   r   r   r   r   r   rC   rD   r   r   past_key_valueattn_dropoutr   target_dtyper   attn_weightsr.   r.   r/   r0   %  sd   










zFalconFlashAttention2.forwardr   c                 C   s   | j s| j}n| jo|dk}|durE|jd }	| |||||\}}}}
}}|\}}|\}}t||||||||||d
}t||
|	|}|S t||||||d}|S )a  
        Calls the forward method of Flash Attention - if the input hidden states contain at least one padding token
        first unpad the input, then computes the attention scores and pad the final attention scores.

        Args:
            query_states (`torch.Tensor`):
                Input query states to be passed to Flash Attention API
            key_states (`torch.Tensor`):
                Input key states to be passed to Flash Attention API
            value_states (`torch.Tensor`):
                Input value states to be passed to Flash Attention API
            attention_mask (`torch.Tensor`):
                The padding mask - corresponds to a tensor of size `(batch_size, seq_len)` where 0 stands for the
                position of padding tokens and 1 for the position of non-padding tokens.
            dropout (`int`, *optional*):
                Attention dropout
            softmax_scale (`float`, *optional*):
                The scaling of QK^T before applying softmax. Default to 1 / sqrt(head_dim)
        r   Nr   )cu_seqlens_qcu_seqlens_kmax_seqlen_qmax_seqlen_kr   softmax_scalecausal)r  r  )r  r   r:   _upad_inputr!   r#   r    )r,   query_states
key_statesvalue_statesrV   r   r   r  r  r   	indices_qcu_seq_lensmax_seq_lensr  r  max_seqlen_in_batch_qmax_seqlen_in_batch_kattn_output_unpadr   r.   r.   r/   r    s8   

z.FalconFlashAttention2._flash_attention_forwardc                 C   s   t |\}}}|j\}	}
}}t||	|
 |||}t||	|
 |||}||
kr>t||	|
 | j||}|}|}|}n2|dkr\d}tj|	d tj|jd}|d d }|	d}n|d d | d f }t
||\}}}}||||||f||ffS )Nr   rK   re   r6   )r[   r:   r"   r   r   r4   rj   rN   re   squeezer$   )r,   r   r   r   rV   r   	indices_kr  r  r   r   num_key_value_headsr   r  r  r  r.   r.   r/   r    s>   z!FalconFlashAttention2._upad_inputr  )r   N)r1   r2   r3   r   rg   r4   r5   r   r  r   r   r0   r  r  r}   r.   r.   rp   r/   r    s8    	
^
<r  c                       s8   e Zd Zdef fddZdejdejfddZ  ZS )	FalconMLPr   c                    sR   t    |j}t|d| |jd| _t | _td| ||jd| _	|j
| _
d S )N   r   )rf   rg   r   r%   r+   dense_h_to_4hr   GELUactdense_4h_to_hr   r,   r   r   rp   r.   r/   rg     s   

zFalconMLP.__init__r<   r'   c                 C   s   |  | |}| |}|S r(   )r)  r'  r*  )r,   r<   r.   r.   r/   r0     s   
zFalconMLP.forward)	r1   r2   r3   r   rg   r4   r5   r0   r}   r.   r.   rp   r/   r%    s    	r%  )eagerr   flash_attention_2c                       s~   e Zd Zdef fddZ					ddejdeej dejd	eej d
ee	ejejf  deej de
de
fddZ  ZS )FalconDecoderLayerr   c                    s   t    |j}|j| _t|j || _t|| _	|j
| _
|| _|jr5t||jd| _t||jd| _d S t||jd| _|jsJt||jd| _d S d S )Neps)rf   rg   r   r   r   FALCON_ATTENTION_CLASSESr   self_attentionr%  mlpr   r   r   r	   layer_norm_epsilonln_attnln_mlpinput_layernormparallel_attnpost_attention_layernormr+  rp   r.   r/   rg     s   

zFalconDecoderLayer.__init__NFr-   r   rV   rE   r   r   r   r   c	              
   K   s
  d|	v r	t d |}
| jjr| |}| |}n| |}| j|f|||||||d|	}|d }| jjsO| jjr?|}nt	||
| jj
| jd}
| |
}|dd  }| |}| jjsb| jjrf||7 }t	||
| jj| jd}|rz|f| }|S |f|dd   }|S )Nr   r   )r   rV   rE   r   r   r   r   r   )r   r   )r   r   r   r   r5  r6  r7  r2  r8  r   r   r   r9  r3  r   )r,   r-   r   rV   rE   r   r   r   r   r   r   attention_layernorm_outmlp_layernorm_outattn_outputsattention_outputoutputs
mlp_outputoutputr.   r.   r/   r0     sP   

	


zFalconDecoderLayer.forwardr  )r1   r2   r3   r   rg   r4   r5   r   r  r   r   r0   r}   r.   r.   rp   r/   r.    s0    	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.
a2  
    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 (`Tuple[Tuple[torch.Tensor]]` of length `config.num_hidden_layers`):
            Contains precomputed hidden-states (key and values in the attention blocks) as computed by the model (see
            `past_key_values` output below). Can be used to speed up sequential decoding. The `input_ids` which have
            their past given to this model should not be passed as `input_ids` as they have already been computed.

            Each element of `past_key_values` is a tuple (past_key, past_value):
            - past_key: [batch_size * num_heads, head_dim, kv_length]
            - past_value: [batch_size * num_heads, kv_length, head_dim]
        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.
c                       sb   e Zd ZdZeZdZdZdgZdZ	dZ
 fddZdejfdd	ZeddeddfddZ  ZS )FalconPreTrainedModelz
    An abstract class to handle weights initialization and a simple interface for downloading and loading pretrained
    models.
    transformerTr.  c                    s   t  j|i | d S r(   )rf   rg   )r,   inputsr   rp   r.   r/   rg     s   zFalconPreTrainedModel.__init__modulec                 C   s   t |tjst |tr%|jjjd| jjd |j	dur#|j	j
  dS dS t |tjrH|jjjd| jjd |jdurF|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stdNr_   )
isinstancer   Linearr%   r)   datanormal_r   initializer_ranger+   zero_	Embeddingpadding_idxr	   fill_)r,   rD  r.   r.   r/   _init_weights  s   


z#FalconPreTrainedModel._init_weightsFhard_check_onlyr'   r   c                 C   s:   |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   )clsr   rQ  _is_bettertransformerr.   r.   r/   _check_and_enable_sdpa  s   z,FalconPreTrainedModel._check_and_enable_sdpa)F)r1   r2   r3   r   r   config_classbase_model_prefixsupports_gradient_checkpointing_no_split_modules_supports_flash_attn_2_supports_sdparg   r   ModulerP  classmethodr   rW  r}   r.   r.   rp   r/   rA    s    rA  z`The bare Falcon Model transformer outputting raw hidden-states without any specific head on top.c                       s   e Zd Zdef fddZdd ZdejfddZe	e
eeeed		
	
	
	
	
	
	
	
	
	
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df ef fddZ  ZS )FalconModelr   c                    s   t     j| _ j| _ j| _t	 j
| j| _t fddt jD | _ jdk| _ jdk| _t| j jd| _d| _|   d S )Nc                    s   g | ]}t  qS r.   )r.  )r   r   r   r.   r/   r     s    z(FalconModel.__init__.<locals>.<listcomp>r-  r   r/  F)rf   rg   r   	embed_dimr   r   r   	use_alibir   rM  
vocab_sizeword_embeddings
ModuleListrangenum_hidden_layershr   _use_flash_attention_2r   r	   r4  ln_fgradient_checkpointing	post_initr,   r   rp   ra  r/   rg     s    zFalconModel.__init__c                 C      | j S r(   re  r,   r.   r.   r/   get_input_embeddings     z FalconModel.get_input_embeddingsnew_embeddingsc                 C   
   || _ d S r(   rp  r,   rt  r.   r.   r/   set_input_embeddings     
z FalconModel.set_input_embeddings
checkpointoutput_typerX  N	input_idspast_key_values.rV   rE   r   inputs_embedsr   r   output_hidden_statesreturn_dictr'   c                 C   s  |d ur|n| j j}|	d ur|	n| j j}	|d ur|n| j j}|
d ur$|
n| j j}
|d ur4|d ur4td|d ur>|j\}}n|d urI|j\}}}ntd|d u r[td gt| j	 }|d u rd| 
|}|}| jru| jru|rutd d}|rydnd }|rdnd }|	rdnd }d}|d d ur|d d jd }| jr|d u rtj||| f|jtjdn|}t|| j|jd	}n!d }|d u r|d ur|jn|j}tj||| tj|d
}|d}| jr|d urd|v r|nd }n| jr`|s`|d u rt|||f||}nj|d u rV|j|dg|jdd  R  }|}t|||f||}|d u r0|t| j j | j  }n9t!|t| j j | j  |dk t"|jj#}|dkrUt$j%||dd}nt|||f||}n	t|||f||}| &|| j j'}t(t)| j	|D ]U\}\}}|	r||f }| jr| jr| *|j+|||||| |||	}n||||||| |||d}|d }|du r||d f }|r|||rdnd f }qy| ,|}|	r||f }|
stdd ||||fD S t-||||dS )NzDYou cannot specify both input_ids and inputs_embeds at the same timez5You have to specify either input_ids or inputs_embedszZ`use_cache=True` is incompatible with gradient checkpointing. Setting `use_cache=False`...Fr.   r   r   rs   r|   r!  r6   r   r   )unmasked_value)r   rV   rE   r   r   r   r   Tr7   c                 s   s    | ]	}|d ur|V  qd S r(   r.   )r   vr.   r.   r/   	<genexpr>  s    z&FalconModel.forward.<locals>.<genexpr>)last_hidden_stater}  r-   
attentions).r   r   r  r   use_return_dictr   r:   tuplelenri  re  rl  r   r
  warningrc  r4   onesre   longr   r   rK   rj   r@   rj  r   r   r   r   r   r   r   masked_fillfinfor   r   _unmask_unattendedget_head_maskrh  	enumeratezip_gradient_checkpointing_func__call__rk  r   )r,   r|  r}  rV   rE   r   r~  r   r   r  r  r   r   r   r-   presentsall_self_attentionsall_hidden_statesr   r   r   re   attention_mask_2diblockr   r>  r.   r.   r/   r0     s   








zFalconModel.forward
NNNNNNNNNN)r1   r2   r3   r   rg   rr  r4   r5   rw  r   FALCON_INPUTS_DOCSTRINGr   _CHECKPOINT_FOR_DOCr   _CONFIG_FOR_DOCr   r  r   r   r   r0   r}   r.   r.   rp   r/   r`    sV    	
r`  z{The Falcon Model transformer with a language modeling head on top (linear layer with weights tied to the input embeddings).c                       s|  e Zd ZdgZdef fddZdd Zdejfdd	Z		
	
	
d!dej
deej deej deej def
ddZeeeeeed	
	
	
	
	
	
	
	
	
	
	
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j dee dee dee dee deeej ef fd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d Z  ZS )#FalconForCausalLMzlm_head.weightr   c                    s8   t  | t|| _tj|j|jdd| _| 	  d S NFr   )
rf   rg   r`  rB  r   rH  r   rd  lm_headrm  rn  rp   r.   r/   rg     s   
zFalconForCausalLM.__init__c                 C   ro  r(   r  rq  r.   r.   r/   get_output_embeddings  rs  z'FalconForCausalLM.get_output_embeddingsrt  c                 C   ru  r(   r  rv  r.   r.   r/   set_output_embeddings  rx  z'FalconForCausalLM.set_output_embeddingsNr|  r}  rV   rE   r'   c                 K   s   |d ur(|d d j d }|j d |kr|}n|j d d }|d d |d f }| jjsU|d urU|d u rU| dd }||dkd |rU|d d |j d  d f }||||d|dS )Nr   r7   r   r6   r   )r|  rE   r}  r   rV   )r:   rB  rc  r  rU   masked_fill_get)r,   r|  r}  rV   rE   r   past_lengthremove_prefix_lengthr.   r.   r/   prepare_inputs_for_generation  s"   z/FalconForCausalLM.prepare_inputs_for_generationry  .r   r~  labelsr   r   r  r  c                 C   s   |dur|n| j j}| j||||||||	|
|d
}|d }| |}d}|durX|dddddf  }|dddf  }|j\}}}t }|||| |||| }|sn|f|dd  }|durl|f| S |S t|||j	|j
|jd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}  rV   rE   r   r~  r   r   r  r  r   .r6   r   losslogitsr}  r-   r  )r   r  rB  r  
contiguousr:   r   r   r   r}  r-   r  )r,   r|  r}  rV   rE   r   r~  r  r   r   r  r  transformer_outputsr-   	lm_logitsr  shift_logitsshift_labelsr   r   rd  loss_fctr@  r.   r.   r/   r0     sD   
zFalconForCausalLM.forwardpastbeam_idxc                    s,    fdd|D t fd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                    s&   i | ]}|D ]
}|j  |j qqS r.   )re   rl   )r   r   
past_state)r  r.   r/   
<dictcomp>6  s
    z4FalconForCausalLM._reorder_cache.<locals>.<dictcomp>c                 3   sD    | ]}|d   d  |d  j |d  d  |d  j fV  qdS )r   r   N)index_selectre   )r   r   )device_to_beam_idxr.   r/   r  9  s    
z3FalconForCausalLM._reorder_cache.<locals>.<genexpr>)r  )r,   r  r  reordered_pastr.   )r  r  r/   _reorder_cache*  s   
z FalconForCausalLM._reorder_cache)NNN)NNNNNNNNNNN)r1   r2   r3   _tied_weights_keysr   rg   r  r4   r5   r  r  r   dictr  r   r  r   r  r   r  r   r   r   r0   r  r}   r.   r.   rp   r/   r    s    
$	
?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dZeeeee	e
d										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dZ  ZS )FalconForSequenceClassificationr   c                    s@   t  | |j| _t|| _tj|j|jdd| _| 	  d S r  )
rf   rg   
num_labelsr`  rB  r   rH  r   scorerm  rn  rp   r.   r/   rg   S  s
   
z(FalconForSequenceClassification.__init__ry  Nr|  r}  .rV   r   r~  r  r   r   r  r  r'   c                 C   s  |
dur|
n| j j}
| j||||||||	|
d	}|d }| |}|dur+|jd }n|jd }| j jdu r>|dkr>td| j jdu rGd}n#|dur^t|| j jj	ddd 
|j}nd}t| jj d |tj||jd	|f }d}|dur| j jdu r| jdkrd
| j _n| jdkr|jtjks|jtjkrd| j _nd| j _| j jd
krt }| jdkr|| | }n#|||}n| j jdkrt }|||}n| j jdkrt }|||}|
s|f|dd  }|dur|f| S |S t|||j|j|jd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}  rV   r   r~  r   r   r  r  r   r   z=Cannot handle batch sizes > 1 if no padding token is defined.r6   r8   z will not detect padding tokens in `inputs_embeds`. Results may be unexpected if using padding tokens in conjunction with `inputs_embeds.`)re   
regressionsingle_label_classificationmulti_label_classificationr  )r   r  rB  r  r:   pad_token_idr   r4   nerM   rl   re   r
  r  rq   r1   rj   problem_typer  rK   r  intr
   r"  r   r   r   r}  r-   r  )r,   r|  r}  rV   r   r~  r  r   r   r  r  r  r-   r  r   sequence_lengthspooled_logitsr  r  r@  r.   r.   r/   r0   \  sr   

&

"


z'FalconForSequenceClassification.forwardr  )r1   r2   r3   r   rg   r   r  r   r  r   r  r   r4   r  r   r5   r   r   r0   r}   r.   r.   rp   r/   r  C  sR    		
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                       r  )FalconForTokenClassificationr   c                    s|   t  | |j| _t|| _t|dd d ur|j}nt|dd d ur'|j}nd}t	|| _
t|j|j| _|   d S )Nclassifier_dropoutr   g?)rf   rg   r  r`  rB  rT  r  r   r   r   r   rH  r   
classifierrm  )r,   r   r  rp   r.   r/   rg     s   
z%FalconForTokenClassification.__init__ry  Nr|  r}  .rV   r   r~  r  r   r   r  r  r'   c                 C   s   |
dur|
n| j j}
| j||||||||	|
d	}|d }| |}| |}d}|durE|j\}}t }|||| | j||| }|
s[|f|dd  }|durY|f| S |S t	|||j
|jdS )r  Nr  r   r7   )r  r  r-   r  )r   r  rB  r   r  r:   r   r   r  r   r-   r  )r,   r|  r}  rV   r   r~  r  r   r   r  r  r  r-   r  r  r   r   r  r@  r.   r.   r/   r0     s>   


z$FalconForTokenClassification.forwardr  )r1   r2   r3   r   rg   r   r  r   r  r   r  r   r4   r  r   r5   r   r   r0   r}   r.   r.   rp   r/   r    sR    	
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                       s   e Zd Z fd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dZ  ZS )FalconForQuestionAnsweringc                    s2   t  | t|| _t|jd| _|   d S )Nr7   )	rf   rg   r`  rB  r   rH  r   
qa_outputsrm  rn  rp   r.   r/   rg      s   
z#FalconForQuestionAnswering.__init__Nr|  rV   r   r~  start_positionsend_positionsr   r  r  r'   c
              	   C   sD  |	dur|	n| j j}	| j|||||||	d}
|
d }| |}|jddd\}}|d }|d }d}|dur|durt| dkrM|d}t| dkrZ|d}|d}|	d|}|	d|}t
|d}|||}|||}|| d }|	s||f|
dd  }|dur|f| S |S t||||
j|
jd	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)rV   r   r~  r   r  r  r   r   r6   r8   )ignore_indexr7   )r  start_logits
end_logitsr-   r  )r   r  rB  r  splitr"  r  r  sizeclampr   r   r-   r  )r,   r|  rV   r   r~  r  r  r   r  r  r>  sequence_outputr  r  r  
total_lossignored_indexr  
start_lossend_lossr@  r.   r.   r/   r0   (  sL   







z"FalconForQuestionAnswering.forward)	NNNNNNNNN)r1   r2   r3   rg   r   r  r   r4   r  FloatTensorr   r   r   r   r0   r}   r.   r.   rp   r/   r    sB    	

r  )r   )Wr   r   r   typingr   r   r   r   r4   torch.utils.checkpointr   torch.nnr   r   r	   r
   r   rS   modeling_attn_mask_utilsr   r   r   modeling_outputsr   r   r   r   r   modeling_utilsr   pytorch_utilsr   utilsr   r   r   r   r   r   configuration_falconr   configuration_utilsr   
flash_attnr    r!   flash_attn.bert_paddingr"   r#   r$   
get_loggerr1   r
  $FALCON_PRETRAINED_MODEL_ARCHIVE_LISTr  r  rH  r%   r?   rI   r[   r^  r\   r   r   r5   r  
BoolTensorr   rK   r   rk   r   r   r   r  r%  r1  r.  FALCON_START_DOCSTRINGr  rA  r`  r  r  r  r  r.   r.   r.   r/   <module>   s    
	
% $   QX<4 V mR