U
    9%e#                    @   s  d Z ddlZddl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mZmZ dd	lmZ dd
lmZmZmZmZmZ ddlmZ e rddl m!Z!m"Z" ddl#m$Z$m%Z%m&Z& e'e(Z)ddddddgZ*dZ+dZ,G dd dej-Z.dd Z/dd Z0G dd dej1Z2G dd  d e2Z3G d!d" d"e2Z4ej5ej6e7ej8d#d$d%Z9ej:e7ej8d&d'd(Z;ej:e7ej<ej:d)d*d+Z=ej:ej:e>e?ej:d,d-d.Z@G d/d0 d0ej1ZAG d1d2 d2eAZBG d3d4 d4ej1ZCG d5d6 d6ej1ZDd7ZEd8ZFG d9d: d:eZGed;eEG d<d= d=eGZHed>eEG d?d@ d@eGZIedAeEG dBdC dCeGZJedDeEG dEdF dFeGZKedGeEG dHdI dIeGZLdS )JzPyTorch Falcon model.    N)OptionalTupleUnion)nn)BCEWithLogitsLossCrossEntropyLoss	LayerNormMSELoss)
functional   ))BaseModelOutputWithPastAndCrossAttentions!CausalLMOutputWithCrossAttentionsQuestionAnsweringModelOutput SequenceClassifierOutputWithPastTokenClassifierOutput)PreTrainedModel)add_code_sample_docstringsadd_start_docstrings%add_start_docstrings_to_model_forwardis_flash_attn_availablelogging   )FalconConfig)flash_attn_funcflash_attn_varlen_func)index_first_axis	pad_inputunpad_inputz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ejejdddZdS )FalconLinear)inputreturnc                 C   s$   || j j }| jd kr|S || j S N)weightTbias)selfr   hidden_states r'   i/var/www/html/Darija-Ai-API/env/lib/python3.8/site-packages/transformers/models/falcon/modeling_falcon.pyforwardA   s    
zFalconLinear.forwardN)__name__
__module____qualname__torchTensorr)   r'   r'   r'   r(   r   @   s   r   c                 C   sJ   | dd | j d d f | d| j d d d f  }}tj| |fddS )N.   dim)shaper-   cat)xx1Zx2r'   r'   r(   rotate_halfI   s    6r7   c                 C   sX   | j dtjd}tj|  dd }|  }ttj	|dtjjdd}|||fS )Nr/   r2   dtypeF)as_tupler   )r   r   )
sumr-   int32ZnonzeroflattenmaxitemFpadcumsum)padding_maskZseqlens_in_batchindicesZmax_seqlen_in_batchZ
cu_seqlensr'   r'   r(   _get_unpad_dataO   s    rE   c                       sX   e Zd ZdZded fddZdd Zd	ejfeeej	ej	d
ddZ
dd Z  ZS )FalconRotaryEmbeddingzImplementation of RotaryEmbedding from GPT-NeoX.
    This implementation is designed to operate on queries and keys that are compatible with `[batch_size,
    n_heads_per_partition, seq_len, head_dim]` (e.g. MinGPTAttention format).
    '     head_dimc                    sb   t    || _|| _d| jtd|d |   }| jd|dd || _d| _	d | _
d | _d S )N      ?r   r0   inv_freqF
persistentr/   )super__init__basemax_position_embeddingsr-   arangefloatregister_bufferrJ   seq_len_cached
cos_cached
sin_cached)r%   rJ   rQ   rR   rL   	__class__r'   r(   rP   b   s    
 zFalconRotaryEmbedding.__init__c                 C   s   || _ tj||| jjd}td|| j}tj||fdd|}|tjtj	fkrZ|
 }| d d d d d f | _| d d d d d f | _| j|| _| j|| _d S Ndevicer9   i,j->ijr/   r1   )rV   r-   rS   rL   r9   einsumr4   tofloat16bfloat16rT   cosrW   sinrX   typer%   seq_lenr]   r9   tfreqsembr'   r'   r(   _set_cos_sin_cachem   s    z(FalconRotaryEmbedding._set_cos_sin_cachecpu)rg   past_key_values_lengthposition_idsr    c           	      C   sd   || }|| j kr | ||| | j|| _| j|| _| jd| }| jd| }||fS )Nr   )rV   rk   rW   r`   rX   squeeze)	r%   rg   rm   rn   r]   r9   total_lengthrc   rd   r'   r'   r(   cos_sin|   s    
zFalconRotaryEmbedding.cos_sinc                 C   s   |j \}}}| ||||j|j\}}t|j d |j d  }	|	dkrhtj||	dd}
tj||	dd}n
|| }
}t|j d |j d  }|dkr||	krtj||dd}tj||dd}q|
| }}n
|| }}||
 t||  || t||  fS )Nr   r   r1   )r3   rq   r]   r9   intr-   Zrepeat_interleaver7   )r%   querykeyrm   rn   _rg   rc   rd   Zquery_expansion_factorZ	query_cosZ	query_sinZkey_expansion_factorZkey_cosZkey_sinr'   r'   r(   r)      s    

zFalconRotaryEmbedding.forward)rG   rH   )r*   r+   r,   __doc__rr   rP   rk   r-   rb   r.   rq   r)   __classcell__r'   r'   rY   r(   rF   \   s      rF   c                       s0   e Zd ZdZd
ed fddZdd	 Z  ZS )"FalconLinearScalingRotaryEmbeddingz\FalconRotaryEmbedding extended with linear scaling. Credits to the Reddit user /u/kaiokendevrG   rH   rK   rI   c                    s   || _ t ||| d S r!   scaling_factorrO   rP   r%   rJ   rQ   rR   rz   rY   r'   r(   rP      s    z+FalconLinearScalingRotaryEmbedding.__init__c                 C   s   || _ tj||| jjd}|| j }td|| j}tj||fdd|}|tj	tj
fkrd| }| d d d d d f | _| d d d d d f | _| j|| _| j|| _d S r[   )rV   r-   rS   rL   r9   rz   r_   r4   r`   ra   rb   rT   rc   rW   rd   rX   re   rf   r'   r'   r(   rk      s    
z5FalconLinearScalingRotaryEmbedding._set_cos_sin_cache)rG   rH   rK   r*   r+   r,   rv   rr   rP   rk   rw   r'   r'   rY   r(   rx      s   rx   c                       s0   e Zd ZdZd
ed fddZdd	 Z  ZS )&FalconDynamicNTKScalingRotaryEmbeddingzx
    FalconRotaryEmbedding extended with Dynamic NTK scaling. Credits to the Reddit users /u/bloc97 and /u/emozilla
    rG   rH   rK   rI   c                    s   || _ t ||| d S r!   ry   r{   rY   r'   r(   rP      s    z/FalconDynamicNTKScalingRotaryEmbedding.__init__c           	      C   s$  || _ || jkrx| j| j| | j | jd  | j| jd    }d|td| jd || j   }| j	d|dd tj||| j
jd}td	|| j
}tj||fd
d|}|tjtjfkr| }| d d d d d f | _| d d d d d f | _| j|| _| j|| _d S )Nr   r0   rK   r   rL   FrM   r\   r^   r/   r1   )rV   rR   rQ   rz   rJ   r-   rS   rT   r`   rU   rL   r9   r_   r4   ra   rb   rc   rW   rd   rX   re   )	r%   rg   r]   r9   rQ   rL   rh   ri   rj   r'   r'   r(   rk      s"    
(z9FalconDynamicNTKScalingRotaryEmbedding._set_cos_sin_cache)rG   rH   rK   r|   r'   r'   rY   r(   r}      s   r}   )input_ids_shaper]   rm   r    c                 C   s|   | \}}t jt j||ft j|ddd}t j||ft j|d}t j||gdd}|ddddddf |d||| }|S )a  
    Make causal mask used for self-attention. This mask does not take the existing attention mask into account - it
    just blocks tokens from attending forwards in the sequence. The output shape will be `[batch_size, 1,
    target_length, target_length+past_key_values_length]`.
    r9   r]   r   )Zdiagonalr/   r1   N)r-   ZtriuonesboolZzerosr4   expand)r~   r]   rm   
batch_sizeZtarget_lengthmaskZ	past_maskexpanded_maskr'   r'   r(   _make_causal_mask   s     (r   )r   rm   r    c                 C   sP   | j \}}|dk	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   )r3   r`   r-   r   r   )r   rm   r   rp   
seq_lengthr   r'   r'   r(   _expand_mask   s    
"r   )attention_mask	num_headsr9   r    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rt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 )	Nr0   r   r\   r   r   r1   r/   ).N)r3   mathfloorlog2r-   Ztensorr]   float32rS   r<   powminr4   rB   rb   reshaper`   )r   r   r9   r   r   Zclosest_power_of_2rQ   ZpowersZslopesZ
extra_baseZnum_remaining_headsZextra_powersZarange_tensoralibir'   r'   r(   build_alibi_tensor   s*    
     &r   )r5   residualprobtrainingr    c                 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   )r@   dropout)r5   r   r   r   outr'   r'   r(   dropout_add  s    r   c                       s   e Zd Zed fddZdd Zejeejejejf dddZ	ejejd	d
dZ
dejeej ejeej eeejejf  eej eeeej d	ddZ  ZS )FalconAttentionconfigc                    sD  t    || _|j| _|j| _| j| j | _| j| _|j| _| j| j | jkrjt	d| j d| j d|j
rx|  ndd | _dt| j | _| j| _|jr|jd |j | j }n"|jr| jd| j  }n
d| j }t| j||jd	| _|j| _|j| _t| j| j|jd	| _t|j| _| js4| js:|jnd
| _d S )NzA`hidden_size` must be divisible by num_heads (got `hidden_size`: z and `num_heads`: z).c                 S   s   | |fS r!   r'   )qkrh   r   r'   r'   r(   <lambda>A      z*FalconAttention.__init__.<locals>.<lambda>rK   r0   r   r$   r   )rO   rP   r   hidden_sizenum_attention_headsr   rJ   Z
split_sizehidden_dropout
ValueErrorZrotary
_init_ropemaybe_rotaryr   sqrtinv_norm_factorbetanew_decoder_architecturenum_kv_headsmulti_queryr   r$   query_key_valuedenser   Dropoutattention_dropout)r%   r   Zqkv_out_dimrY   r'   r(   rP   1  s2    

zFalconAttention.__init__c                 C   s   | j jd kr&t| j| j j| j jd}nn| j jd }| j jd }|dkrbt| j| j j| j j|d}n2|dkrt| j| j j| j j|d}ntd| |S )N)rQ   rR   re   factorZlinear)rQ   rR   rz   ZdynamiczUnknown RoPE scaling type )	r   Zrope_scalingrF   rJ   Z
rope_thetarR   rx   r}   r   )r%   Z
rotary_embZscaling_typerz   r'   r'   r(   r   S  s0    zFalconAttention._init_rope)	fused_qkvr    c                 C   s  | j r|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 d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]
        r/   r0   Nc                 S   s   g | ]}| d dqS )r0   r   )r=   ).0r5   r'   r'   r(   
<listcomp>  s     z0FalconAttention._split_heads.<locals>.<listcomp>r   .r   r   )	r   r3   viewr   r   rJ   r-   Zbroadcast_tor   )r%   r   batchrg   ru   Zqkvrs   rt   valuer   r   Zthree_times_hidden_sizer'   r'   r(   _split_headso  s"      
4zFalconAttention._split_headsr5   r    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   r0   r   r   )r3   r   r   rJ   permuter   )r%   r5   Zbatch_size_and_num_headsr   ru   r   r'   r'   r(   _merge_heads  s
    
zFalconAttention._merge_headsNF	r&   r   r   rn   
layer_past	head_mask	use_cacheoutput_attentionsrC   c
           %      C   s>  |  |}
| jr| jn| j}| |
\}}}|j\}}}}|dd|| j || j}|dd|| || j}|dd|| || j}|d krdn|d jd }| 	||||\}}|d k	r|\}}t
j||fdd}t
j||fdd}|j\}}}|r||f}nd }t
|jj}|d |||j}||| jd| j}|||d| j}|||d| j}|d krNttdr|std tj||||d	d
d}d }n>||dd }|t| j }tj|| d|jd}|| }||| j|| j}|dddd}|||| j| j }| |}|rD|||fS ||fS n||dd }||| j||}|j} | t
jks| t
jkr|t
j}|||| jdd }!|!| j9 }!tj|!| d|jd}"|  |"}"|d k	r|"| }"|"|| j||}#|#| !dd}$| "|$}$| |$}|r2|||"fS ||fS d S )Nr   r0   r   r1   rK   r/   scaled_dot_product_attentionas  The current implementation of Falcon calls `torch.scaled_dot_product_attention` directly, this will be deprecated in the future in favor of the `BetterTransformer` API. Please install the latest optimum library with `pip install -U optimum` and call `model.to_bettertransformer()` to benefit from `torch.scaled_dot_product_attention` and future performance optimizations.        F)Z	is_causalr   r8   r   )#r   r   r   r   r   r3   	transposer   rJ   r   r-   r4   Zfinfor9   r   Zmasked_fillr`   hasattrr@   loggerwarning_oncer   r   r   Zsoftmaxr   r   r   ra   rb   r   r   r   r=   r   )%r%   r&   r   r   rn   r   r   r   r   rC   r   r   query_layer	key_layervalue_layerr   query_lengthru   past_kv_lengthpast_key
past_value	kv_lengthZpresentZ	float_minZattention_mask_floatZquery_layer_Z
key_layer_Zvalue_layer_attn_outputZattention_scoresZoutput_tensorZmatmul_resultinput_dtypeZattention_logitsZattention_probsZattention_probs_reshapedZcontext_layerr'   r'   r(   r)     s    


       








zFalconAttention.forward)NNNFFN)r*   r+   r,   r   rP   r   r-   r.   r   r   r   r   
LongTensorr   r)   rw   r'   r'   rY   r(   r   0  s*   ""       r   c                   @   sn   e Zd ZdZdejeej ejeej eeejejf  eej e	e	eej d	ddZ
ddd	Zd
d Zd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.
    NFr   c
                 C   s*  |  |}
| jr| jn| j}| |
\}}}|j\}}}}|dd|| j || j}|dd|| || j}|dd|| || j}|d krdn|d jd }| 	||||\}}|d k	r|r|\}}t
j||fdd}t
j||fdd}|j\}}}|j}|r||fnd }||| jd| jdd|}|||d| jdd|}|||d| jdd|}|d k	rtd| jr| jnd}|j}|t
jkrtd |t
j}|t
j}|t
j}| j||||	||d	}|||| j| j }| |}|s d }|||fS )
Nr   r0   r   r1   r/   z6`alibi` is not supported when `use_flash_attn` is Truer   zThe 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 float16.)r   )r   r   r   r   r   r3   r   r   rJ   r   r-   r4   r9   r`   r   r   r   r   r   r   ra   _flash_attention_forwardr   )r%   r&   r   r   rn   r   r   r   r   rC   r   r   r   r   r   r   r   ru   r   r   r   Zkv_seq_lengthZtorch_dtypepast_key_valueZattn_dropoutr   r   Zattn_weightsr'   r'   r(   r)   ,  s`    
   
     
zFalconFlashAttention2.forwardr   c                 C   s   |dk	rl|j d }| |||||\}}}}	}
}|
\}}|\}}t|||||||||dd
}t||	||}nt|||||d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
            padding_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)
        Nr   T)cu_seqlens_qcu_seqlens_kZmax_seqlen_qZmax_seqlen_kZ	dropout_psoftmax_scalecausal)r   r   )r3   _upad_inputr   r   r   )r%   Zquery_statesZ
key_statesZvalue_statesrC   r   r   r   r   	indices_qZcu_seq_lensZmax_seq_lensr   r   max_seqlen_in_batch_qmax_seqlen_in_batch_kZattn_output_unpadr   r'   r'   r(   r     sB    
         z.FalconFlashAttention2._flash_attention_forwardc                 C   s   t |\}}}|j\}	}
}}t||	|
 |||}t||	|
 |||}||
kr|t||	|
 | j||}|}|}|}nd|dkrd}tj|	d tj|jd}|d d }|	d}n(|d d | d f }t
||\}}}}||||||f||ffS )Nr   r   r/   )rE   r3   r   r   r   r-   rS   r<   r]   ro   r   )r%   r   r   r   rC   r   Z	indices_kr   r   r   Z
kv_seq_lenZnum_key_value_headsrJ   r   r   r   r'   r'   r(   r     sH         z!FalconFlashAttention2._upad_input)NNNFFN)r   N)r*   r+   r,   rv   r-   r.   r   r   r   r   r)   r   r   r'   r'   r'   r(   r   %  s,         T   
6r   c                       s6   e Zd Zed fddZejejdddZ  ZS )	FalconMLPr   c                    sR   t    |j}t|d| |jd| _t | _td| ||jd| _	|j
| _
d S )N   r   )rO   rP   r   r   r$   dense_h_to_4hr   ZGELUactdense_4h_to_hr   r%   r   r   rY   r'   r(   rP     s    

zFalconMLP.__init__r   c                 C   s   |  | |}| |}|S r!   )r   r   r   )r%   r5   r'   r'   r(   r)     s    
zFalconMLP.forward)	r*   r+   r,   r   rP   r-   r.   r)   rw   r'   r'   rY   r(   r     s   	r   c                       sn   e Zd Zed fddZd	ejeej ejeej ee	ejejf  eej e
e
eej d	ddZ  ZS )
FalconDecoderLayerr   c                    s   t    |j}|j| _t|dds,t|nt|| _t	|| _
|j| _|| _|jrvt||jd| _t||jd| _n&t||jd| _|jst||jd| _d S )NZ_flash_attn_2_enabledFZeps)rO   rP   r   r   r   getattrr   r   self_attentionr   mlpr   r   r   r   layer_norm_epsilonln_attnln_mlpinput_layernormparallel_attnpost_attention_layernormr   rY   r'   r(   rP     s     



zFalconDecoderLayer.__init__NFr   c
                 C   s   |}
| j jr"| |}| |}n
| |}| j|||||||||	d	}|d }| j js| j jrf|}n t||
| j j| j	d}
| 
|
}|dd  }| |}| j js| j jr||7 }t||
| j j| j	d}|r|f| }n|f|dd   }|S )N)r   r   rn   r   r   r   r   rC   r   )r   r   )r   r   r   r   r   r   r   r   r   r   r   r   r   )r%   r&   r   r   rn   r   r   r   r   rC   r   Zattention_layernorm_outZmlp_layernorm_outZattn_outputsZattention_outputoutputsZ
mlp_outputoutputr'   r'   r(   r)     sH    

   

zFalconDecoderLayer.forward)NNNFFN)r*   r+   r,   r   rP   r-   r.   r   r   r   r   r)   rw   r'   r'   rY   r(   r     s$         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                       s   e Zd ZdZeZdZdZdgZdZ	 fddZ
ejddd	ZdejedddZeeeejejf  eeeejejf  dddZeeeejejf  eeejejf  d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|| d S r!   )rO   rP   )r%   inputskwargsrY   r'   r(   rP     s    zFalconPreTrainedModel.__init__modulec                 C   s   t |tjst |trD|jjjd| jjd |j	dk	r|j	j
  ndt |tjr|jjjd| jjd |jdk	r|jj|j 
  n$t |tr|j	j
  |jjd dS )zInitialize the weights.r   )ZmeanZstdNrK   )
isinstancer   Linearr   r"   dataZnormal_r   Zinitializer_ranger$   Zzero_	EmbeddingZpadding_idxr   Zfill_)r%   r   r'   r'   r(   _init_weights  s    


z#FalconPreTrainedModel._init_weightsF)r   r   c                 C   s   t |tr||_d S r!   )r   FalconModelgradient_checkpointing)r%   r   r   r'   r'   r(   _set_gradient_checkpointing  s    
z1FalconPreTrainedModel._set_gradient_checkpointing)r   r   r    c                    s8   | d d j \}|  t fdd| D S )z
        Standardizes the format of the cache so as to match most implementations, i.e. to tuple(tuple([batch_size,
        num_heads, ...]))
        r   c                 3   s6   | ].}|d    |d   fV  qdS r   r   Nr   r   r   r   rJ   r   r   r'   r(   	<genexpr>  s   zJFalconPreTrainedModel._convert_cache_to_standard_format.<locals>.<genexpr>r3   tuple)r   r   batch_size_times_num_headsr'   r  r(   !_convert_cache_to_standard_format  s
    z7FalconPreTrainedModel._convert_cache_to_standard_format)r   r    c                    s8   | d d j \}}||  t fdd| D S )Nr   c                 3   s2   | ]*}|d    |d   fV  qdS r  r  r  r  rJ   r   r'   r(   r    s   z=FalconPreTrainedModel._convert_to_rw_cache.<locals>.<genexpr>r  )r   r   r   r'   r
  r(   _convert_to_rw_cache  s
    z*FalconPreTrainedModel._convert_to_rw_cache)F)r*   r+   r,   rv   r   config_classZbase_model_prefixZsupports_gradient_checkpointingZ_no_split_modulesZ_supports_flash_attn_2rP   r   Moduler   r   r   staticmethodr   r-   r.   rr   r	  r  rw   r'   r'   rY   r(   r     s$    r   z`The bare Falcon Model transformer outputting raw hidden-states without any specific head on top.c                       s   e Zd Zed fddZdd Zeeje	e
e
f e
ejdddZejd	d
dZeeeeeeddeej ee	e	ejejf df  eej eej eej eej ee ee ee ee ee	ejdf ef dddZ  ZS )r   r   c                    sz   t     j| _ j| _ j| _t	 j
| j| _t fddt jD | _t| j jd| _d| _|   d S )Nc                    s   g | ]}t  qS r'   )r   )r   ru   r   r'   r(   r     s     z(FalconModel.__init__.<locals>.<listcomp>r   F)rO   rP   r   Z	embed_dimr   r   r   	use_alibir   r   
vocab_sizeword_embeddingsZ
ModuleListrangenum_hidden_layershr   r   ln_fr   	post_initr%   r   rY   r   r(   rP     s     zFalconModel.__init__c                 C   s   | j S r!   r  r%   r'   r'   r(   get_input_embeddings  s    z FalconModel.get_input_embeddings)r   input_shaperm   r    c                 C   s   |d | | j d kr4td| j  d| d| dd }| j}|\}}|dkr\t|||d}t| |d}|d krt|n||B }|S )Nr   zXAttention mask shape should be (batch_size, seq_length + past_key_values_length) but is z with input_ids shape z and past length .)r]   rm   )rm   )r3   r   r]   r   r   )r   r  rm   Zcombined_attention_maskr]   ru   r   Zexpanded_attn_maskr'   r'   r(   _prepare_attn_mask  s"      zFalconModel._prepare_attn_masknew_embeddingsc                 C   s
   || _ d S r!   r  r%   r  r'   r'   r(   set_input_embeddings  s    z FalconModel.set_input_embeddings
checkpointoutput_typer  N.)	input_idspast_key_valuesr   rn   r   inputs_embedsr   r   output_hidden_statesreturn_dictr    c                    sN   d k	r n| j j |	d k	r |	n| j j}	d k	r4n| j j|
d k	rH|
n| j j}
|d k	rj|d k	rjtdn2|d k	r~|j\}}n|d k	r|j\}}}ntd|d krtd gt| j	 }n
| 
|}| || j j}|d kr| |}|}rdnd } rdnd }|	rdnd }d}|d d k	r4|d d jd }|d kr\tj||| f|jd}d }n ||j}d|krx|}nd }| jrt|| j|jd}n`d }|d kr|d k	r|jn|j}tj||| tj|d}|dd	|}n|d	| }| j|||f|d
}tt| j	|D ]\}\}}|	r8||f }| jr| jrr\t d d fdd}tj!j""|||||||| |}n|||||||  ||d	}|d }dkr||d f } r||rdnd f }q| #|}|	r||f }|d k	r| $||}|
s>t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_embedsr'   r   r   r]   )r9   r   r/   )r  rm   zZ`use_cache=True` is incompatible with gradient checkpointing. Setting `use_cache=False`...Fc                    s    fdd}|S )Nc                     s    | dS )N)r   r   r'   )r   )r   r   r   r'   r(   custom_forward{  s    zJFalconModel.forward.<locals>.create_custom_forward.<locals>.custom_forwardr'   )r   r+  r   r   r   r(   create_custom_forwardz  s    z2FalconModel.forward.<locals>.create_custom_forward)r   r   rn   r   r   r   r   rC   Tr0   c                 s   s   | ]}|d k	r|V  qd S r!   r'   )r   vr'   r'   r(   r    s      z&FalconModel.forward.<locals>.<genexpr>)Zlast_hidden_stater&  r&   
attentions)&r   r   r(  r   use_return_dictr   r3   r  lenr  r  Zget_head_maskr  r  r-   r   r]   r`   r  r   r   r9   rS   long	unsqueezer   r  	enumeratezipr   r   r   warningutilsr#  r  r	  r   )r%   r%  r&  r   rn   r   r'  r   r   r(  r)  r   r   ru   r&   ZpresentsZall_self_attentionsZall_hidden_statesrm   rC   r   r]   Zcausal_maskiblockr   r-  r   r'   r,  r(   r)     s    





   





zFalconModel.forward)
NNNNNNNNNN)r*   r+   r,   r   rP   r  r  r-   r.   r   rr   
BoolTensorr  r!  r   FALCON_INPUTS_DOCSTRINGr   _CHECKPOINT_FOR_DOCr   _CONFIG_FOR_DOCr   r   r   r   r)   rw   r'   r'   rY   r(   r     sL    
           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ed fddZdd Zejddd	Z	dej
eej eej eej edddZeeeeeeddeej
 eeeejejf df  eej eej
 eej eej eej ee ee ee ee eeej ef dddZeeejejf df ej
eeejejf df dddZ  ZS )FalconForCausalLMzlm_head.weightr   c                    s8   t  | t|| _tj|j|jdd| _| 	  d S NFr   )
rO   rP   r   r   r   r   r   r  lm_headr  r  rY   r'   r(   rP     s    
zFalconForCausalLM.__init__c                 C   s   | j S r!   r@  r  r'   r'   r(   get_output_embeddings  s    z'FalconForCausalLM.get_output_embeddingsr  c                 C   s
   || _ d S r!   rA  r   r'   r'   r(   set_output_embeddings  s    z'FalconForCausalLM.set_output_embeddingsN)r%  r&  r   rn   r    c                 K   s   |d k	r|d d dd f }| j jsp|d k	rp|d krp| dd }||dkd |rp|d d df d}||||d|dS )Nr/   r   r   r   )r%  rn   r&  r   r   )r   r  r2  rB   Zmasked_fill_r3  get)r%   r%  r&  r   rn   r   r'   r'   r(   prepare_inputs_for_generation  s    z/FalconForCausalLM.prepare_inputs_for_generationr"  .)r%  r&  r   rn   r   r'  labelsr   r   r(  r)  r    c                 C   s   |dk	r|n| j j}| j||||||||	|
|d
}|d }| |}d}|dk	r|dddddf  }|dddf  }|j\}}}t }|||| |||| }|s|f|dd  }|dk	r|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&  r   rn   r   r'  r   r   r(  r)  r   .r/   r   losslogitsr&  r&   r/  )r   r0  r   r@  
contiguousr3   r   r   r   r&  r&   r/  )r%   r%  r&  r   rn   r   r'  rF  r   r   r(  r)  transformer_outputsr&   Z	lm_logitsrH  Zshift_logitsZshift_labelsr   r   r  loss_fctr   r'   r'   r(   r)     sF    
 zFalconForCausalLM.forward)pastbeam_idxr    c                    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'   )r]   r`   )r   r   Z
past_state)rN  r'   r(   
<dictcomp>3  s
       z4FalconForCausalLM._reorder_cache.<locals>.<dictcomp>c                 3   sB   | ]:}|d   d  |d  j |d  d  |d  j fV  qdS r  )Zindex_selectr]   r  )device_to_beam_idxr'   r(   r  6  s   z3FalconForCausalLM._reorder_cache.<locals>.<genexpr>)r  )r%   rM  rN  Zreordered_pastr'   )rN  rP  r(   _reorder_cache'  s    
z FalconForCausalLM._reorder_cache)NNN)NNNNNNNNNNN)r*   r+   r,   Z_tied_weights_keysr   rP   rB  r-   r.   rC  r   r   dictrE  r   r;  r   r<  r   r=  r   r   r   r)   rQ  rw   r'   r'   rY   r(   r>    sb                 @ 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                       s   e Zd Zed fddZeeeee	e
dd
eej eeeejejf df  eej eej eej eej ee ee ee ee eeej e	f ddd	Z  ZS )FalconForSequenceClassificationr   c                    s@   t  | |j| _t|| _tj|j|jdd| _| 	  d S r?  )
rO   rP   
num_labelsr   r   r   r   r   scorer  r  rY   r'   r(   rP   P  s
    
z(FalconForSequenceClassification.__init__r"  N.r%  r&  r   r   r'  rF  r   r   r(  r)  r    c                 C   s  |
dk	r|
n| j j}
| j||||||||	|
d	}|d }| |}|dk	rV|jd }n
|jd }| j jdkr||dkr|td| j jdkrd}nF|dk	rt|| j jj	ddd 
|j}nd}t| jj d |tj||jd	|f }d}|dk	r| j jdkrX| jdkrd
| j _n:| jdkrP|jtjksF|jtjkrPd| 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k	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&  r   r   r'  r   r   r(  r)  r   r   z=Cannot handle batch sizes > 1 if no padding token is defined.r/   r1   z will not detect padding tokens in `inputs_embeds`. Results may be unexpected if using padding tokens in conjunction with `inputs_embeds.`r*  Z
regressionZsingle_label_classificationZmulti_label_classificationrG  )r   r0  r   rU  r3   Zpad_token_idr   r-   ner;   r`   r]   r   r6  rZ   r*   rS   Zproblem_typerT  r9   r2  rr   r	   ro   r   r   r   r&  r&   r/  )r%   r%  r&  r   r   r'  rF  r   r   r(  r)  rK  r&   rI  r   Zsequence_lengthsZpooled_logitsrH  rL  r   r'   r'   r(   r)   Y  sr    

&

(

z'FalconForSequenceClassification.forward)
NNNNNNNNNN)r*   r+   r,   r   rP   r   r;  r   r<  r   r=  r   r-   r   r   r.   r   r   r)   rw   r'   r'   rY   r(   rS  @  s<   	          rS  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                       s   e Zd Zed fddZeeeee	e
dd
eej eeeejejf df  eej eej eej eej ee ee ee ee eeej e	f ddd	Z  ZS )FalconForTokenClassificationr   c                    s|   t  | |j| _t|| _t|dd d k	r6|j}nt|dd d k	rN|j}nd}t	|| _
t|j|j| _|   d S )Nclassifier_dropoutr   g?)rO   rP   rT  r   r   r   r[  r   r   r   r   r   r   
classifierr  )r%   r   r[  rY   r'   r(   rP     s    
z%FalconForTokenClassification.__init__r"  N.rV  c                 C   s   |
dk	r|
n| j j}
| j||||||||	|
d	}|d }| |}| |}d}|dk	r|j\}}t }|||| | j||| }|
s|f|dd  }|dk	r|f| S |S t	|||j
|jdS )rW  NrX  r   r0   )rH  rI  r&   r/  )r   r0  r   r   r\  r3   r   r   rT  r   r&   r/  )r%   r%  r&  r   r   r'  rF  r   r   r(  r)  rK  r&   rI  rH  r   r   rL  r   r'   r'   r(   r)     s@    


 z$FalconForTokenClassification.forward)
NNNNNNNNNN)r*   r+   r,   r   rP   r   r;  r   r<  r   r=  r   r-   r   r   r.   r   r   r)   rw   r'   r'   rY   r(   rZ    s<             rZ  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eej eej	 eej	 eej	 eej eej ee
 ee
 ee
 eeef d
ddZ  ZS )FalconForQuestionAnsweringc                    s2   t  | t|| _t|jd| _|   d S )Nr0   )	rO   rP   r   r   r   r   r   
qa_outputsr  r  rY   r'   r(   rP     s    
z#FalconForQuestionAnswering.__init__N)
r%  r   r   r'  start_positionsend_positionsr   r(  r)  r    c
              	   C   sL  |	dk	r|	n| j j}	| j|||||||	d}
|
d }| |}|jddd\}}|d }|d }d}|dk	r|dk	rt| dkr|d}t| dkr|d}|d}|	d|}|	d|}t
|d}|||}|||}|| d }|	s6||f|
dd  }|dk	r2|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)r   r   r'  r   r(  r)  r   r   r/   r1   )Zignore_indexr0   )rH  start_logits
end_logitsr&   r/  )r   r0  r   r^  splitro   rJ  r1  sizeclampr   r   r&   r/  )r%   r%  r   r   r'  r_  r`  r   r(  r)  r   Zsequence_outputrI  ra  rb  Z
total_lossZignored_indexrL  Z
start_lossZend_lossr   r'   r'   r(   r)   %  sL    







z"FalconForQuestionAnswering.forward)	NNNNNNNNN)r*   r+   r,   rP   r   r;  r   r-   r   ZFloatTensorr   r   r   r   r)   rw   r'   r'   rY   r(   r]    s.            
r]  )Mrv   r   typingr   r   r   r-   Ztorch.utils.checkpointr   Ztorch.nnr   r   r   r	   r
   r@   Zmodeling_outputsr   r   r   r   r   Zmodeling_utilsr   r7  r   r   r   r   r   Zconfiguration_falconr   Z
flash_attnr   r   Zflash_attn.bert_paddingr   r   r   Z
get_loggerr*   r   Z$FALCON_PRETRAINED_MODEL_ARCHIVE_LISTr<  r=  r   r   r7   rE   r  rF   rx   r}   Sizer]   rr   r:  r   r.   r   r9   r   rT   r   r   r   r   r   r   ZFALCON_START_DOCSTRINGr;  r   r   r>  rS  rZ  r]  r'   r'   r'   r(   <module>   s   
	I#   v 8W<I X mR