o
    Zh                 
   @   s  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 ddlmZm Z m!Z!m"Z"m#Z# ddl$m%Z%m&Z& ddl'm(Z( ddl)m*Z*m+Z+ ddl,m-Z- erddl.m/Z/ e rddlm0Z0 e+1e2Z3G dd de	j4Z5dd Z6dBddZ7G dd de	j8Z9dej:de;dej<d ej:fd!d"Z=d#ej:d$ej:d%e>d&e?d ej:f
d'd(Z@G d)d* d*e	j8ZAG d+d, d,eAZBG d-d. d.e	j8ZCeAeAeBd/ZDG d0d1 d1e	j8ZEe*G d2d3 d3e(ZFe*G d4d5 d5eFZGe*d6d7G d8d9 d9eFeZHe*d:d7G d;d< d<eFZIe*G d=d> d>eFZJe*G d?d@ d@eFZKg dAZLdS )CzPyTorch Falcon model.    N)TYPE_CHECKINGOptionalTupleUnion)nn)BCEWithLogitsLossCrossEntropyLoss	LayerNormMSELoss)
functional   )get_activation)CacheDynamicCacheStaticCache)GenerationMixin)AttentionMaskConverter)!flash_attn_supports_top_left_maskis_flash_attn_available))BaseModelOutputWithPastAndCrossAttentions!CausalLMOutputWithCrossAttentionsQuestionAnsweringModelOutput SequenceClassifierOutputWithPastTokenClassifierOutput)ROPE_INIT_FUNCTIONSdynamic_rope_update)PreTrainedModel)auto_docstringlogging   )FalconConfig)PretrainedConfig)_flash_attention_forwardc                   @   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,   Y/var/www/auris/lib/python3.10/site-packages/transformers/models/falcon/modeling_falcon.pyforward=   s   

zFalconLinear.forwardN)__name__
__module____qualname__torchTensorr.   r,   r,   r,   r-   r#   <   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)shaper2   cat)xx1Zx2r,   r,   r-   rotate_halfE   s   r<   c                 C   sD   | |}| |}| | t| |  }|| t||  }||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.
    )	unsqueezer<   )qkcossinposition_idsZunsqueeze_dimZq_embedZk_embedr,   r,   r-   apply_rotary_pos_embM   s
   

rC   c                       s8   e Zd Zddef fddZe edd Z  Z	S )FalconRotaryEmbeddingNconfigc                    s   t    t|dr|jd ur|jd|jd| _nd| _|j| _|j| _|| _	t
| j | _| | j	|\}| _| jd|dd | j| _d S )Nrope_scaling	rope_typetypedefaultinv_freqF)
persistent)super__init__hasattrrF   getrG   max_position_embeddingsZmax_seq_len_cachedZoriginal_max_seq_lenrE   r   Zrope_init_fnattention_scalingZregister_bufferrJ   Zoriginal_inv_freq)r*   rE   devicerJ   	__class__r,   r-   rM   j   s   
zFalconRotaryEmbedding.__init__c           
      C   s   | j d d d d f  |jd dd|j}|d d d d d f  }t|jjtr6|jjdkr6|jjnd}t	j
|dd+ | |  dd}t	j||fdd	}| | j }| | j }	W d    n1 smw   Y  |j|jd
|	j|jd
fS )Nr   r4   r   ZmpscpuF)device_typeenabledr5   r6   dtype)rJ   floatexpandr8   torR   
isinstancerH   strr2   Zautocast	transposer9   r@   rQ   rA   rY   )
r*   r:   rB   Zinv_freq_expandedZposition_ids_expandedrV   ZfreqsZembr@   rA   r,   r,   r-   r.   {   s   0&zFalconRotaryEmbedding.forwardr&   )
r/   r0   r1   r    rM   r2   Zno_gradr   r.   __classcell__r,   r,   rS   r-   rD   i   s
    rD   attention_mask	num_headsrY   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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 )	Nr5   r   rR   rY   r   r   r6   r4   ).N)r8   mathfloorlog2r2   ZtensorrR   float32arangeint32powminr9   Zcumsumbfloat16reshaper\   )ra   rb   rY   
batch_size
seq_lengthZclosest_power_of_2baseZpowersZslopesZ
extra_baseZnum_remaining_headsZextra_powersZarange_tensoralibir,   r,   r-   build_alibi_tensor   s"   
 $ &rr   r:   residualprobtrainingc                 C   s   t j| ||d}|| }|S )a
  
    Dropout add function

    Args:
        x (`torch.tensor`):
            input tensor
        residual (`torch.tensor`):
            residual tensor
        prob (`float`):
            dropout probability
        training (`bool`):
            training mode
    )pru   )Fdropout)r:   rs   rt   ru   outr,   r,   r-   dropout_add   s   rz   c                       s   e Zd Zddef f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 de
ej dedede
ej de
eejejf  fddZ  ZS )FalconAttentionNrE   c                    s  t    || _|j| _|j| _| j| j | _| j| _|j| _|j	| _	|j
| _
d| _|jdk| _|| _|d u rBtd| jj d | j| j | jkrXtd| j d| j ddt| j | _| j| _|jrt|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s| js|jnd| _|j"rt#| jd| _$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).      ?r5   r   r)   r   rE   )%rL   rM   rE   hidden_sizenum_attention_headsrb   head_dimZ
split_sizehidden_dropoutrP   Z
rope_theta	is_causal_attn_implementation	_use_sdpa	layer_idxloggerwarning_oncerT   r/   
ValueErrorrd   sqrtinv_norm_factorbetanew_decoder_architecturenum_kv_headsmulti_queryr#   r)   query_key_valuedenser   Dropoutattention_dropoutZrotaryrD   
rotary_emb)r*   rE   r   Zqkv_out_dimrS   r,   r-   rM      sL   


zFalconAttention.__init__	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`): [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]
        r4   r5   Nc                 S   s   g | ]}| d dqS )r5   r   )flatten).0r:   r,   r,   r-   
<listcomp>       z0FalconAttention._split_heads.<locals>.<listcomp>r   .r   r   )	r   r8   viewrb   r   r   r2   Zbroadcast_tor   )r*   r   batchZseq_len_Zqkvquerykeyvaluern   ro   Zthree_times_hidden_sizer,   r,   r-   _split_heads   s"     
4<zFalconAttention._split_headsr:   c                 C   sP   |j \}}}|| j }||| j|| j}|dddd}|||| j| j 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   r5   r   r   )r8   rb   r   r   permuterm   )r*   r:   Zbatch_size_and_num_headsro   r   rn   r,   r,   r-   _merge_heads  s
   
zFalconAttention._merge_headsFr+   rq   ra   rB   
layer_past	head_mask	use_cacheoutput_attentionscache_positionposition_embeddingsc                 C   s  |  |}| jr| jn| j}| |\}}}|j\}}}}|dd|| j|| j}|dd|||| j}|dd|||| j}|d u rV|
\}}t	||||\}}|d urud|	i}|d u rj|
||d |
||| j|\}}|jd }| jr|jjdkr|d ur| }| }| }|d ur|d d d d d d d |jd f }|d u r | jr|s| jr|d u r|dkrdnd}tjjj||||d	|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rj|sj|d u rj| jr<|d u r<|dkr<dnd}tjjj||||| jrN| jjnd	|d
}|dd}|||| j| j }| |}nj||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 ur|| }||| j||}|| %dd}| &|}| |}|r|||fS ||fS )Nr   r5   r   rA   r@   r   cudaTF        )Z	attn_maskZ	dropout_pr   r4   )r7   rY   r   r   )'r   r   rb   r   r   r8   r_   rm   r   rC   updater   r   rR   rH   
contiguousr   r2   r   r   Zscaled_dot_product_attentionrd   r   rw   ZsoftmaxrY   r   r   r   ru   r   rv   Zfloat16rl   r\   rg   r   r   r   )r*   r+   rq   ra   rB   r   r   r   r   r   r   r   r   query_layer	key_layervalue_layerrn   query_lengthr   r@   rA   cache_kwargsZ	kv_lengthr   attn_outputZattention_scoresZmatmul_resultinput_dtypeZattention_logitsZattention_probsZattention_probs_reshapedr,   r,   r-   r.   $  s   

&



$





zFalconAttention.forwardr&   NNNFFNN)r/   r0   r1   r    rM   r2   r3   r   r   r   r   
LongTensorr   boolr.   r`   r,   r,   rS   r-   r{      s@    $/ 	
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	 deej de
de
deej deeejejf  f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&   )rL   rM   r   _flash_attn_uses_top_left_mask)r*   argskwargsrS   r,   r-   rM     s   zFalconFlashAttention2.__init__NFr+   rq   ra   rB   r   r   r   r   r   r   c                 C   s  |  |}| jr| jn| j}| |\}}}|j\}}}}|dd|| j|| j}|dd|||| j}|dd|||| j}|d u rV|
\}}t	||||\}}|d urud|	i}|d u rj|
||d |
||| j|\}}|dd}|dd}|dd}|d urtd| jr| jjnd}|j}|tjkrt rt }nt| jdr| jj}n| j jj}td| d	 ||}||}||}t|||||||| j| jd
	}|||| j| j }| |}|sd }|||fS )Nr   r5   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 .)rB   rx   r   Zuse_top_left_mask)r   r   rb   r   r   r8   r_   rm   r   rC   r   r   r   ru   rE   r   rY   r2   rg   Zis_autocast_enabledZget_autocast_gpu_dtyperN   r   r'   r   r   r\   r"   r   r   r   )r*   r+   rq   ra   rB   r   r   r   r   r   r   r   r   r   r   r   rn   r   r   r@   rA   r   Zattn_dropoutr   Ztarget_dtyper   Zattn_weightsr,   r,   r-   r.     sh   









zFalconFlashAttention2.forwardr   )r/   r0   r1   __doc__rM   r2   r3   r   r   r   r   r   r.   r`   r,   r,   rS   r-   r     s>    	
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 )	FalconMLPrE   c                    sP   t    |j}t||j|jd| _t|j| _	t|j||jd| _
|j| _d S )Nr~   )rL   rM   r   r#   Zffn_hidden_sizer)   dense_h_to_4hr   Z
activationactdense_4h_to_hr   )r*   rE   r   rS   r,   r-   rM     s   
zFalconMLP.__init__r:   r%   c                 C   s   |  | |}| |}|S r&   )r   r   r   )r*   r:   r,   r,   r-   r.     s   
zFalconMLP.forward)	r/   r0   r1   r    rM   r2   r3   r.   r`   r,   r,   rS   r-   r     s    	r   )eagerr|   flash_attention_2c                       s   e Zd Zd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
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dZ  ZS )FalconDecoderLayerNrE   c                    s   t    |j}|j| _t|j ||| _t|| _	|j
| _
|| _|jd u r,|jr,d|_|jsAt||jd| _t||jd| _d S |jdkrXt||jd| _t||jd| _d S t||jd| _d S )Nr5   Zeps)rL   rM   r   r   rb   FALCON_ATTENTION_CLASSESr   self_attentionr   mlpr   rE   num_ln_in_parallel_attnr   parallel_attnr	   layer_norm_epsilonpost_attention_layernorminput_layernormln_attnln_mlp)r*   rE   r   r   rS   r,   r-   rM   +  s    


zFalconDecoderLayer.__init__Fr+   rq   ra   rB   r   r   r   r   r   r   c                 K   s   |}| j jr| j jdkr| |}| |}n| |}| j|||||||||	|
d
}|d }| j jsJ| j jr:|}nt||| j j	| j
d}| |}| j jrZ| j jrZ| j jdkrZ|}|dd  }| |}| j jsm| j jrq||7 }t||| j j| j
d}|r|f| }|S |f|dd   }|S )Nr5   )	r   ra   rB   rq   r   r   r   r   r   r   )ru   r   )rE   r   r   r   r   r   r   r   rz   r   ru   r   r   r   )r*   r+   rq   ra   rB   r   r   r   r   r   r   r   rs   Zattention_layernorm_outZmlp_layernorm_outZattn_outputsZattention_outputoutputsZ
mlp_outputoutputr,   r,   r-   r.   D  sR   




zFalconDecoderLayer.forwardr&   r   )r/   r0   r1   r    rM   r2   r3   r   r   r   r   r   r   r.   r`   r,   r,   rS   r-   r   *  s<    	
r   c                       sj   e Zd ZeZdZdZdgZdZdZ	d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 )FalconPreTrainedModeltransformerTr   c                    s   t  j|i | d S r&   )rL   rM   )r*   Zinputsr   rS   r,   r-   rM     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   )meanZstdNr}   )r]   r   Linearr#   r'   dataZnormal_rE   Zinitializer_ranger)   Zzero_	EmbeddingZpadding_idxr	   Zfill_)r*   r   r,   r,   r-   _init_weights  s   


z#FalconPreTrainedModel._init_weightsFhard_check_onlyr%   r!   c                 C   s"   t | dd}|r
|S |sd|_|S )NZuse_bettertransformerFr|   )getattrr   )clsrE   r   Z_is_bettertransformerr,   r,   r-   _check_and_enable_sdpa  s   z,FalconPreTrainedModel._check_and_enable_sdpa)F)r/   r0   r1   r    Zconfig_classZbase_model_prefixZsupports_gradient_checkpointingZ_no_split_modulesZ_supports_flash_attn_2Z_supports_sdpaZ_supports_cache_classZ_supports_quantized_cacheZ_supports_static_cacherM   r   Moduler   classmethodr   r   r`   r,   r,   rS   r-   r     s    r   c                       sR  e Zd Zdef fddZdd ZdejfddZ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dZdejdejdejdededejdejfddZedejdededejdejd efd!d"Z  ZS )$FalconModelrE   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| _t d| _d| _|   d S )Nc                    s   g | ]}t  |d qS ))r   )r   )r   ir   r,   r-   r     r   z(FalconModel.__init__.<locals>.<listcomp>r   r|   r   r   F)rL   rM   r   Z	embed_dimr   rb   rq   	use_alibir   r   
vocab_sizeword_embeddingsZ
ModuleListrangenum_hidden_layershr   Z_use_flash_attention_2r   r	   r   ln_frD   r   gradient_checkpointing	post_initr*   rE   rS   r   r-   rM     s    zFalconModel.__init__c                 C      | j S r&   r   r*   r,   r,   r-   get_input_embeddings     z FalconModel.get_input_embeddingsnew_embeddingsc                 C   
   || _ d S r&   r   r*   r   r,   r,   r-   set_input_embeddings     
z FalconModel.set_input_embeddingsN	input_idspast_key_values.ra   rB   r   inputs_embedsr   r   output_hidden_statesreturn_dictr   r%   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 |duA r4td| jrC| jrC|rCt	d d}|du rL| 
|}d}|rit|tsid}|du r_t }n
t|}t	d d}|durs| nd}|j\}}}| jr|du rtj||| f|jtjdn|}t|| j|jd	}|du rtj||| |jd
}|du r|d}| |||||||}| || j j}|}| ||}d}|rdnd}|	rdnd}t| j D ]R\}}|	r||f }| jr| jr| !|j"|||||| |||||}n||||||| |||||d
}|d }|du r$|d }|r3|||r.dnd f }q| #|}|	rA||f }|rF|nd}|rO|$ }|
s_t%dd ||||fD S t&||||dS )  
        input_ids (`torch.LongTensor` of shape `(batch_size, input_ids_length)`):
            `input_ids_length` = `sequence_length` if `past_key_values` is `None` else `past_key_values[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)
        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   rc   rX   rR   r,   )	r   ra   rB   r   r   r   rq   r   r   r   r5   c                 s   s    | ]	}|d ur|V  qd S r&   r,   )r   vr,   r,   r-   	<genexpr>p  s    z&FalconModel.forward.<locals>.<genexpr>)Zlast_hidden_stater   r+   
attentions)'rE   r   r   r   use_return_dictr   r   ru   r   r   r   r]   r   r   Zfrom_legacy_cacheget_seq_lengthr8   r   r2   ZonesrR   longrr   rb   rY   rh   r=   _update_causal_maskZget_head_maskr   r   	enumerater   Z_gradient_checkpointing_func__call__r   Zto_legacy_cachetupler   )r*   r   r   ra   rB   r   r   r   r   r   r   r   Zreturn_legacy_cacherq   past_key_values_lengthrn   ro   r   maskcausal_maskr+   r   Znext_decoder_cacheZall_self_attentionsZall_hidden_statesr   blockr   Z
next_cacher,   r,   r-   r.     s   







zFalconModel.forwardinput_tensorrq   c              	   C   sv  | j jdkr|d urd|v r|S d S |d ur| nd}t|t}	| j jdkr?|	s?|s?|d u r?|d u r?tj|||| jdr?d S |j|j	}
}t
|
j}|j\}}}|	rY| }nt|t
jrd|jd n|| }| j||||
|||jd d}|d u r|d ur|j|dg|jdd  R  }t
|t| j j| j  |dk |}| j jdkr|d ur|j	jd	v r|st||}|S )
Nr   r   r   r|   )r   r
  Zis_trainingr4   )sequence_lengthtarget_lengthrY   rR   r   rn   r   )r   ZxpuZnpu)rE   r   r  r]   r   r   Z_ignore_causal_mask_sdparu   rY   rR   r2   finfork   r8   Zget_max_cache_shaper3   5_prepare_4d_causal_attention_mask_with_cache_positionrm   masked_fillrd   r   r   rb   rH   Z_unmask_unattended)r*   ra   r  r   r   r   r   rq   Zpast_seen_tokensZusing_static_cacherY   rR   	min_dtypern   r  r   r  r  r,   r,   r-   r  {  sh   


zFalconModel._update_causal_maskr  r  rY   rn   c                 K   sD  | dur|   dkr| }|S t|j}tj||f|||jd}|dkr+tj|dd}|tj||jd|ddk9 }|ddddddf 	|ddd}| dur|
 }| jd }	|ddddddd|	f | ddddddf |j }
|
dk}
|ddddddd|	f |
||ddddddd|	f< |S )	aM  
        Creates a causal 4D mask of shape `(batch_size, 1, query_length, key_value_length)` from a 2D mask of shape
        `(batch_size, key_value_length)`, or if the input `attention_mask` is already 4D, do nothing.

        Args:
            attention_mask (`torch.Tensor`):
                A 2D attention mask of shape `(batch_size, key_value_length)` or a 4D attention mask of shape
                `(batch_size, 1, query_length, key_value_length)`.
            sequence_length (`int`):
                The sequence length being processed.
            target_length (`int`):
                The target length: when generating with static cache, the mask should be as long as the static cache,
                to account for the 0 padding, the part of the cache that is not filled yet.
            dtype (`torch.dtype`):
                The dtype to use for the 4D attention mask.
            cache_position (`torch.Tensor`):
                Indices depicting the position of the input sequence tokens in the sequence.
            batch_size (`torch.Tensor`):
                Batch size.
        N   )Z
fill_valuerY   rR   r   )Zdiagonalr   r4   r   )r7   r2   r  rk   fullrR   Ztriurh   rm   r[   cloner8   r\   r  )ra   r  r  rY   r   rn   r   r  r  Zmask_lengthZpadding_maskr,   r,   r-   r    s,    $
6  zAFalconModel._prepare_4d_causal_attention_mask_with_cache_position)NNNNNNNNNNN)r/   r0   r1   r    rM   r   r2   r3   r   r   r   r   r   r   r   r   r   r.   r  staticmethodintrY   r  r`   r,   r,   rS   r-   r     s    "	
 #
Wr   z
    The Falcon Model transformer with a language modeling head on top (linear layer with weights tied to the input embeddings).
    )Zcustom_introc                        sT  e Zd ZdgZdef fddZdd Zdejfdd	Z	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f 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.weightrE   c                    s8   t  | t|| _tj|j|jdd| _| 	  d S NFr~   )
rL   rM   r   r   r   r   r   r   lm_headr   r   rS   r,   r-   rM     s   
zFalconForCausalLM.__init__c                 C   r   r&   r  r   r,   r,   r-   get_output_embeddings  r   z'FalconForCausalLM.get_output_embeddingsr   c                 C   r   r&   r  r   r,   r,   r-   set_output_embeddings  r   z'FalconForCausalLM.set_output_embeddingsNr   r   r   .ra   rB   r   r   labelsr   r   r   r   r   logits_to_keepr%   c                 K   s   |dur|n| j j}| j||||||||	|
||d}|d }t|tr)t| dn|}| |dd|ddf }d}|durM| j||fd| j ji|}|sc|f|dd  }|dura|f| S |S t	|||j
|j|jdS )aZ  
        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)
        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   ra   rB   r   r   r   r   r   r   r   r   r   r   losslogitsr   r+   r  )rE   r  r   r]   r  slicer  Zloss_functionr   r   r   r+   r  )r*   r   r   ra   rB   r   r   r   r   r   r   r   r   r!  r   transformer_outputsr+   Zslice_indicesZ	lm_logitsr#  r   r,   r,   r-   r.   !  sJ   $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,   )rR   r\   )r   r   Z
past_state)r(  r,   r-   
<dictcomp>z  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)Zindex_selectrR   )r   r   )device_to_beam_idxr,   r-   r  }  s    
z3FalconForCausalLM._reorder_cache.<locals>.<genexpr>)r	  )r*   r'  r(  Zreordered_pastr,   )r(  r*  r-   _reorder_cachen  s   
z FalconForCausalLM._reorder_cache)NNNNNNNNNNNNr   )r/   r0   r1   Z_tied_weights_keysr    rM   r  r2   r3   r  r   r   r   r   r   r   r   r  r   r.   r+  r`   r,   r,   rS   r-   r    sn    "	
L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										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 )FalconForSequenceClassificationrE   c                    s@   t  | |j| _t|| _tj|j|jdd| _| 	  d S r  )
rL   rM   
num_labelsr   r   r   r   r   scorer   r   rS   r,   r-   rM     s
   
z(FalconForSequenceClassification.__init__Nr   r   .ra   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}n1|durl|| j jk|jt	j
}t	j|jd |jt	j
d}|| d}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 )4  
        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)
        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   ra   r   r   r   r   r   r   r   r   z=Cannot handle batch sizes > 1 if no padding token is defined.r4   rc   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_classificationr"  )rE   r  r   r/  r8   Zpad_token_idr   r\   rR   r2   ri   rh   Zargmaxr   r   rT   r/   Zproblem_typer.  rY   r  r  r
   squeezer   r   r   r   r+   r  )r*   r   r   ra   r   r   r   r   r   r   r   r&  r+   r$  rn   Zlast_non_pad_tokenZnon_pad_maskZtoken_indicesZpooled_logitsr#  loss_fctr   r,   r,   r-   r.     sv    



"


z'FalconForSequenceClassification.forward
NNNNNNNNNN)r/   r0   r1   r    rM   r   r   r2   r   r   r3   r   r   r   r.   r`   r,   r,   rS   r-   r-    sH    		
r-  c                       r,  )FalconForTokenClassificationrE   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?)rL   rM   r.  r   r   r   r6  r   r   r   rx   r   r   
classifierr   )r*   rE   r6  rS   r,   r-   rM     s   
z%FalconForTokenClassification.__init__Nr   r   .ra   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 )r0  Nr1  r   r5   )r#  r$  r+   r  )rE   r  r   rx   r7  r8   r   r   r.  r   r+   r  )r*   r   r   ra   r   r   r   r   r   r   r   r&  r+   r$  r#  rn   ro   r3  r   r,   r,   r-   r.     s>    


z$FalconForTokenClassification.forwardr4  )r/   r0   r1   r    rM   r   r   r2   r   r   r3   r   r   r   r.   r`   r,   r,   rS   r-   r5  
  sH    	
r5  c                       s   e Zd Z fddZ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 )Nr5   )	rL   rM   r   r   r   r   r   
qa_outputsr   r   rS   r,   r-   rM   e  s   
z#FalconForQuestionAnswering.__init__Nr   ra   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 )
r   N)ra   r   r   r   r   r   r   r   r4   r6   )Zignore_indexr5   )r#  start_logits
end_logitsr+   r  )rE   r  r   r9  splitr2  r   lensizeclampr   r   r+   r  )r*   r   ra   r   r   r:  r;  r   r   r   r   Zsequence_outputr$  r<  r=  Z
total_lossZignored_indexr3  Z
start_lossZend_lossr   r,   r,   r-   r.   m  sL   







z"FalconForQuestionAnswering.forward)	NNNNNNNNN)r/   r0   r1   rM   r   r   r2   r   ZFloatTensorr   r   r   r   r.   r`   r,   r,   rS   r-   r8  c  sB    	

r8  )r  r   r   r-  r5  r8  )Nr   )Mr   rd   typingr   r   r   r   r2   Ztorch.utils.checkpointr   Ztorch.nnr   r   r	   r
   r   rw   Zactivationsr   Zcache_utilsr   r   r   Z
generationr   Zmodeling_attn_mask_utilsr   Zmodeling_flash_attention_utilsr   r   Zmodeling_outputsr   r   r   r   r   Zmodeling_rope_utilsr   r   Zmodeling_utilsr   utilsr   r   Zconfiguration_falconr    Zconfiguration_utilsr!   r"   Z
get_loggerr/   r   r   r#   r<   rC   r   rD   r3   r  rY   rr   rZ   r   rz   r{   r   r   r   r   r   r   r  r-  r5  r8  __all__r,   r,   r,   r-   <module>   sr   
	
 "$ qhb*  UwuXT