o
    i                  
   @   st  d Z ddlZddlmZmZ ddlZddlmZ ddlmZm	Z	m
Z
mZ ddlmZ ddlmZ dd	lmZmZmZ dd
lmZ ddlmZ ddlmZmZ ddlmZ ddlmZmZm Z m!Z!m"Z" ddl#m$Z$m%Z% ddl&m'Z' ddl(m)Z)m*Z* ddl+m,Z, e rddlm-Z- e*.e/Z0G dd dej1Z2dd Z3dBddZ4G dd dej5Z6dej7de8dej9d ej7fd!d"Z:d#ej7d$ej7d%e;d&e<d ej7f
d'd(Z=G d)d* d*ej5Z>G d+d, d,e>Z?G d-d. d.ej5Z@e>e>e?d/ZAG d0d1 d1eZBe)G d2d3 d3e'ZCe)G d4d5 d5eCZDe)d6d7G d8d9 d9eCeZEe)d:d7G d;d< d<eCZFe)G d=d> d>eCZGe)G d?d@ d@eCZHg dAZIdS )CzPyTorch Falcon model.    N)OptionalUnion)nn)BCEWithLogitsLossCrossEntropyLoss	LayerNormMSELoss)
functional   )get_activation)CacheDynamicCacheStaticCache)GenerationMixin)AttentionMaskConverter)!flash_attn_supports_top_left_maskis_flash_attn_available)GradientCheckpointingLayer))BaseModelOutputWithPastAndCrossAttentions!CausalLMOutputWithCrossAttentionsQuestionAnsweringModelOutput SequenceClassifierOutputWithPastTokenClassifierOutput)ROPE_INIT_FUNCTIONSdynamic_rope_update)PreTrainedModel)auto_docstringlogging   )FalconConfig)_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*   ^/home/ubuntu/.local/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!   9   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)shaper0   cat)xx1x2r*   r*   r+   rotate_halfB   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_idsunsqueeze_dimq_embedk_embedr*   r*   r+   apply_rotary_pos_embJ   s
   

rE   c                       sD   e Zd ZU ejed< ddef fddZe e	dd Z
  ZS )	FalconRotaryEmbeddinginv_freqNconfigc                    s   t    t|drt|jt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defaultrG   F)
persistent)super__init__hasattr
isinstancerI   dictgetrJ   max_position_embeddingsmax_seq_len_cachedoriginal_max_seq_lenrH   r   rope_init_fnattention_scalingregister_bufferrG   original_inv_freq)r(   rH   devicerG   	__class__r*   r+   rO   i   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   r2   r   mpscpuF)device_typeenabledr3   r4   dtype)rG   floatexpandr6   tor[   rQ   rK   strr0   autocast	transposer7   r?   rX   r@   rc   )
r(   r8   rA   inv_freq_expandedposition_ids_expandedr`   freqsembr?   r@   r*   r*   r+   r,   z   s   0&zFalconRotaryEmbedding.forwardr$   )r-   r.   r/   r0   r1   __annotations__r   rO   no_gradr   r,   __classcell__r*   r*   r\   r+   rF   f   s   
 
rF   attention_mask	num_headsrc   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 )	Nr3   r
   r[   rc   r   r   r4   r2   ).N)r6   mathfloorlog2r0   tensorr[   float32arangeint32powminr7   cumsumbfloat16reshaperf   )rq   rr   rc   
batch_size
seq_lengthclosest_power_of_2basepowersslopes
extra_basenum_remaining_headsextra_powersarange_tensoralibir*   r*   r+   build_alibi_tensor   s"   
 $ &r   r8   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
    )pr   )Fdropout)r8   r   r   r   outr*   r*   r+   dropout_add   s   r   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 )FalconAttentionNrH   c                    sh  t    || _|j| _|j| _| j| j | _| j| _|j| _|j	| _	|j
| _
d| _|| _|d u r<td| jj d | j| j | jkrRtd| j d| j ddt| j | _| j| _|jrn|jd |j | j }n|jrz| 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 )NTzInstantiating z without passing a `layer_idx` is not recommended and will lead to errors during the forward call if caching is used. Please make sure to provide a `layer_idx` when creating this class.zA`hidden_size` must be divisible by num_heads (got `hidden_size`: z and `num_heads`: z).      ?r3   r
   r'   r   ) rN   rO   rH   hidden_sizenum_attention_headsrr   head_dim
split_sizehidden_dropoutrT   
rope_theta	is_causal	layer_idxloggerwarning_oncer]   r-   
ValueErrorrt   sqrtinv_norm_factorbetanew_decoder_architecturenum_kv_headsmulti_queryr!   r'   query_key_valuedenser   Dropoutattention_dropout)r(   rH   r   qkv_out_dimr\   r*   r+   rO      sD   


"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]
        r2   r3   Nc                 S   s   g | ]}| d dqS )r3   r
   )flatten).0r8   r*   r*   r+   
<listcomp>       z0FalconAttention._split_heads.<locals>.<listcomp>r
   .r   r   )	r   r6   viewrr   r   r   r0   broadcast_tor   )r(   r   batchseq_len_qkvquerykeyvaluer   r   three_times_hidden_sizer*   r*   r+   _split_heads   s"     
4<zFalconAttention._split_headsr8   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   r3   r   r
   )r6   rr   r   r   permuter   )r(   r8   batch_size_and_num_headsr   r   r   r*   r*   r+   _merge_heads  s
   
zFalconAttention._merge_headsFr)   r   rq   rA   
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jdk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jdkr|s| jo|d u o|dk}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 }| |}||fS | jjdkrg|sg|d u rg| jo5|d u o5|dk}tjjj||||| jrF| jj nd|d	}d }|dd}|||| j| j }| |}||fS ||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}| '|}| |}||fS )Nr   r3   r   r@   r?   r   sdpacuda        )	attn_mask	dropout_pr   r2   )r5   rc   r   r
   )(r   r   rr   r   r   r6   ri   r   r   rE   updater   rH   _attn_implementationr[   rK   
contiguousr   r0   r   r	   scaled_dot_product_attentionrt   r   r   softmaxrc   r   r   r   r   r   r   float16r~   rf   rx   r   r   r   )r(   r)   r   rq   rA   r   r   r   r   r   r   r   r   query_layer	key_layervalue_layerr   query_lengthr   r?   r@   cache_kwargs	kv_lengthr   attn_outputattention_scoresattention_probsmatmul_resultinput_dtypeattention_logitsattention_probs_reshapedr*   r*   r+   r,     s   

&


!




zFalconAttention.forwardr$   NNNFFNN)r-   r.   r/   r   rO   r0   r1   tupler   r   r   
LongTensorr   boolr,   rp   r*   r*   r\   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$   )rN   rO   r   _flash_attn_uses_top_left_mask)r(   argskwargsr\   r*   r+   rO     s   zFalconFlashAttention2.__init__NFr)   r   rq   rA   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}|jjdkr|jjnd}|tjkrt rttd	rt|nt }nt| jd
r| jj}n| j jj}td| d ||}||}||}t|||||||| j| j d	}|||| j| j }| !|}|sd }||fS )Nr   r3   r   r   z6`alibi` is not supported when `use_flash_attn` is Truer   r^   r_   get_autocast_dtype_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 .)rA   r   r   use_top_left_mask)"r   r   rr   r   r   r6   ri   r   r   rE   r   r   r   r   rH   r   rc   r[   rK   r0   rx   is_autocast_enabledrP   r   get_autocast_gpu_dtyper   r%   r   r   rf   r    r   r   r   )r(   r)   r   rq   rA   r   r   r   r   r   r   r   r   r   r   r   r   r   r   r?   r@   r   attn_dropoutr   r`   target_dtyper   attn_weightsr*   r*   r+   r,     sp   







zFalconFlashAttention2.forwardr   )r-   r.   r/   __doc__rO   r0   r1   r   r   r   r   r   r,   rp   r*   r*   r\   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 )	FalconMLPrH   c                    sP   t    |j}t||j|jd| _t|j| _	t|j||jd| _
|j| _d S )Nr   )rN   rO   r   r!   ffn_hidden_sizer'   dense_h_to_4hr   
activationactdense_4h_to_hr   )r(   rH   r   r\   r*   r+   rO     s   
zFalconMLP.__init__r8   r#   c                 C   s   |  | |}| |}|S r$   )r   r   r   )r(   r8   r*   r*   r+   r,     s   
zFalconMLP.forward)	r-   r.   r/   r   rO   r0   r1   r,   rp   r*   r*   r\   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 )FalconDecoderLayerNrH   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 )Nr3   eps)rN   rO   r   r   rr   FALCON_ATTENTION_CLASSESr   self_attentionr   mlpr   rH   num_ln_in_parallel_attnr   parallel_attnr   layer_norm_epsilonpost_attention_layernorminput_layernormln_attnln_mlp)r(   rH   r   r   r\   r*   r+   rO   )  s    


zFalconDecoderLayer.__init__Fr)   r   rq   rA   r   r   r   r   r   r   c                 K   s   |}| j jr| j jdkr| |}| |}n| |}| j|||||||||	|
d
\}}| j jsH| j jr8|}nt||| j j	| j
d}| |}| j jrX| j jrX| j jdkrX|}| |}| j jse| j jri||7 }t||| j j| j
d}||fS )Nr3   )	r   rq   rA   r   r   r   r   r   r   )r   r   )rH   r   r   r  r  r  r   r  r   r   r   r  r   r   )r(   r)   r   rq   rA   r   r   r   r   r   r   r   r   attention_layernorm_outmlp_layernorm_outattention_outputr   
mlp_outputoutputr*   r*   r+   r,   B  sF   




zFalconDecoderLayer.forwardr$   r   )r-   r.   r/   r   rO   r0   r1   r   r   r   r   r   r   r,   rp   r*   r*   r\   r+   r   (  s<    	
r   c                       sd   e Zd ZU eed< dZdZdgZdZdZ	dZ
 fddZdejfdd	ZeddefddZ  ZS )FalconPreTrainedModelrH   transformerTr   c                    s   t  j|i | d S r$   )rN   rO   )r(   inputsr   r\   r*   r+   rO     s   zFalconPreTrainedModel.__init__modulec                 C   s   t |tjtfr"|jjjd| jjd |j	dur |j	j
  dS dS t |tjrE|jjjd| jjd |jdurC|jj|j 
  dS dS t |trY|j	j
  |jjd dS dS )zInitialize the weights.r   )meanstdNr   )rQ   r   Linearr!   r%   datanormal_rH   initializer_ranger'   zero_	Embeddingpadding_idxr   fill_)r(   r  r*   r*   r+   _init_weights  s   


z#FalconPreTrainedModel._init_weightsFhard_check_onlyc                 C   s"   t | dd}|r
|S |sd|_|S )Nuse_bettertransformerFr   )getattrr   )clsrH   r  _is_bettertransformerr*   r*   r+   _check_and_enable_sdpa  s   z,FalconPreTrainedModel._check_and_enable_sdpa)F)r-   r.   r/   r   rn   base_model_prefixsupports_gradient_checkpointing_no_split_modules_supports_flash_attn_supports_sdpa_can_compile_fullgraphrO   r   Moduler  classmethodr   r   rp   r*   r*   r\   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 )$FalconModelrH   c                    s   t     j| _ j| _ j| _t	 j
| j| _t fddt jD | _t| j jd| _t d| _d| _|   d S )Nc                    s   g | ]}t  |d qS ))r   )r   )r   irH   r*   r+   r     r   z(FalconModel.__init__.<locals>.<listcomp>r   r+  F)rN   rO   r   	embed_dimr   rr   r   	use_alibir   r  
vocab_sizeword_embeddings
ModuleListrangenum_hidden_layershr   r  ln_frF   
rotary_embgradient_checkpointing	post_initr(   rH   r\   r+  r+   rO     s    zFalconModel.__init__c                 C   s   | j S r$   r/  )r(   r*   r*   r+   get_input_embeddings  s   z FalconModel.get_input_embeddingsnew_embeddingsc                 C   
   || _ d S r$   r9  r(   r;  r*   r*   r+   set_input_embeddings     
z FalconModel.set_input_embeddingsN	input_idspast_key_values.rq   rA   r   inputs_embedsr   r   output_hidden_statesreturn_dictr   r#   c                 C   s8  |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| 
|}|rX|du rXt| j d}d}|durb| nd}|j\}}}| jr|du rtj||| f|jtjdn|}t|| j|jd}|du rtj||| |jd	}|du r|d}| |||||||}| || j j}|}| ||}|rd
nd}|	rd
nd}t| jD ](\}}|	r||f }||||||| |||||d
}|d }|r||d f }q| |}|	r||f }|
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.get_seq_length()`
            (`sequence_length` of input past key value states). Indices of input sequence tokens in the vocabulary.

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

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

            [What are input IDs?](../glossary#input-ids)
        Nz:You must specify exactly one of input_ids or inputs_embedszZ`use_cache=True` is incompatible with gradient checkpointing. Setting `use_cache=False`...Fr+  r   rs   rb   r[   r*   )	r   rq   rA   r   r   r   r   r   r   r   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_staterA  r)   
attentions)!rH   r   rC  r   use_return_dictr   r6  r   r   r   r/  r   get_seq_lengthr6   r-  r0   onesr[   longr   rr   rc   ry   r<   _update_causal_maskget_head_maskr2  r5  	enumerater3  r4  r   r   )r(   r@  rA  rq   rA   r   rB  r   r   rC  rD  r   r   past_key_values_lengthr   r   r   maskcausal_maskr)   r   all_self_attentionsall_hidden_statesr*  blockoutputsr*   r*   r+   r,     s   





zFalconModel.forwardinput_tensorr   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   )rB  rR  is_trainingr2   )sequence_lengthtarget_lengthrc   r[   r   r   r   )r   xpunpu)rH   r   rL  rQ   r   r   _ignore_causal_mask_sdpar   rc   r[   r0   finfor|   r6   get_max_cache_shaper1   5_prepare_4d_causal_attention_mask_with_cache_positionr   masked_fillrt   r   r   rr   rK   _unmask_unattended)r(   rq   rY  r   rA  r   r   r   past_seen_tokensusing_static_cacherc   r[   	min_dtyper   r[  r   r\  rT  r*   r*   r+   rO  K  sh   


zFalconModel._update_causal_maskr[  r\  rc   r   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   )
fill_valuerc   r[   r   )diagonalrF  r2   r   )r5   r0   r`  r|   fullr[   triury   r   re   cloner6   rf   rc  )rq   r[  r\  rc   r   r   r   rT  rg  mask_lengthpadding_maskr*   r*   r+   rb    s,    $
6  zAFalconModel._prepare_4d_causal_attention_mask_with_cache_position)NNNNNNNNNNN)r-   r.   r/   r   rO   r:  r0   r1   r>  r   r   r   r   r   r   r   r   r,   rO  staticmethodintrc   rb  rp   r*   r*   r\   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).
    )custom_introc                        s  e Zd ZdgZdef f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  ZS )FalconForCausalLMzlm_head.weightrH   c                    s8   t  | t|| _tj|j|jdd| _| 	  d S NFr   )
rN   rO   r)  r  r   r  r   r.  lm_headr7  r8  r\   r*   r+   rO     s   
zFalconForCausalLM.__init__r;  c                 C   r<  r$   )ru  r=  r*   r*   r+   set_output_embeddings  r?  z'FalconForCausalLM.set_output_embeddingsNr   r@  rA  .rq   rA   r   rB  labelsr   r   rC  rD  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 )a\  
        input_ids (`torch.LongTensor` of shape `(batch_size, input_ids_length)`):
            `input_ids_length` = `sequence_length` if `past_key_values` is `None` else `past_key_values.get_seq_length()`
            (`sequence_length` of input past key value states). Indices of input sequence tokens in the vocabulary.

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

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

            [What are input IDs?](../glossary#input-ids)
        labels (`torch.LongTensor` of shape `(batch_size, sequence_length)`, *optional*):
            Labels for language modeling. Note that the labels **are shifted** inside the model, i.e. you can set
            `labels = input_ids` Indices are selected in `[-100, 0, ..., config.vocab_size]` All labels set to `-100`
            are ignored (masked), the loss is only computed for labels in `[0, ..., config.vocab_size]`
        N)
rA  rq   rA   r   rB  r   r   rC  rD  r   r   r.  r   losslogitsrA  r)   rJ  )rH   rK  r  rQ   rq  sliceru  loss_functionr.  r   rA  r)   rJ  )r(   r@  rA  rq   rA   r   rB  rw  r   r   rC  rD  r   rx  r   transformer_outputsr)   slice_indices	lm_logitsrz  r  r*   r*   r+   r,     sJ   $zFalconForCausalLM.forward)NNNNNNNNNNNNr   )r-   r.   r/   _tied_weights_keysr   rO   r0   r1   rv  r   r   r   r   r   r   r   rq  r   r,   rp   r*   r*   r\   r+   rs    s^    "	
rs  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	 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 )FalconForSequenceClassificationrH   c                    s@   t  | |j| _t|| _tj|j|jdd| _| 	  d S rt  )
rN   rO   
num_labelsr)  r  r   r  r   scorer7  r8  r\   r*   r+   rO   K  s
   
z(FalconForSequenceClassification.__init__Nr@  rA  rq   r   rB  rw  r   r   rC  rD  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 )6  
        input_ids (`torch.LongTensor` of shape `(batch_size, input_ids_length)`):
            `input_ids_length` = `sequence_length` if `past_key_values` is `None` else `past_key_values.get_seq_length()`
            (`sequence_length` of input past key value states). Indices of input sequence tokens in the vocabulary.

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

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

            [What are input IDs?](../glossary#input-ids)
        labels (`torch.LongTensor` of shape `(batch_size,)`, *optional*):
            Labels for computing the sequence classification/regression loss. Indices should be in `[0, ...,
            config.num_labels - 1]`. If `config.num_labels == 1` a regression loss is computed (Mean-Square loss), If
            `config.num_labels > 1` a classification loss is computed (Cross-Entropy).
        NrA  rq   r   rB  r   r   rC  rD  r   r   z=Cannot handle batch sizes > 1 if no padding token is defined.r2   rs   z will not detect padding tokens in `inputs_embeds`. Results may be unexpected if using padding tokens in conjunction with `inputs_embeds.`rF  
regressionsingle_label_classificationmulti_label_classificationry  )rH   rK  r  r  r6   pad_token_idr   rf   r[   r0   rz   ry   argmaxr   r   r]   r-   problem_typer  rc   rN  rq  r   squeezer   r   r   rA  r)   rJ  )r(   r@  rA  rq   r   rB  rw  r   r   rC  rD  r~  r)   r{  r   last_non_pad_tokennon_pad_masktoken_indicespooled_logitsrz  loss_fctr  r*   r*   r+   r,   T  sv    



"


z'FalconForSequenceClassification.forward
NNNNNNNNNN)r-   r.   r/   r   rO   r   r   r0   r   r   r1   r   r   r   r   r,   rp   r*   r*   r\   r+   r  <  sH    		
r  c                       r  )FalconForTokenClassificationrH   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?)rN   rO   r  r)  r  r  r  r   r   r   r   r  r   
classifierr7  )r(   rH   r  r\   r*   r+   rO     s   
z%FalconForTokenClassification.__init__Nr@  rA  rq   r   rB  rw  r   r   rC  rD  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   r3   )rz  r{  r)   rJ  )rH   rK  r  r   r  r6   r   r   r  r   r)   rJ  )r(   r@  rA  rq   r   rB  rw  r   r   rC  rD  r~  r)   r{  rz  r   r   r  r  r*   r*   r+   r,     s>    


z$FalconForTokenClassification.forwardr  )r-   r.   r/   r   rO   r   r   r0   r   r   r1   r   r   r   r   r,   rp   r*   r*   r\   r+   r    sH    	
r  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 )Nr3   )	rN   rO   r)  r  r   r  r   
qa_outputsr7  r8  r\   r*   r+   rO     s   
z#FalconForQuestionAnswering.__init__Nr@  rq   r   rB  start_positionsend_positionsr   rC  rD  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 )
rE  N)rq   r   rB  r   rC  rD  r   r   r2   r4   )ignore_indexr3   )rz  start_logits
end_logitsr)   rJ  )rH   rK  r  r  splitr  r   lensizeclampr   r   r)   rJ  )r(   r@  rq   r   rB  r  r  r   rC  rD  rX  sequence_outputr{  r  r  
total_lossignored_indexr  
start_lossend_lossr  r*   r*   r+   r,   "  sL   







z"FalconForQuestionAnswering.forward)	NNNNNNNNN)r-   r.   r/   rO   r   r   r0   r   FloatTensorr   r   r   r   r,   rp   r*   r*   r\   r+   r    sB    	

r  )rs  r)  r  r  r  r  )Nr   )Jr   rt   typingr   r   r0   r   torch.nnr   r   r   r   r	   r   activationsr   cache_utilsr   r   r   
generationr   modeling_attn_mask_utilsr   modeling_flash_attention_utilsr   r   modeling_layersr   modeling_outputsr   r   r   r   r   modeling_rope_utilsr   r   modeling_utilsr   utilsr   r   configuration_falconr   r    
get_loggerr-   r   r  r!   r;   rE   r'  rF   r1   rq  rc   r   rd   r   r   r   r   r   r   r   r  r)  rs  r  r  r  __all__r*   r*   r*   r+   <module>   sn   
	
 $$ kmY)  1\uXT