o
    ei                  
   @   s  d Z ddlZddlmZ ddl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 ddl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/ ddl0m1Z1 e rddlm2Z2 e-3e4Z5G dd dej6Z7dd Z8dEddZ9G dd dej:Z;d ej<d!e=d"ej>d#ej<fd$d%Z?d&ej<d'ej<d(e@d)eAd#ej<f
d*d+ZBG d,d- d-ej:ZCG d.d/ d/eCZDG d0d1 d1ej:ZEeCeCeDd2ZFG d3d4 d4eZGe,G d5d6 d6e*ZHe,G d7d8 d8eHZIe,d9d:G d;d< d<eHeZJe,d=d:G d>d? d?eHZKe,G d@dA dAeHZLe,G dBdC dCeHZMg dDZNdS )FzPyTorch Falcon model.    N)Callable)Optional)nn)BCEWithLogitsLossCrossEntropyLoss	LayerNormMSELoss)
functional   )initialization)get_activation)CacheDynamicCache)GenerationMixin)create_causal_mask)!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)maybe_autocast   )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+   h/home/ubuntu/transcripts/venv/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)shaper1   cat)xx1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.
        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unsqueeze_dimq_embedk_embedr+   r+   r,   apply_rotary_pos_embM   s
   

rE   c                       s~   e Zd ZU ejed< ddef fddZe			ddedB de	d de
dB d	ed
ef fddZe edd Z  ZS )FalconRotaryEmbeddinginv_freqNconfigc                    s   t    |j| _|j| _|| _| jjd | _| j}| jdkr$t	| j }|| j|\}| _
| jd|dd | jd| dd d S )N	rope_typedefaultrG   F)
persistentoriginal_inv_freq)super__init__max_position_embeddingsmax_seq_len_cachedoriginal_max_seq_lenrH   rope_parametersrI   compute_default_rope_parametersr   attention_scalingregister_bufferclone)r)   rH   devicerope_init_fnrG   	__class__r+   r,   rN   j   s   


zFalconRotaryEmbedding.__init__rW   ztorch.deviceseq_lenr$   ztorch.Tensorc                 C   sZ   | j d }t| ddp| j| j }d}d|tjd|dtjdj|tjd|   }||fS )	a  
        Computes the inverse frequencies according to the original RoPE implementation
        Args:
            config ([`~transformers.PreTrainedConfig`]):
                The model configuration.
            device (`torch.device`):
                The device to use for initialization of the inverse frequencies.
            seq_len (`int`, *optional*):
                The current sequence length. Unused for this type of RoPE.
        Returns:
            Tuple of (`torch.Tensor`, `float`), containing the inverse frequencies for the RoPE embeddings and the
            post-processing scaling factor applied to the computed cos/sin (unused in this type of RoPE).
        
rope_thetahead_dimN      ?r   r4   dtyperW   r`   )	rR   getattrhidden_sizenum_attention_headsr1   arangeint64tofloat)rH   rW   r[   baser6   attention_factorrG   r+   r+   r,   rS   z   s   
&z5FalconRotaryEmbedding.compute_default_rope_parametersc           
      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	|dd+ | |  
dd}tj||fdd	}| | j }| | j }	W d    n1 slw   Y  |j|jd
|	j|jd
fS )Nr   r3   r   mpscpuF)device_typeenabledr4   r5   r_   )rG   rh   expandr7   rg   rW   
isinstancetypestrr   	transposer1   r8   r@   rT   rA   r`   )
r)   r9   position_idsinv_freq_expandedposition_ids_expandedrm   freqsembr@   rA   r+   r+   r,   r-      s   0&zFalconRotaryEmbedding.forwardr%   )NNN)r.   r/   r0   r1   r2   __annotations__r    rN   staticmethodr   inttuplerh   rS   no_gradr   r-   __classcell__r+   r+   rY   r,   rF   g   s&   
 

rF   attention_mask	num_headsr`   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 )	Nr4   r
   ra   r   r   r5   r3   ).N)r7   mathfloorlog2r1   tensorrW   float32re   int32powminr8   cumsumbfloat16reshaperg   )r   r   r`   
batch_size
seq_lengthclosest_power_of_2ri   powersslopes
extra_basenum_remaining_headsextra_powersarange_tensoralibir+   r+   r,   build_alibi_tensor   s"   
 $ &r   r9   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)r9   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jdB dejdej
dB dedB dededej
dB deejejf dB fddZ  ZS )FalconAttentionNrH   c                    s`  t    || _|j| _|j| _| j| j | _| j| _|j| _|j	| _	d| _
|| _|d u r8td| jj d | j| j | jkrNtd| j d| j ddt| j | _| j| _|jrj|jd |j | j }n|jrv| 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).r^   r4   r
   r(   r   )rM   rN   rH   rc   rd   r   r]   
split_sizehidden_dropoutrO   	is_causal	layer_idxloggerwarning_oncerZ   r.   
ValueErrorr   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_dimrY   r+   r,   rN      sB   


"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]
        r3   r4   Nc                 S   s   g | ]}| d dqS )r4   r
   )flatten).0r9   r+   r+   r,   
<listcomp>      z0FalconAttention._split_heads.<locals>.<listcomp>r
   .r   r   )	r   r7   viewr   r   r]   r1   broadcast_tor   )r)   r   batchr[   _qkvquerykeyvaluer   r   three_times_hidden_sizer+   r+   r,   _split_heads  s"     
4<zFalconAttention._split_headsr9   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   r4   r   r
   )r7   r   r   r]   permuter   )r)   r9   batch_size_and_num_headsr   r   r   r+   r+   r,   _merge_heads#  s
   
zFalconAttention._merge_headsFr*   r   r   rt   
layer_past	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 }|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r,|s,| jo|d u o|dk}tjjj||||| jr| jjnd|d}d }|dd}|||| j| j }| |}||fS ||d	d }||| j||}|j}|tjksL|tjkrR| tj!}|||| jdd	 }|| j"9 }tj|| d	|jd
}| |}||| j||}|| #dd}| $|}| |}||fS )Nr   r4   r   rA   r@   r   sdpa        )	attn_mask	dropout_pr   r3   )r6   r`   r   r
   )%r   r   r   r   r   r7   rs   r   r]   rE   updater   rH   _attn_implementationr   r1   r   r	   scaled_dot_product_attentionr   r   r   softmaxr`   r   r   r   r   r   r   float16r   rg   r   r   r   r   )r)   r*   r   r   rt   r   r   r   r   r   r   r   query_layer	key_layervalue_layerr   query_lengthr   r@   rA   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%   NNFFNN)r.   r/   r0   r    rN   r1   r2   r|   r   r   
LongTensorr   boolr-   r~   r+   r+   rY   r,   r      s:    $* 	
r   c                       s   e Zd ZdZ fddZ						ddejdejdB dejd	ejdB d
edB de	de	dejdB de
ejejf dB 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%   )rM   rN   r   _flash_attn_uses_top_left_mask)r)   argskwargsrY   r+   r,   rN     s   zFalconFlashAttention2.__init__NFr*   r   r   rt   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|}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   r4   r   r   z6`alibi` is not supported when `use_flash_attn` is Truer   rk   rl   _is_quantizedzThe 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 .)rt   r   r   use_top_left_mask) r   r   r   r   r   r7   rs   r   r]   rE   r   r   r   r   rH   r   r`   rW   rq   r1   r   is_autocast_enabledget_autocast_dtypehasattrr&   r   r   rg   r!   r   r   r   )r)   r*   r   r   rt   r   r   r   r   r   r   r   r   r   r   r   r   r   r@   rA   r   attn_dropoutr   rm   target_dtyper   attn_weightsr+   r+   r,   r-     sj   








zFalconFlashAttention2.forwardr   )r.   r/   r0   __doc__rN   r1   r2   r   r   r   r|   r-   r~   r+   r+   rY   r,   r     s8    	
r   c                       s8   e Zd Zdef fddZdejdejfddZ  ZS )	FalconMLPrH   c                    sP   t    |j}t||j|jd| _t|j| _	t|j||jd| _
|j| _d S )Nr   )rM   rN   rc   r"   ffn_hidden_sizer(   dense_h_to_4hr   
activationactdense_4h_to_hr   )r)   rH   rc   rY   r+   r,   rN     s   
zFalconMLP.__init__r9   r$   c                 C   s   |  | |}| |}|S r%   )r   r   r   )r)   r9   r+   r+   r,   r-   #  s   
zFalconMLP.forward)	r.   r/   r0   r    rN   r1   r2   r-   r~   r+   r+   rY   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jdB dejd	ejdB d
ee	ejejf B dB de
de
dejdB de	ejejf dB 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 )Nr4   eps)rM   rN   rc   rd   r   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   rc   rY   r+   r,   rN   1  s    


zFalconDecoderLayer.__init__Fr*   r   r   rt   r   r   r   r   r   c
                 K   s   |}| j jr| j jdkr| |}| |}n| |}| j|||||||||	d	\}}| j jsG| j jr7|}nt||| j j	| j
d}| |}| j jrW| j jrW| j jdkrW|}| |}| j jsd| j jrh||7 }t||| j j| j
d}||fS )Nr4   )r   r   rt   r   r   r   r   r   )r   r   )rH   r   r  r  r  r  r   r  r   r   r   r  r   r   )r)   r*   r   r   rt   r   r   r   r   r   r   r   attention_layernorm_outmlp_layernorm_outattention_outputr   
mlp_outputoutputr+   r+   r,   r-   J  sD   




zFalconDecoderLayer.forwardr%   r   )r.   r/   r0   r    rN   r1   r2   r   r   r|   r   r-   r~   r+   r+   rY   r,   r   0  s6    	
r   c                       sd   e Zd ZU eed< dZdZdgZdZdZ	dZ
e dejf fddZedd	efd
dZ  ZS )FalconPreTrainedModelrH   transformerTr   modulec                    sN   t  | t|tr#tj|jd| jjd |j	dur%t
|j	 dS dS dS )zInitialize the weights.r   )meanstdN)rM   _init_weightsrp   r"   initnormal_r&   rH   initializer_ranger(   zeros_)r)   r  rY   r+   r,   r    s   

z#FalconPreTrainedModel._init_weightsFhard_check_onlyc                 C   s"   t | dd}|r
|S |sd|_|S )Nuse_bettertransformerFr   )rb   r   )clsrH   r  _is_bettertransformerr+   r+   r,   _check_and_enable_sdpa  s   z,FalconPreTrainedModel._check_and_enable_sdpa)F)r.   r/   r0   r    ry   base_model_prefixsupports_gradient_checkpointing_no_split_modules_supports_flash_attn_supports_sdpa_can_compile_fullgraphr1   r}   r   Moduler  classmethodr   r  r~   r+   r+   rY   r,   r    s   
 	r  c                       s   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j
d	B ded	B dejd	B dej
d	B dej
d	B ded	B ded	B ded	B ded	B dej
d	B deejdf eB 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| _d| _t 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   Fr&  )rM   rN   rc   	embed_dimrd   r   r   	use_alibir   	Embedding
vocab_sizeword_embeddings
ModuleListrangenum_hidden_layershr   r  ln_fgradient_checkpointingrF   
rotary_emb	post_initr)   rH   rY   r&  r,   rN     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%   r5  r)   r7  r+   r+   r,   set_input_embeddings     
z FalconModel.set_input_embeddingsN	input_idspast_key_valuesr   rt   inputs_embedsr   r   output_hidden_statesreturn_dictr   r$   .c                 K   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| 
|}|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}t| j |||
|d
d d}|dur|dur|jdkrt|jj}|jtjkrt|tjd|j|jd|}|j|dg|jdd R  }t |t!"| j j#| j  |dk |}|}| j$||d}|rdnd}|rdnd}t%| j&D ](\}}|r"||f }|||||||||
|d	}|d }|r=||d f }q| '|}|rL||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   ra   r_   rW   c                  W   s   t jdt jdS )NTr_   )r1   r   r   )r   r+   r+   r,   <lambda>  s    z%FalconModel.forward.<locals>.<lambda>)rH   r>  r   r   r=  and_mask_function   r   r3   r   )rt   r+   )r   r   rt   r   r   r   r   r   c                 s   s    | ]	}|d ur|V  qd S r%   r+   )r   vr+   r+   r,   	<genexpr>G  s    z&FalconModel.forward.<locals>.<genexpr>)last_hidden_stater=  r*   
attentions)*rH   r   r?  r   use_return_dictr   r1  r   r   r   r+  r   get_seq_lengthr7   r(  r1   onesrW   longr   r   r`   re   r=   r   ndimfinfor   r   wherer   r   masked_fillr   r   rc   r2  	enumerater/  r0  r|   r   )r)   r<  r=  r   rt   r>  r   r   r?  r@  r   r   r   past_key_values_lengthr   r   r   maskcausal_mask	min_dtyper*   r   all_self_attentionsall_hidden_statesr%  blockoutputsr+   r+   r,   r-     s   

	



zFalconModel.forward)
NNNNNNNNNN)r.   r/   r0   r    rN   r6  r1   r2   r:  r   r   r   r   r|   r   r-   r~   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).
    )custom_introc                       s   e Zd ZddiZdef fddZdejfddZe																								
ddej
d	B ded	B dejd	B dej
d	B dejd	B dejd	B ded	B ded	B ded	B ded	B dej
d	B deejB deej eB fddZ  ZS )FalconForCausalLMzlm_head.weightz"transformer.word_embeddings.weightrH   c                    s8   t  | t|| _tj|j|jdd| _| 	  d S NFr   )
rM   rN   r$  r  r   Linearrc   r*  lm_headr3  r4  rY   r+   r,   rN   [  s   
zFalconForCausalLM.__init__r7  c                 C   r8  r%   )r_  r9  r+   r+   r,   set_output_embeddingsc  r;  z'FalconForCausalLM.set_output_embeddingsNr   r<  r=  r   rt   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rL| j||fd| j ji|}|
sb|f|dd  }|dur`|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)	r=  r   rt   r>  r   r   r?  r@  r   r   r*  r   losslogitsr=  r*   rI  )rH   rJ  r  rp   r{   slicer_  loss_functionr*  r   r=  r*   rI  )r)   r<  r=  r   rt   r>  ra  r   r   r?  r@  r   rb  r   transformer_outputsr*   slice_indices	lm_logitsrd  r  r+   r+   r,   r-   f  sH   #zFalconForCausalLM.forward)NNNNNNNNNNNr   )r.   r/   r0   _tied_weights_keysr    rN   r1   r2   r`  r   r   r   r   r{   r|   r   r-   r~   r+   r+   rY   r,   r\  S  sX    	
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jdB dedB dej	dB dej	dB d	ej	dB d
e
dB de
dB de
dB de
dB deej	 eB fddZ  ZS )FalconForSequenceClassificationrH   c                    s@   t  | |j| _t|| _tj|j|jdd| _| 	  d S r]  )
rM   rN   
num_labelsr$  r  r   r^  rc   scorer3  r4  rY   r+   r,   rN     s
   
z(FalconForSequenceClassification.__init__Nr<  r=  r   r>  ra  r   r   r?  r@  r$   c
              
   K   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 rFd}n1|durk|| 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r=  r   r>  r   r   r?  r@  r   r   z=Cannot handle batch sizes > 1 if no padding token is defined.r3   ra   z will not detect padding tokens in `inputs_embeds`. Results may be unexpected if using padding tokens in conjunction with `inputs_embeds.`rB  
regressionsingle_label_classificationmulti_label_classificationrc  )rH   rJ  r  ro  r7   pad_token_idr   rg   rW   r1   r   re   argmaxr   r   rZ   r.   problem_typern  r`   rM  r{   r   squeezer   r   r   r=  r*   rI  )r)   r<  r=  r   r>  ra  r   r   r?  r@  r   rh  r*   re  r   last_non_pad_tokennon_pad_masktoken_indicespooled_logitsrd  loss_fctr  r+   r+   r,   r-     st    



"


z'FalconForSequenceClassification.forward	NNNNNNNNN)r.   r/   r0   r    rN   r   r1   r   r   r2   r   r|   r   r-   r~   r+   r+   rY   r,   rm    sB    		
rm  c                       rl  )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?)rM   rN   rn  r$  r  rb   r  r   r   r   r   r^  rc   
classifierr3  )r)   rH   r  rY   r+   r,   rN   6  s   
z%FalconForTokenClassification.__init__Nr<  r=  r   r>  ra  r   r   r?  r@  r$   c
              
   K   s   |	dur|	n| j j}	| j||||||||	d}|d }| |}| |}d}|durD|j\}}t }|||| | j||| }|	sZ|f|dd  }|durX|f| S |S t	|||j
|jdS )rp  Nrq  r   r4   )rd  re  r*   rI  )rH   rJ  r  r   r  r7   r   r   rn  r   r*   rI  )r)   r<  r=  r   r>  ra  r   r   r?  r@  r   rh  r*   re  rd  r   r   r}  r  r+   r+   r,   r-   G  s<    


z$FalconForTokenClassification.forwardr~  )r.   r/   r0   r    rN   r   r1   r   r   r2   r   r|   r   r-   r~   r+   r+   rY   r,   r  4  sB    	
r  c                       s   e Zd Z fddZe								ddejdB dejdB dejdB dejdB dejdB d	edB d
edB dedB de	e
B fddZ  ZS )FalconForQuestionAnsweringc                    s2   t  | t|| _t|jd| _|   d S )Nr4   )	rM   rN   r$  r  r   r^  rc   
qa_outputsr3  r4  rY   r+   r,   rN     s   
z#FalconForQuestionAnswering.__init__Nr<  r   r>  start_positionsend_positionsr   r?  r@  r$   c	                 K   sB  |dur|n| j j}| j||||||d}
|
d }| |}|jddd\}}|d }|d }d}|dur|durt| dkrL|d}t| dkrY|d}|d}|	d|}|	d|}t
|d}|||}|||}|| d }|s||f|
dd  }|dur|f| S |S t||||
j|
jd	S )
rA  N)r   r>  r   r?  r@  r   r   r3   r5   )ignore_indexr4   )rd  start_logits
end_logitsr*   rI  )rH   rJ  r  r  splitrx  
contiguouslensizeclampr   r   r*   rI  )r)   r<  r   r>  r  r  r   r?  r@  r   rZ  sequence_outputre  r  r  
total_lossignored_indexr}  
start_lossend_lossr  r+   r+   r,   r-     sJ   	






z"FalconForQuestionAnswering.forward)NNNNNNNN)r.   r/   r0   rN   r   r1   r   FloatTensorr   r|   r   r-   r~   r+   r+   rY   r,   r    s<    	r  )r\  r$  r  rm  r  r  )r   )Or   r   collections.abcr   typingr   r1   r   torch.nnr   r   r   r   r	   r    r   r  activationsr   cache_utilsr   r   
generationr   masking_utilsr   modeling_flash_attention_utilsr   r   modeling_layersr   modeling_outputsr   r   r   r   r   modeling_rope_utilsr   r   modeling_utilsr   utilsr   r   utils.genericr   configuration_falconr    r!   
get_loggerr.   r   r^  r"   r<   rE   r"  rF   r2   r{   r`   r   rh   r   r   r   r   r   r   r   r  r$  r\  rm  r  r  __all__r+   r+   r+   r,   <module>   sr   
	
 A$ ZhW -ZtWS