o
    Zhy                     @   sr  d Z ddlZddlmZmZ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 ddl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mZmZm Z m!Z!m"Z" ddl#m$Z$ ddl%m&Z&m'Z'm(Z(m)Z) ddl*m+Z+m,Z, ddl-m.Z. e rddlm/Z/ e,0e1Z2de3de3dej4fddZ5de3de3dej4fddZ6G dd dej7Z8G dd dej7Z9G dd de9Z:G d d! d!e9Z;G d"d# d#ej7Z<e9e:e;d$Z=G d%d& d&ej7Z>G d'd( d(ej7Z?e+G d)d* d*e$Z@e+G d+d, d,e@ZAe+d-d.G d/d0 d0e@ZBe+d1d.G d2d3 d3e@ZCe+G d4d5 d5e@ZDe+G d6d7 d7e@ZEe+G d8d9 d9e@ZFg d:ZGdS );z
PyTorch DistilBERT model adapted in part from Facebook, Inc XLM model (https://github.com/facebookresearch/XLM) and in
part from HuggingFace PyTorch version of Google AI Bert model (https://github.com/google-research/bert)
    N)DictListOptionalSetTupleUnion)nn)BCEWithLogitsLossCrossEntropyLossMSELoss   )get_activation)PretrainedConfig)is_deepspeed_zero3_enabled)#_prepare_4d_attention_mask_for_sdpa)!flash_attn_supports_top_left_maskis_flash_attn_available)BaseModelOutputMaskedLMOutputMultipleChoiceModelOutputQuestionAnsweringModelOutputSequenceClassifierOutputTokenClassifierOutput)PreTrainedModel)apply_chunking_to_forward find_pruneable_heads_and_indices"is_torch_greater_or_equal_than_2_2prune_linear_layer)auto_docstringlogging   )DistilBertConfig)_flash_attention_forwardn_posdimoutc                 C   s   t  r8dd l}|jj|dd tj dkr&t| ||d W d    d S W d    d S 1 s1w   Y  d S t| ||d d S )Nr   )Zmodifier_rankr#   r$   r%   )r   	deepspeedzeroZGatheredParameterstorchdistributedZget_rank_create_sinusoidal_embeddings)r#   r$   r%   r'    r,   a/var/www/auris/lib/python3.10/site-packages/transformers/models/distilbert/modeling_distilbert.pycreate_sinusoidal_embeddingsB   s   "r.   c              	      s   t  fddt| D }d|_tt |d d dd df |d d dd df< tt |d d dd df |d d dd df< |  d S )Nc                    s$   g | ]  fd dt D qS )c              	      s(   g | ]}t d d|d     qS )i'     )nppower).0j)r$   posr,   r-   
<listcomp>N   s   ( z<_create_sinusoidal_embeddings.<locals>.<listcomp>.<listcomp>)range)r2   r$   )r4   r-   r5   N   s   $ z1_create_sinusoidal_embeddings.<locals>.<listcomp>Fr   r/   r    )	r0   arrayr6   Zrequires_gradr)   ZFloatTensorsincosZdetach_)r#   r$   r%   Zposition_encr,   r7   r-   r+   M   s
   44r+   c                       sD   e Zd Zdef fddZd
dejdeej dejfdd	Z  Z	S )
Embeddingsconfigc                    sv   t    tj|j|j|jd| _t|j|j| _	tj
|jdd| _
t|j| _| jdt|jddd d S )N)padding_idx-q=epsposition_ids)r    F)
persistent)super__init__r   	Embedding
vocab_sizer$   Zpad_token_idword_embeddingsmax_position_embeddingsposition_embeddings	LayerNormDropoutdropoutZregister_bufferr)   arangeexpandselfr<   	__class__r,   r-   rE   V   s   

zEmbeddings.__init__N	input_idsinput_embedsreturnc                 C   s   |dur	|  |}|d}t| dr| jddd|f }ntj|tj|jd}|d	|}| 
|}|| }| |}| |}|S )a  
        Parameters:
            input_ids (torch.Tensor):
                torch.tensor(bs, max_seq_length) The token ids to embed.
            input_embeds (*optional*, torch.Tensor):
                The pre-computed word embeddings. Can only be passed if the input ids are `None`.


        Returns: torch.tensor(bs, max_seq_length, dim) The embedded tokens (plus position embeddings, no token_type
        embeddings)
        Nr    rA   )dtypedevicer   )rH   sizehasattrrA   r)   rN   longrX   Z	unsqueeze	expand_asrJ   rK   rM   )rQ   rT   rU   Z
seq_lengthrA   rJ   
embeddingsr,   r,   r-   forwarda   s   





zEmbeddings.forwardN)
__name__
__module____qualname__r   rE   r)   Tensorr   r^   __classcell__r,   r,   rR   r-   r;   U   s    *r;   c                       sx   e Zd Zdef fddZdee fddZ		dd	ej	d
ej	dej	dej	de
ej	 dedeej	df fddZ  ZS )MultiHeadSelfAttentionr<   c                    s   t    || _|j| _|j| _tj|jd| _d| _	| j| j dkr0t
d| j d| j dtj|j|jd| _tj|j|jd| _tj|j|jd| _tj|j|jd| _t | _| j| j | _d S )NpFr   zself.n_heads: z must divide self.dim:  evenlyZin_featuresZout_features)rD   rE   r<   n_headsr$   r   rL   attention_dropoutrM   	is_causal
ValueErrorLinearq_link_linv_linout_linsetpruned_headsattention_head_sizerP   rR   r,   r-   rE      s   
zMultiHeadSelfAttention.__init__headsc                 C   s   t |dkrd S t|| j| j| j\}}t| j|| _t| j|| _t| j|| _t| j	|dd| _	| jt | | _| j| j | _
| j|| _d S )Nr   r    r7   )lenr   rj   ru   rt   r   ro   rp   rq   rr   r$   union)rQ   rv   indexr,   r,   r-   prune_heads   s   z"MultiHeadSelfAttention.prune_headsNFquerykeyvaluemask	head_maskoutput_attentionsrV   .c                    sB  |  \ }}| d}	jj  dd|	f}
dtjdtjf fdd}dtjdtjf fdd}||}||}||}|t	 }t
||dd	}|d
k|
|}||tt|jj}tjj|dd}|}|dur|| }t
||}||}|}|r||fS |fS )  
        Parameters:
            query: torch.tensor(bs, seq_length, dim)
            key: torch.tensor(bs, seq_length, dim)
            value: torch.tensor(bs, seq_length, dim)
            mask: torch.tensor(bs, seq_length)

        Returns:
            weights: torch.tensor(bs, n_heads, seq_length, seq_length) Attention weights context: torch.tensor(bs,
            seq_length, dim) Contextualized layer. Optional: only if `output_attentions=True`
        r    xrV   c                       |   djddS separate headsrB   r    r/   viewrj   	transposer   bsdim_per_headrQ   r,   r-   shape      z-MultiHeadSelfAttention.forward.<locals>.shapec                        |  dd  dj S zgroup headsr    r/   rB   r   
contiguousr   rj   r   r   r,   r-   unshape       z/MultiHeadSelfAttention.forward.<locals>.unshaper/   r   r   rB   r7   N)rY   r$   rj   r)   rc   ro   rp   rq   mathsqrtmatmulr   r   r\   Zmasked_fillZtensorZfinforW   minr   
functionalZsoftmaxrM   rr   )rQ   r{   r|   r}   r~   r   r   q_lengthr$   Zk_lengthZ
mask_reshpr   r   qkvZscoresweightscontextr,   r   r-   r^      s2   


zMultiHeadSelfAttention.forwardNF)r`   ra   rb   r   rE   r   intrz   r)   rc   r   boolr   r^   rd   r,   r,   rR   r-   re      s(    re   c                       sd   e Zd ZdZ fddZ		ddejdejdejd	ejd
eej dede	ejdf fddZ
  ZS )DistilBertFlashAttention2aS  
    DistilBert flash attention module. This module inherits from `MultiHeadSelfAttention` 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_   )rD   rE   r   _flash_attn_uses_top_left_mask)rQ   argskwargsrR   r,   r-   rE      s   z"DistilBertFlashAttention2.__init__NFr{   r|   r}   r~   r   r   rV   .c              
      s.  |  \ }}jj dtjdtjf fdd}	|	|}
|	|}|	|}jr8j	j
nd}|
jtjkrqt rIt }ntj	drTj	j}njjj}td| d |
|}
||}||}t|
|||||jjd	}| |j }|}|r||fS |fS )
r   r   rV   c                    s   |   djS )r   rB   )r   rj   r   Z
batch_sizer   rQ   r,   r-   reshape  s   z2DistilBertFlashAttention2.forward.<locals>.reshape        _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 .)rM   Zuse_top_left_maskrl   )rY   r$   rj   r)   rc   ro   rp   rq   trainingr<   rk   rW   Zfloat32Zis_autocast_enabledZget_autocast_gpu_dtyperZ   r   weightloggerwarning_oncetor"   r   rl   r   rr   )rQ   r{   r|   r}   r~   r   r   r   r$   r   Zquery_statesZ
key_statesZvalue_statesZattn_dropoutZtarget_dtypeZattn_weightsZattn_weights_reshapedattn_outputr,   r   r-   r^      sH   






z!DistilBertFlashAttention2.forwardr   )r`   ra   rb   __doc__rE   r)   rc   r   r   r   r^   rd   r,   r,   rR   r-   r      s(    r   c                       sj   e Zd Zdef fddZ		ddejdejdejd	ejd
eej dede	ejdf f fddZ
  ZS )DistilBertSdpaAttentionr<   c                    s"   t  j|d |j| _t | _d S )Nr<   )rD   rE   rk   dropout_probr   require_contiguous_qkvrP   rR   r,   r-   rE   L  s   z DistilBertSdpaAttention.__init__NFr{   r|   r}   r~   r   r   rV   .c                    s  |s|durt d t ||||||S | \ }}jj dtjdtjf fdd}dtjdtjf fdd}	|	|}
|
|}||}jro|
jjd	kro|duro|
 }
| }| }tjjj|
|||jr}jnd
dd}|	|}|}|fS )r   Na  DistilBertSdpaAttention is used but `torch.nn.functional.scaled_dot_product_attention` does not support `output_attentions=True` or `head_mask`. Falling back to the manual attention implementation, but specifying the manual implementation will be required from Transformers version v5.0.0 onwards. This warning can be removed using the argument `attn_implementation="eager"` when loading the model.r   rV   c                    r   r   r   r   r   r,   r-   r   x  r   z.DistilBertSdpaAttention.forward.<locals>.shapec                    r   r   r   r   r   r,   r-   r   |  r   z0DistilBertSdpaAttention.forward.<locals>.unshapecudar   F)	attn_maskZ	dropout_prl   )r   r   rD   r^   rY   r$   rj   r)   rc   ro   rp   rq   r   rX   typer   r   r   Zscaled_dot_product_attentionr   r   rr   )rQ   r{   r|   r}   r~   r   r   _r   r   r   r   r   r   rR   r   r-   r^   Q  sD   		
zDistilBertSdpaAttention.forwardr   r`   ra   rb   r   rE   r)   rc   r   r   r   r^   rd   r,   r,   rR   r-   r   K  s&    r   c                       sN   e Zd Zdef fddZdejdejfddZdejdejfdd	Z  Z	S )
FFNr<   c                    s`   t    tj|jd| _|j| _d| _tj|j|j	d| _
tj|j	|jd| _t|j| _d S )Nrf   r    ri   )rD   rE   r   rL   rM   chunk_size_feed_forwardseq_len_dimrn   r$   Z
hidden_dimlin1lin2r   
activationrP   rR   r,   r-   rE     s   
zFFN.__init__inputrV   c                 C   s   t | j| j| j|S r_   )r   ff_chunkr   r   )rQ   r   r,   r,   r-   r^     s   zFFN.forwardc                 C   s,   |  |}| |}| |}| |}|S r_   )r   r   r   rM   )rQ   r   r   r,   r,   r-   r     s
   



zFFN.ff_chunk)
r`   ra   rb   r   rE   r)   rc   r^   r   rd   r,   r,   rR   r-   r     s    	r   )eagerflash_attention_2sdpac                       s`   e Zd Zdef fddZ			ddejdeej deej d	ed
e	ejdf f
ddZ
  ZS )TransformerBlockr<   c                    sv   t    |j|j dkrtd|j d|j dt|j || _tj	|jdd| _
t|| _tj	|jdd| _d S )Nr   zconfig.n_heads z must divide config.dim rh   r>   )Znormalized_shaper@   )rD   rE   r$   rj   rm   DISTILBERT_ATTENTION_CLASSES_attn_implementation	attentionr   rK   sa_layer_normr   ffnoutput_layer_normrP   rR   r,   r-   rE     s   

zTransformerBlock.__init__NFr   r   r   r   rV   .c           	      C   s   | j ||||||d}|r|\}}nt|tur"tdt| d|d }| || }| |}| || }|f}|rC|f| }|S )ae  
        Parameters:
            x: torch.tensor(bs, seq_length, dim)
            attn_mask: torch.tensor(bs, seq_length)

        Returns:
            sa_weights: torch.tensor(bs, n_heads, seq_length, seq_length) The attention weights ffn_output:
            torch.tensor(bs, seq_length, dim) The output of the transformer block contextualization.
        )r{   r|   r}   r~   r   r   z$sa_output must be a tuple but it is z typer   )r   r   tuple	TypeErrorr   r   r   )	rQ   r   r   r   r   Z	sa_outputZ
sa_weightsZ
ffn_outputoutputr,   r,   r-   r^     s(   


zTransformerBlock.forward)NNFr   r,   r,   rR   r-   r     s     r   c                       sx   e Zd Zdef fddZ					ddejdeej deej d	ed
edee de	e
eejdf f fddZ  ZS )Transformerr<   c                    s<   t     j| _t fddt jD | _d| _d S )Nc                    s   g | ]}t  qS r,   )r   )r2   r   r   r,   r-   r5     s    z(Transformer.__init__.<locals>.<listcomp>F)rD   rE   Zn_layersr   Z
ModuleListr6   layergradient_checkpointingrP   rR   r   r-   rE     s   
 
zTransformer.__init__NFr   r   r   r   output_hidden_statesreturn_dictrV   .c                 C   s
  |rdnd}|r
dnd}|}	t | jD ]U\}
}|r||	f }| jr1| jr1| |j|	|||
 |}n	||	|||
 |}|d }	|rYt|dkrOtdt| |d }||f }qt|dkrhtdt| q|rp||	f }|s~td	d
 |	||fD S t	|	||dS )a  
        Parameters:
            x: torch.tensor(bs, seq_length, dim) Input sequence embedded.
            attn_mask: torch.tensor(bs, seq_length) Attention mask on the sequence.

        Returns:
            hidden_state: torch.tensor(bs, seq_length, dim) Sequence of hidden states in the last (top)
            layer all_hidden_states: Tuple[torch.tensor(bs, seq_length, dim)]
                Tuple of length n_layers with the hidden states from each layer.
                Optional: only if output_hidden_states=True
            all_attentions: Tuple[torch.tensor(bs, n_heads, seq_length, seq_length)]
                Tuple of length n_layers with the attention weights from each layer
                Optional: only if output_attentions=True
        r,   NrB   r/   z7The length of the layer_outputs should be 2, but it is r   r    z7The length of the layer_outputs should be 1, but it is c                 s   s    | ]	}|d ur|V  qd S r_   r,   )r2   r   r,   r,   r-   	<genexpr>8  s    z&Transformer.forward.<locals>.<genexpr>)Zlast_hidden_statehidden_states
attentions)
	enumerater   r   r   Z_gradient_checkpointing_func__call__rw   rm   r   r   )rQ   r   r   r   r   r   r   Zall_hidden_statesZall_attentionshidden_stateiZlayer_moduleZlayer_outputsr   r,   r,   r-   r^     sH   

zTransformer.forward)NNFFN)r`   ra   rb   r   rE   r)   rc   r   r   r   r   r   r^   rd   r,   r,   rR   r-   r     s,    	r   c                   @   s4   e Zd ZeZdZdZdZdZdZ	de
jfddZdS )DistilBertPreTrainedModelN
distilbertTmodulec                 C   s   t |tjr |jjjd| jjd |jdur|jj	  dS dS t |tj
rC|jjjd| jjd |jdurA|jj|j 	  dS dS t |tjrX|jj	  |jjd dS t |tro| jjrqt| jj| jj|jj dS dS dS )zInitialize the weights.r   )meanZstdNg      ?)
isinstancer   rn   r   dataZnormal_r<   Zinitializer_rangeZbiasZzero_rF   r=   rK   Zfill_r;   sinusoidal_pos_embdsr.   rI   r$   rJ   )rQ   r   r,   r,   r-   _init_weightsH  s$   

z'DistilBertPreTrainedModel._init_weights)r`   ra   rb   r!   Zconfig_classZload_tf_weightsZbase_model_prefixZsupports_gradient_checkpointingZ_supports_flash_attn_2Z_supports_sdpar   Moduler   r,   r,   r,   r-   r   ?  s    r   c                       s   e Zd Zdef fddZdejfddZdefdd	Z	dejfd
dZ
dejfddZdeeeee  f 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 dee dee deeeejdf f fddZ  ZS )DistilBertModelr<   c                    sD   t  | t|| _t|| _|jdk| _|jdk| _| 	  d S )Nr   r   )
rD   rE   r;   r]   r   transformerr   _use_flash_attention_2	_use_sdpa	post_initrP   rR   r,   r-   rE   _  s   

zDistilBertModel.__init__rV   c                 C      | j jS z1
        Returns the position embeddings
        )r]   rJ   rQ   r,   r,   r-   get_position_embeddingsj  s   z'DistilBertModel.get_position_embeddingsnew_num_position_embeddingsc                 C   s   || j j }|dkrdS td| d || j _| jjj }t	| j j| j j
| j_| j jr>t| j j| j j
| jjd n2t & |dkrUt|| jjjd| < nt|d| | jj_W d   n1 skw   Y  | jj| j dS )  
        Resizes position embeddings of the model if `new_num_position_embeddings != config.max_position_embeddings`.

        Arguments:
            new_num_position_embeddings (`int`):
                The number of new position embedding matrix. If position embeddings are learned, increasing the size
                will add newly initialized vectors at the end, whereas reducing the size will remove vectors from the
                end. If position embeddings are not learned (*e.g.* sinusoidal position embeddings), increasing the
                size will add correct vectors at the end following the position encoding algorithm, whereas reducing
                the size will remove vectors from the end.
        r   Nz(Setting `config.max_position_embeddings=z`...r&   )r<   rI   r   infor]   rJ   r   cloner   rF   r$   r   r.   r)   Zno_grad	Parameterr   rX   )rQ   r   Znum_position_embeds_diffZold_position_embeddings_weightr,   r,   r-   resize_position_embeddingsp  s,   



z*DistilBertModel.resize_position_embeddingsc                 C   r   r_   r]   rH   r   r,   r,   r-   get_input_embeddings  s   z$DistilBertModel.get_input_embeddingsnew_embeddingsc                 C   s   || j _d S r_   r   rQ   r   r,   r,   r-   set_input_embeddings  s   z$DistilBertModel.set_input_embeddingsheads_to_prunec                 C   s*   |  D ]\}}| jj| j| qdS )z
        Prunes heads of the model. heads_to_prune: dict of {layer_num: list of heads to prune in this layer} See base
        class PreTrainedModel
        N)itemsr   r   r   rz   )rQ   r   r   rv   r,   r,   r-   _prune_heads  s   zDistilBertModel._prune_headsNrT   attention_maskr   inputs_embedsr   r   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*|dur*td|dur9| || | }n|durF| dd }ntd|durQ|jn|j}	|du }
| || j j	}| 
||}| jrv|dursd|v rs|nd}n|du rtj||	d}| jr|
r|st||j|d d}| j||||||d	S )
   
        input_ids (`torch.LongTensor` of shape `(batch_size, num_choices)`):
            Indices of input sequence tokens in the vocabulary.

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

            [What are input IDs?](../glossary#input-ids)
        inputs_embeds (`torch.FloatTensor` of shape `(batch_size, num_choices, hidden_size)`, *optional*):
            Optionally, instead of passing `input_ids` you can choose to directly pass an embedded representation. This
            is useful if you want more control over how to convert `input_ids` indices into associated vectors than the
            model's internal embedding lookup matrix.
        NzDYou cannot specify both input_ids and inputs_embeds at the same timerB   z5You have to specify either input_ids or inputs_embedsr   )rX   r    )Ztgt_len)r   r   r   r   r   r   )r<   r   r   use_return_dictrm   Z%warn_if_padding_and_no_attention_maskrY   rX   Zget_head_maskZnum_hidden_layersr]   r   r)   Zonesr   r   rW   r   )rQ   rT   r   r   r   r   r   r   Zinput_shaperX   Zhead_mask_is_noner]   r,   r,   r-   r^     s@   
zDistilBertModel.forward)NNNNNNN)r`   ra   rb   r   rE   r   rF   r   r   r   r   r   r   r   r   r   r   r)   rc   r   r   r   r   r^   rd   r,   r,   rR   r-   r   ]  s@    *	r   zI
    DistilBert Model with a `masked language modeling` head on top.
    )Zcustom_introc                       s   e Zd ZdgZdef fddZdejfddZde	fd	d
Z
dejfddZdej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 dee dee deeeejdf f fddZ  ZS )DistilBertForMaskedLMzvocab_projector.weightr<   c                    sn   t  | t|j| _t|| _t|j|j| _	tj
|jdd| _t|j|j| _|   t | _d S )Nr>   r?   )rD   rE   r   r   r   r   r   rn   r$   vocab_transformrK   vocab_layer_normrG   vocab_projectorr   r
   mlm_loss_fctrP   rR   r,   r-   rE     s   
zDistilBertForMaskedLM.__init__rV   c                 C   
   | j  S r   r   r   r   r,   r,   r-   r        
z-DistilBertForMaskedLM.get_position_embeddingsr   c                 C      | j | dS r   Nr   r   rQ   r   r,   r,   r-   r   
     z0DistilBertForMaskedLM.resize_position_embeddingsc                 C   s   | j S r_   r  r   r,   r,   r-   get_output_embeddings  s   z+DistilBertForMaskedLM.get_output_embeddingsr   c                 C   s
   || _ d S r_   r  r   r,   r,   r-   set_output_embeddings  s   
z+DistilBertForMaskedLM.set_output_embeddingsNrT   r   r   r   labelsr   r   r   .c	              	   C   s   |dur|n| j j}| j|||||||d}	|	d }
| |
}| |}| |}| |}d}|durD| |d|	d|d}|sZ|f|	dd  }|durX|f| S |S t
|||	j|	jdS )a  
        input_ids (`torch.LongTensor` of shape `(batch_size, num_choices)`):
            Indices of input sequence tokens in the vocabulary.

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

            [What are input IDs?](../glossary#input-ids)
        inputs_embeds (`torch.FloatTensor` of shape `(batch_size, num_choices, hidden_size)`, *optional*):
            Optionally, instead of passing `input_ids` you can choose to directly pass an embedded representation. This
            is useful if you want more control over how to convert `input_ids` indices into associated vectors than the
            model's internal embedding lookup matrix.
        labels (`torch.LongTensor` of shape `(batch_size, sequence_length)`, *optional*):
            Labels for computing the masked language modeling loss. Indices should be in `[-100, 0, ...,
            config.vocab_size]` (see `input_ids` docstring) Tokens with indices set to `-100` are ignored (masked), the
            loss is only computed for the tokens with labels in `[0, ..., config.vocab_size]`.
        NrT   r   r   r   r   r   r   r   rB   r    losslogitsr   r   )r<   r   r   r  r   r  r  r  r   rY   r   r   r   )rQ   rT   r   r   r   r  r   r   r   Zdlbrt_outputr   Zprediction_logitsZmlm_lossr   r,   r,   r-   r^     s6   	



 zDistilBertForMaskedLM.forwardNNNNNNNN)r`   ra   rb   Z_tied_weights_keysr   rE   r   rF   r   r   r   r   r  r  r   r   r)   rc   
LongTensorr   r   r   r   r^   rd   r,   r,   rR   r-   r    sF    	
r  z
    DistilBert Model transformer with a sequence classification/regression head on top (a linear layer on top of the
    pooled output) e.g. for GLUE tasks.
    c                          e Zd Zdef fddZdejfddZde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 dee dee deeeejdf f fddZ  ZS )#DistilBertForSequenceClassificationr<   c                    sb   t  | |j| _|| _t|| _t|j|j| _	t|j|j| _
t|j| _|   d S r_   )rD   rE   
num_labelsr<   r   r   r   rn   r$   pre_classifier
classifierrL   seq_classif_dropoutrM   r   rP   rR   r,   r-   rE   c  s   
z,DistilBertForSequenceClassification.__init__rV   c                 C   r  r   r  r   r,   r,   r-   r   p  r  z;DistilBertForSequenceClassification.get_position_embeddingsr   c                 C   r	  r
  r  r  r,   r,   r-   r   v  r  z>DistilBertForSequenceClassification.resize_position_embeddingsNrT   r   r   r   r  r   r   r   .c	              	   C   s  |dur|n| j j}| j|||||||d}	|	d }
|
dddf }| |}t |}| |}| |}d}|dur| j jdu rg| j	dkrMd| j _n| j	dkrc|j
tjks^|j
tjkrcd| j _nd| j _| j jdkrt }| j	dkr|| | }n+|||}n%| j jdkrt }||d| j	|d}n| j jdkrt }|||}|s|f|	dd  }|dur|f| S |S t|||	j|	jd	S )
a  
        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).
        Nr  r   r    Z
regressionZsingle_label_classificationZmulti_label_classificationrB   r  )r<   r   r   r  r   ReLUrM   r  Zproblem_typer  rW   r)   r[   r   r   squeezer
   r   r	   r   r   r   )rQ   rT   r   r   r   r  r   r   r   distilbert_outputr   pooled_outputr  r  loss_fctr   r,   r,   r-   r^     sX   	




"


z+DistilBertForSequenceClassification.forwardr  )r`   ra   rb   r   rE   r   rF   r   r   r   r   r   r)   rc   r  r   r   r   r   r^   rd   r,   r,   rR   r-   r  \  s@    	
r  c                       s   e Zd Zdef fddZdejfddZde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ejdf f fddZ  ZS )DistilBertForQuestionAnsweringr<   c                    s\   t  | t|| _t|j|j| _|jdkr!t	d|j t
|j| _|   d S )Nr/   z)config.num_labels should be 2, but it is )rD   rE   r   r   r   rn   r$   r  
qa_outputsrm   rL   Z
qa_dropoutrM   r   rP   rR   r,   r-   rE     s   

z'DistilBertForQuestionAnswering.__init__rV   c                 C   r  r   r  r   r,   r,   r-   r     r  z6DistilBertForQuestionAnswering.get_position_embeddingsr   c                 C   r	  r
  r  r  r,   r,   r-   r     r  z9DistilBertForQuestionAnswering.resize_position_embeddingsNrT   r   r   r   start_positionsend_positionsr   r   r   .c
              	   C   sP  |	dur|	n| j j}	| j|||||||	d}
|
d }| |}| |}|jddd\}}|d }|d }d}|dur|durt|	 dkrR|d}t|	 dkr_|d}|	d}|
d|}|
d|}tj|d}|||}|||}|| d }|	s||f|
dd  }|dur|f| S |S t||||
j|
jd	S )
r   Nr  r   r    rB   r7   )Zignore_indexr/   )r  start_logits
end_logitsr   r   )r<   r   r   rM   r$  splitr  r   rw   rY   clampr   r
   r   r   r   )rQ   rT   r   r   r   r%  r&  r   r   r   r   r   r  r'  r(  Z
total_lossZignored_indexr"  Z
start_lossZend_lossr   r,   r,   r-   r^     sN   	






z&DistilBertForQuestionAnswering.forward)	NNNNNNNNN)r`   ra   rb   r   rE   r   rF   r   r   r   r   r   r)   rc   r   r   r   r   r^   rd   r,   r,   rR   r-   r#    sF    	
r#  c                       r  ) DistilBertForTokenClassificationr<   c                    sJ   t  | |j| _t|| _t|j| _t|j	|j| _
|   d S r_   )rD   rE   r  r   r   r   rL   rM   rn   Zhidden_sizer  r   rP   rR   r,   r-   rE   ;  s   
z)DistilBertForTokenClassification.__init__rV   c                 C   r  r   r  r   r,   r,   r-   r   F  r  z8DistilBertForTokenClassification.get_position_embeddingsr   c                 C   r	  r
  r  r  r,   r,   r-   r   L  r  z;DistilBertForTokenClassification.resize_position_embeddingsNrT   r   r   r   r  r   r   r   .c	              	   C   s   |dur|n| j j}| j|||||||d}	|	d }
| |
}
| |
}d}|dur:t }||d| j|d}|sP|f|	dd  }|durN|f| S |S t|||	j	|	j
dS )z
        labels (`torch.LongTensor` of shape `(batch_size, sequence_length)`, *optional*):
            Labels for computing the token classification loss. Indices should be in `[0, ..., config.num_labels - 1]`.
        Nr   r   r   r   r   r   r   rB   r    r  )r<   r   r   rM   r  r
   r   r  r   r   r   )rQ   rT   r   r   r   r  r   r   r   outputsZsequence_outputr  r  r"  r   r,   r,   r-   r^   Z  s4   


z(DistilBertForTokenClassification.forwardr  )r`   ra   rb   r   rE   r   rF   r   r   r   r   r   r)   rc   r  r   r   r   r   r^   rd   r,   r,   rR   r-   r+  9  @    	
r+  c                       r  )DistilBertForMultipleChoicer<   c                    sR   t  | t|| _t|j|j| _t|jd| _t	|j
| _|   d S )Nr    )rD   rE   r   r   r   rn   r$   r  r  rL   r  rM   r   rP   rR   r,   r-   rE     s   
z$DistilBertForMultipleChoice.__init__rV   c                 C   r  r   r  r   r,   r,   r-   r     r  z3DistilBertForMultipleChoice.get_position_embeddingsr   c                 C   r	  )a  
        Resizes position embeddings of the model if `new_num_position_embeddings != config.max_position_embeddings`.

        Arguments:
            new_num_position_embeddings (`int`)
                The number of new position embeddings. If position embeddings are learned, increasing the size will add
                newly initialized vectors at the end, whereas reducing the size will remove vectors from the end. If
                position embeddings are not learned (*e.g.* sinusoidal position embeddings), increasing the size will
                add correct vectors at the end following the position encoding algorithm, whereas reducing the size
                will remove vectors from the end.
        Nr  r  r,   r,   r-   r     r  z6DistilBertForMultipleChoice.resize_position_embeddingsNrT   r   r   r   r  r   r   r   .c	              	   C   sT  |dur|n| j j}|dur|jd n|jd }	|dur%|d|dnd}|dur4|d|dnd}|durG|d|d|dnd}| j|||||||d}
|
d }|dddf }| |}t |}| 	|}| 
|}|d|	}d}|durt }|||}|s|f|
dd  }|dur|f| S |S t|||
j|
jdS )a^  
        input_ids (`torch.LongTensor` of shape `(batch_size, num_choices, sequence_length)`):
            Indices of input sequence tokens in the vocabulary.

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

            [What are input IDs?](../glossary#input-ids)
        inputs_embeds (`torch.FloatTensor` of shape `(batch_size, num_choices, sequence_length, hidden_size)`, *optional*):
            Optionally, instead of passing `input_ids` you can choose to directly pass an embedded representation. This
            is useful if you want more control over how to convert `input_ids` indices into associated vectors than the
            model's internal embedding lookup matrix.
        labels (`torch.LongTensor` of shape `(batch_size,)`, *optional*):
            Labels for computing the multiple choice classification loss. Indices should be in `[0, ...,
            num_choices-1]` where `num_choices` is the size of the second dimension of the input tensors. (See
            `input_ids` above)

        Examples:

        ```python
        >>> from transformers import AutoTokenizer, DistilBertForMultipleChoice
        >>> import torch

        >>> tokenizer = AutoTokenizer.from_pretrained("distilbert-base-cased")
        >>> model = DistilBertForMultipleChoice.from_pretrained("distilbert-base-cased")

        >>> prompt = "In Italy, pizza served in formal settings, such as at a restaurant, is presented unsliced."
        >>> choice0 = "It is eaten with a fork and a knife."
        >>> choice1 = "It is eaten while held in the hand."
        >>> labels = torch.tensor(0).unsqueeze(0)  # choice0 is correct (according to Wikipedia ;)), batch size 1

        >>> encoding = tokenizer([[prompt, choice0], [prompt, choice1]], return_tensors="pt", padding=True)
        >>> outputs = model(**{k: v.unsqueeze(0) for k, v in encoding.items()}, labels=labels)  # batch size is 1

        >>> # the linear classifier still needs to be trained
        >>> loss = outputs.loss
        >>> logits = outputs.logits
        ```Nr    rB   r,  r   r  )r<   r   r   r   rY   r   r  r   r  rM   r  r
   r   r   r   )rQ   rT   r   r   r   r  r   r   r   Znum_choicesr-  r   r!  r  Zreshaped_logitsr  r"  r   r,   r,   r-   r^     sJ   2




z#DistilBertForMultipleChoice.forwardr  )r`   ra   rb   r   rE   r   rF   r   r   r   r   r   r)   rc   r  r   r   r   r   r^   rd   r,   r,   rR   r-   r/    r.  r/  )r  r/  r#  r  r+  r   r   )Hr   r   typingr   r   r   r   r   r   numpyr0   r)   r   Ztorch.nnr	   r
   r   Zactivationsr   Zconfiguration_utilsr   Zintegrations.deepspeedr   Zmodeling_attn_mask_utilsr   Zmodeling_flash_attention_utilsr   r   Zmodeling_outputsr   r   r   r   r   r   Zmodeling_utilsr   Zpytorch_utilsr   r   r   r   utilsr   r   Zconfiguration_distilbertr!   r"   Z
get_loggerr`   r   r   rc   r.   r+   r   r;   re   r   r   r   r   r   r   r   r   r  r  r#  r+  r/  __all__r,   r,   r,   r-   <module>   sl     
.h`P:N jimR 