U
    9%e%                     @   sT  d Z ddlZddlmZmZm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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 ee Z!dZ"dZ#dddgZ$G dd dej%Z&G dd dej%Z'G dd dej(Z)G dd dej%Z*G dd dej%Z+G dd dej%Z,G dd dej%Z-G dd  d ej%Z.G d!d" d"ej%Z/G d#d$ d$ej%Z0G d%d& d&ej%Z1G d'd( d(ej%Z2G d)d* d*eZ3d+Z4d,Z5ed-e4G d.d/ d/e3Z6ed0e4G d1d2 d2e3Z7ed3e4G d4d5 d5e3Z8ed6e4G d7d8 d8e3Z9ed9e4G d:d; d;e3Z:ed<e4G d=d> d>e3Z;dS )?z PyTorch SqueezeBert model.    N)OptionalTupleUnion)nn)BCEWithLogitsLossCrossEntropyLossMSELoss   )ACT2FN)BaseModelOutputBaseModelOutputWithPoolingMaskedLMOutputMultipleChoiceModelOutputQuestionAnsweringModelOutputSequenceClassifierOutputTokenClassifierOutput)PreTrainedModel)add_code_sample_docstringsadd_start_docstrings%add_start_docstrings_to_model_forwardlogging   )SqueezeBertConfigzsqueezebert/squeezebert-uncasedr   zsqueezebert/squeezebert-mnliz%squeezebert/squeezebert-mnli-headlessc                       s*   e Zd ZdZ fddZdddZ  ZS )SqueezeBertEmbeddingszGConstruct the embeddings from word, position and token_type embeddings.c                    s   t    tj|j|j|jd| _t|j|j| _	t|j
|j| _tj|j|jd| _t|j| _| jdt|jddd d S )N)padding_idxepsposition_ids)r   F)
persistent)super__init__r   	Embedding
vocab_sizeembedding_sizeZpad_token_idword_embeddingsZmax_position_embeddingsposition_embeddingsZtype_vocab_sizetoken_type_embeddings	LayerNormhidden_sizelayer_norm_epsDropouthidden_dropout_probdropoutZregister_buffertorchZarangeexpandselfconfig	__class__ s/var/www/html/Darija-Ai-API/env/lib/python3.8/site-packages/transformers/models/squeezebert/modeling_squeezebert.pyr!   7   s    
  zSqueezeBertEmbeddings.__init__Nc           
      C   s   |d k	r|  }n|  d d }|d }|d krH| jd d d |f }|d krftj|tj| jjd}|d krx| |}| |}| |}|| | }	| 	|	}	| 
|	}	|	S )Nr   r   dtypedevice)sizer   r.   zeroslongr9   r%   r&   r'   r(   r-   )
r1   	input_idstoken_type_idsr   inputs_embedsinput_shapeZ
seq_lengthr&   r'   
embeddingsr5   r5   r6   forwardG   s     





zSqueezeBertEmbeddings.forward)NNNN__name__
__module____qualname____doc__r!   rB   __classcell__r5   r5   r3   r6   r   4   s   r   c                       s(   e Zd ZdZ fddZdd Z  ZS )MatMulWrapperz
    Wrapper for torch.matmul(). This makes flop-counting easier to implement. Note that if you directly call
    torch.matmul() in your code, the flop counter will typically ignore the flops of the matmul.
    c                    s   t    d S N)r    r!   r1   r3   r5   r6   r!   f   s    zMatMulWrapper.__init__c                 C   s   t ||S )a0  

        :param inputs: two torch tensors :return: matmul of these tensors

        Here are the typical dimensions found in BERT (the B is optional) mat1.shape: [B, <optional extra dims>, M, K]
        mat2.shape: [B, <optional extra dims>, K, N] output shape: [B, <optional extra dims>, M, N]
        )r.   matmul)r1   Zmat1Zmat2r5   r5   r6   rB   i   s    zMatMulWrapper.forwardrC   r5   r5   r3   r6   rI   `   s   rI   c                   @   s"   e Zd ZdZdddZdd ZdS )	SqueezeBertLayerNormz
    This is a nn.LayerNorm subclass that accepts NCW data layout and performs normalization in the C dimension.

    N = batch C = channels W = sequence length
    -q=c                 C   s   t jj| ||d d S )N)Znormalized_shaper   )r   r(   r!   )r1   r)   r   r5   r5   r6   r!   {   s    zSqueezeBertLayerNorm.__init__c                 C   s*   | ddd}tj| |}| dddS )Nr      r   )permuter   r(   rB   )r1   xr5   r5   r6   rB   ~   s    zSqueezeBertLayerNorm.forwardN)rN   )rD   rE   rF   rG   r!   rB   r5   r5   r5   r6   rM   t   s   
rM   c                       s(   e Zd ZdZ fddZdd Z  ZS )ConvDropoutLayerNormz8
    ConvDropoutLayerNorm: Conv, Dropout, LayerNorm
    c                    s8   t    tj||d|d| _t|| _t|| _d S Nr   Zin_channelsZout_channelsZkernel_sizegroups)	r    r!   r   Conv1dconv1drM   	layernormr+   r-   )r1   cincoutrU   dropout_probr3   r5   r6   r!      s    

zConvDropoutLayerNorm.__init__c                 C   s*   |  |}| |}|| }| |}|S rJ   )rW   r-   rX   )r1   hidden_statesZinput_tensorrQ   r5   r5   r6   rB      s
    


zConvDropoutLayerNorm.forwardrC   r5   r5   r3   r6   rR      s   rR   c                       s(   e Zd ZdZ fddZdd Z  ZS )ConvActivationz*
    ConvActivation: Conv, Activation
    c                    s,   t    tj||d|d| _t| | _d S rS   )r    r!   r   rV   rW   r
   act)r1   rY   rZ   rU   r^   r3   r5   r6   r!      s    
zConvActivation.__init__c                 C   s   |  |}| |S rJ   )rW   r^   )r1   rQ   outputr5   r5   r6   rB      s    
zConvActivation.forwardrC   r5   r5   r3   r6   r]      s   r]   c                       s>   e Zd Zd fdd	Zdd Zdd Zdd	 Zd
d Z  ZS )SqueezeBertSelfAttentionr   c                    s   t    ||j dkr0td| d|j d|j| _t||j | _| j| j | _tj||d|d| _	tj||d|d| _
tj||d|d| _t|j| _tjdd| _t | _t | _d	S )
z
        config = used for some things; ignored for others (work in progress...) cin = input channels = output channels
        groups = number of groups to use in conv1d layers
        r   zcin (z6) is not a multiple of the number of attention heads ()r   rT   r   dimN)r    r!   num_attention_heads
ValueErrorintattention_head_sizeall_head_sizer   rV   querykeyvaluer+   Zattention_probs_dropout_probr-   ZSoftmaxsoftmaxrI   	matmul_qk
matmul_qkv)r1   r2   rY   q_groupsk_groupsv_groupsr3   r5   r6   r!      s    
z!SqueezeBertSelfAttention.__init__c                 C   s:   |  d | j| j|  d f}|j| }|ddddS )z
        - input: [N, C, W]
        - output: [N, C1, W, C2] where C1 is the head index, and C2 is one head's contents
        r   r   r   r	   rO   )r:   rd   rg   viewrP   r1   rQ   Znew_x_shaper5   r5   r6   transpose_for_scores   s     
z-SqueezeBertSelfAttention.transpose_for_scoresc                 C   s.   |  d | j| j|  d f}|j| }|S )z
        - input: [N, C, W]
        - output: [N, C1, C2, W] where C1 is the head index, and C2 is one head's contents
        r   r   )r:   rd   rg   rr   rs   r5   r5   r6   transpose_key_for_scores   s     
z1SqueezeBertSelfAttention.transpose_key_for_scoresc                 C   s>   | dddd }| d | j| d f}|j| }|S )zE
        - input: [N, C1, W, C2]
        - output: [N, C, W]
        r   r   r	   rO   )rP   
contiguousr:   rh   rr   rs   r5   r5   r6   transpose_output   s    
z)SqueezeBertSelfAttention.transpose_outputc                 C   s   |  |}| |}| |}| |}| |}| |}	| ||}
|
t| j }
|
| }
| 	|
}| 
|}| ||	}| |}d|i}|r|
|d< |S )z
        expects hidden_states in [N, C, W] data layout.

        The attention_mask data layout is [N, W], and it does not need to be transposed.
        context_layerattention_score)ri   rj   rk   rt   ru   rm   mathsqrtrg   rl   r-   rn   rw   )r1   r\   attention_maskoutput_attentionsZmixed_query_layerZmixed_key_layerZmixed_value_layerZquery_layerZ	key_layerZvalue_layerry   Zattention_probsrx   resultr5   r5   r6   rB      s"    








z SqueezeBertSelfAttention.forward)r   r   r   )	rD   rE   rF   r!   rt   ru   rw   rB   rH   r5   r5   r3   r6   r`      s
   	

r`   c                       s$   e Zd Z fddZdd Z  ZS )SqueezeBertModulec                    s   t    |j}|j}|j}|j}t|||j|j|jd| _t	|||j
|jd| _t|||j|jd| _t	|||j|jd| _dS )a  
        - hidden_size = input chans = output chans for Q, K, V (they are all the same ... for now) = output chans for
          the module
        - intermediate_size = output chans for intermediate layer
        - groups = number of groups for all layers in the BertModule. (eventually we could change the interface to
          allow different groups for different layers)
        )r2   rY   ro   rp   rq   )rY   rZ   rU   r[   )rY   rZ   rU   r^   N)r    r!   r)   Zintermediate_sizer`   ro   rp   rq   	attentionrR   Zpost_attention_groupsr,   post_attentionr]   Zintermediate_groups
hidden_actintermediateZoutput_groupsr_   )r1   r2   Zc0c1c2c3r3   r5   r6   r!     s2    
          zSqueezeBertModule.__init__c           
      C   sT   |  |||}|d }| ||}| |}| ||}d|i}	|rP|d |	d< |	S )Nrx   feature_mapry   )r   r   r   r_   )
r1   r\   r|   r}   ZattZattention_outputZpost_attention_outputZintermediate_outputlayer_outputZoutput_dictr5   r5   r6   rB     s    
zSqueezeBertModule.forwardrD   rE   rF   r!   rB   rH   r5   r5   r3   r6   r     s   r   c                       s&   e Zd Z fddZdddZ  ZS )	SqueezeBertEncoderc                    sB   t     j jkstdt fddt jD | _	d S )NzIf you want embedding_size != intermediate hidden_size, please insert a Conv1d layer to adjust the number of channels before the first SqueezeBertModule.c                 3   s   | ]}t  V  qd S rJ   )r   ).0_r2   r5   r6   	<genexpr>5  s     z.SqueezeBertEncoder.__init__.<locals>.<genexpr>)
r    r!   r$   r)   AssertionErrorr   Z
ModuleListrangenum_hidden_layerslayersr0   r3   r   r6   r!   ,  s
    
zSqueezeBertEncoder.__init__NFTc                 C   s  |d krd}n| d t|kr&d}nd}|dks:td|ddd}|rPdnd }|r\dnd }	| jD ]V}
|r|ddd}||f7 }|ddd}|
|||}|d }|rf|	|d	 f7 }	qf|ddd}|r||f7 }|std
d |||	fD S t|||	dS )NTFzAhead_mask is not yet supported in the SqueezeBert implementation.r   rO   r   r5   r   ry   c                 s   s   | ]}|d k	r|V  qd S rJ   r5   )r   vr5   r5   r6   r   b  s      z-SqueezeBertEncoder.forward.<locals>.<genexpr>)last_hidden_stater\   
attentions)countlenr   rP   r   rB   tupler   )r1   r\   r|   	head_maskr}   output_hidden_statesreturn_dictZhead_mask_is_all_noneZall_hidden_statesZall_attentionslayerr   r5   r5   r6   rB   7  s8    	


  zSqueezeBertEncoder.forward)NNFFTr   r5   r5   r3   r6   r   +  s        r   c                       s$   e Zd Z fddZdd Z  ZS )SqueezeBertPoolerc                    s*   t    t|j|j| _t | _d S rJ   )r    r!   r   Linearr)   denseZTanh
activationr0   r3   r5   r6   r!   i  s    
zSqueezeBertPooler.__init__c                 C   s(   |d d df }|  |}| |}|S )Nr   )r   r   )r1   r\   Zfirst_token_tensorpooled_outputr5   r5   r6   rB   n  s    

zSqueezeBertPooler.forwardr   r5   r5   r3   r6   r   h  s   r   c                       s$   e Zd Z fddZdd Z  ZS )"SqueezeBertPredictionHeadTransformc                    sV   t    t|j|j| _t|jtr6t	|j | _
n|j| _
tj|j|jd| _d S )Nr   )r    r!   r   r   r)   r   
isinstancer   strr
   transform_act_fnr(   r*   r0   r3   r5   r6   r!   x  s    
z+SqueezeBertPredictionHeadTransform.__init__c                 C   s"   |  |}| |}| |}|S rJ   )r   r   r(   r1   r\   r5   r5   r6   rB     s    


z*SqueezeBertPredictionHeadTransform.forwardr   r5   r5   r3   r6   r   w  s   	r   c                       s$   e Zd Z fddZdd Z  ZS )SqueezeBertLMPredictionHeadc                    sL   t    t|| _tj|j|jdd| _t	t
|j| _| j| j_d S )NF)bias)r    r!   r   	transformr   r   r)   r#   decoder	Parameterr.   r;   r   r0   r3   r5   r6   r!     s
    

z$SqueezeBertLMPredictionHead.__init__c                 C   s   |  |}| |}|S rJ   )r   r   r   r5   r5   r6   rB     s    

z#SqueezeBertLMPredictionHead.forwardr   r5   r5   r3   r6   r     s   r   c                       s$   e Zd Z fddZdd Z  ZS )SqueezeBertOnlyMLMHeadc                    s   t    t|| _d S rJ   )r    r!   r   predictionsr0   r3   r5   r6   r!     s    
zSqueezeBertOnlyMLMHead.__init__c                 C   s   |  |}|S rJ   )r   )r1   sequence_outputprediction_scoresr5   r5   r6   rB     s    
zSqueezeBertOnlyMLMHead.forwardr   r5   r5   r3   r6   r     s   r   c                   @   s    e Zd ZdZeZdZdd ZdS )SqueezeBertPreTrainedModelz
    An abstract class to handle weights initialization and a simple interface for downloading and loading pretrained
    models.
    transformerc                 C   s   t |tjtjfr@|jjjd| jjd |j	dk	r|j	j
  ndt |tjr|jjjd| jjd |jdk	r|jj|j 
  n$t |tr|j	j
  |jjd dS )zInitialize the weightsg        )ZmeanZstdNg      ?)r   r   r   rV   weightdataZnormal_r2   Zinitializer_ranger   Zzero_r"   r   rM   Zfill_)r1   moduler5   r5   r6   _init_weights  s    


z(SqueezeBertPreTrainedModel._init_weightsN)rD   rE   rF   rG   r   config_classZbase_model_prefixr   r5   r5   r5   r6   r     s   r   aw  

    The SqueezeBERT model was proposed in [SqueezeBERT: What can computer vision teach NLP about efficient neural
    networks?](https://arxiv.org/abs/2006.11316) by Forrest N. Iandola, Albert E. Shaw, Ravi Krishna, and Kurt W.
    Keutzer

    This model inherits from [`PreTrainedModel`]. Check the superclass documentation for the generic methods the
    library implements for all its model (such as downloading or saving, resizing the input embeddings, pruning heads
    etc.)

    This model is also a PyTorch [torch.nn.Module](https://pytorch.org/docs/stable/nn.html#torch.nn.Module) subclass.
    Use it as a regular PyTorch Module and refer to the PyTorch documentation for all matter related to general usage
    and behavior.

    For best results finetuning SqueezeBERT on text classification tasks, it is recommended to use the
    *squeezebert/squeezebert-mnli-headless* checkpoint as a starting point.

    Parameters:
        config ([`SqueezeBertConfig`]): Model configuration class with all the parameters of the model.
            Initializing with a config file does not load the weights associated with the model, only the
            configuration. Check out the [`~PreTrainedModel.from_pretrained`] method to load the model weights.

    Hierarchy:

    ```
    Internal class hierarchy:
    SqueezeBertModel
        SqueezeBertEncoder
            SqueezeBertModule
            SqueezeBertSelfAttention
                ConvActivation
                ConvDropoutLayerNorm
    ```

    Data layouts:

    ```
    Input data is in [batch, sequence_length, hidden_size] format.

    Data inside the encoder is in [batch, hidden_size, sequence_length] format. But, if `output_hidden_states == True`, the data from inside the encoder is returned in [batch, sequence_length, hidden_size] format.

    The final output of the encoder is in [batch, sequence_length, hidden_size] format.
    ```
a5
  
    Args:
        input_ids (`torch.LongTensor` of shape `({0})`):
            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)
        attention_mask (`torch.FloatTensor` of shape `({0})`, *optional*):
            Mask to avoid performing attention on padding token indices. Mask values selected in `[0, 1]`:

            - 1 for tokens that are **not masked**,
            - 0 for tokens that are **masked**.

            [What are attention masks?](../glossary#attention-mask)
        token_type_ids (`torch.LongTensor` of shape `({0})`, *optional*):
            Segment token indices to indicate first and second portions of the inputs. Indices are selected in `[0,
            1]`:

            - 0 corresponds to a *sentence A* token,
            - 1 corresponds to a *sentence B* token.

            [What are token type IDs?](../glossary#token-type-ids)
        position_ids (`torch.LongTensor` of shape `({0})`, *optional*):
            Indices of positions of each input sequence tokens in the position embeddings. Selected in the range `[0,
            config.max_position_embeddings - 1]`.

            [What are position IDs?](../glossary#position-ids)
        head_mask (`torch.FloatTensor` of shape `(num_heads,)` or `(num_layers, num_heads)`, *optional*):
            Mask to nullify selected heads of the self-attention modules. Mask values selected in `[0, 1]`:

            - 1 indicates the head is **not masked**,
            - 0 indicates the head is **masked**.

        inputs_embeds (`torch.FloatTensor` of shape `({0}, 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.
        output_attentions (`bool`, *optional*):
            Whether or not to return the attentions tensors of all attention layers. See `attentions` under returned
            tensors for more detail.
        output_hidden_states (`bool`, *optional*):
            Whether or not to return the hidden states of all layers. See `hidden_states` under returned tensors for
            more detail.
        return_dict (`bool`, *optional*):
            Whether or not to return a [`~utils.ModelOutput`] instead of a plain tuple.
zeThe bare SqueezeBERT Model transformer outputting raw hidden-states without any specific head on top.c                       s   e Zd Z fddZdd Zdd Zdd Zee	d	e
eeed
deej eej eej eej eej eej ee ee ee eeef d
ddZ  ZS )SqueezeBertModelc                    s6   t  | t|| _t|| _t|| _|   d S rJ   )	r    r!   r   rA   r   encoderr   pooler	post_initr0   r3   r5   r6   r!   $  s
    


zSqueezeBertModel.__init__c                 C   s   | j jS rJ   rA   r%   rK   r5   r5   r6   get_input_embeddings.  s    z%SqueezeBertModel.get_input_embeddingsc                 C   s   || j _d S rJ   r   r1   Znew_embeddingsr5   r5   r6   set_input_embeddings1  s    z%SqueezeBertModel.set_input_embeddingsc                 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   Zprune_heads)r1   Zheads_to_pruner   Zheadsr5   r5   r6   _prune_heads4  s    zSqueezeBertModel._prune_headsbatch_size, sequence_length
checkpointoutput_typer   N)
r=   r|   r>   r   r   r?   r}   r   r   returnc
                 C   s^  |d k	r|n| j j}|d k	r |n| j j}|	d k	r4|	n| j j}	|d k	rV|d k	rVtdn@|d k	rt| || | }
n"|d k	r| d d }
ntd|d k	r|jn|j}|d krtj	|
|d}|d krtj
|
tj|d}| ||
}| || j j}| j||||d}| j||||||	d}|d }| |}|	sJ||f|d	d   S t|||j|jd
S )NzDYou cannot specify both input_ids and inputs_embeds at the same timer   z5You have to specify either input_ids or inputs_embeds)r9   r7   )r=   r   r>   r?   )r\   r|   r   r}   r   r   r   r   )r   Zpooler_outputr\   r   )r2   r}   r   use_return_dictre   Z%warn_if_padding_and_no_attention_maskr:   r9   r.   Zonesr;   r<   Zget_extended_attention_maskZget_head_maskr   rA   r   r   r   r\   r   )r1   r=   r|   r>   r   r   r?   r}   r   r   r@   r9   Zextended_attention_maskZembedding_outputZencoder_outputsr   r   r5   r5   r6   rB   <  sV    

   
zSqueezeBertModel.forward)	NNNNNNNNN)rD   rE   rF   r!   r   r   r   r   SQUEEZEBERT_INPUTS_DOCSTRINGformatr   _CHECKPOINT_FOR_DOCr   _CONFIG_FOR_DOCr   r.   TensorZFloatTensorboolr   r   rB   rH   r5   r5   r3   r6   r     s>   
         
r   z9SqueezeBERT Model with a `language modeling` head on top.c                       s   e Zd ZddgZ fddZdd Zdd Zee	d	e
eeed
deej eej eej eej eej eej eej ee ee ee eeef dddZ  ZS )SqueezeBertForMaskedLMzcls.predictions.decoder.weightzcls.predictions.decoder.biasc                    s,   t  | t|| _t|| _|   d S rJ   )r    r!   r   r   r   clsr   r0   r3   r5   r6   r!     s    

zSqueezeBertForMaskedLM.__init__c                 C   s
   | j jjS rJ   r   r   r   rK   r5   r5   r6   get_output_embeddings  s    z,SqueezeBertForMaskedLM.get_output_embeddingsc                 C   s   || j j_d S rJ   r   r   r5   r5   r6   set_output_embeddings  s    z,SqueezeBertForMaskedLM.set_output_embeddingsr   r   Nr=   r|   r>   r   r   r?   labelsr}   r   r   r   c                 C   s   |
dk	r|
n| j j}
| j||||||||	|
d	}|d }| |}d}|dk	rpt }||d| j j|d}|
s|f|dd  }|dk	r|f| S |S t|||j|j	dS )a  
        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r|   r>   r   r   r?   r}   r   r   r   r   rO   losslogitsr\   r   )
r2   r   r   r   r   rr   r#   r   r\   r   )r1   r=   r|   r>   r   r   r?   r   r}   r   r   outputsr   r   Zmasked_lm_lossloss_fctr_   r5   r5   r6   rB     s6    
zSqueezeBertForMaskedLM.forward)
NNNNNNNNNN)rD   rE   rF   Z_tied_weights_keysr!   r   r   r   r   r   r   r   r   r   r   r.   r   r   r   r   rB   rH   r5   r5   r3   r6   r     sB   	          
r   z
    SqueezeBERT 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                       s   e Zd Z fddZeedeee	e
dd	eej eej eej eej eej eej eej ee ee ee eee	f dddZ  ZS )
$SqueezeBertForSequenceClassificationc                    sR   t  | |j| _|| _t|| _t|j| _	t
|j| jj| _|   d S rJ   )r    r!   
num_labelsr2   r   r   r   r+   r,   r-   r   r)   
classifierr   r0   r3   r5   r6   r!     s    
z-SqueezeBertForSequenceClassification.__init__r   r   Nr   c                 C   s|  |
dk	r|
n| j j}
| j||||||||	|
d	}|d }| |}| |}d}|dk	r8| j jdkr| jdkrzd| j _n4| 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
|||}nN| j jdkrt }||d| j|d}n| j jdkr8t }|||}|
sh|f|dd  }|dk	rd|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   Z
regressionZsingle_label_classificationZmulti_label_classificationr   rO   r   )r2   r   r   r-   r   Zproblem_typer   r8   r.   r<   rf   r   squeezer   rr   r   r   r\   r   )r1   r=   r|   r>   r   r   r?   r   r}   r   r   r   r   r   r   r   r_   r5   r5   r6   rB     sV    




"


z,SqueezeBertForSequenceClassification.forward)
NNNNNNNNNN)rD   rE   rF   r!   r   r   r   r   r   r   r   r   r.   r   r   r   r   rB   rH   r5   r5   r3   r6   r     s<             
r   z
    SqueezeBERT Model with a multiple choice classification head on top (a linear layer on top of the pooled output and
    a softmax) e.g. for RocStories/SWAG tasks.
    c                       s   e Zd Z fddZeedeee	e
dd	eej eej eej eej eej eej eej ee ee ee eee	f dddZ  ZS )
SqueezeBertForMultipleChoicec                    s@   t  | t|| _t|j| _t|j	d| _
|   d S )Nr   )r    r!   r   r   r   r+   r,   r-   r   r)   r   r   r0   r3   r5   r6   r!   ?  s
    
z%SqueezeBertForMultipleChoice.__init__z(batch_size, num_choices, sequence_lengthr   Nr   c                 C   st  |
dk	r|
n| j j}
|dk	r&|jd n|jd }|dk	rJ|d|dnd}|dk	rh|d|dnd}|dk	r|d|dnd}|dk	r|d|dnd}|dk	r|d|d|dnd}| j||||||||	|
d	}|d }| |}| |}|d|}d}|dk	r0t }|||}|
s`|f|dd  }|dk	r\|f| S |S t	|||j
|jdS )aJ  
        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)
        Nr   r   r   rO   r   )r2   r   shaperr   r:   r   r-   r   r   r   r\   r   )r1   r=   r|   r>   r   r   r?   r   r}   r   r   Znum_choicesr   r   r   Zreshaped_logitsr   r   r_   r5   r5   r6   rB   I  sL    



z$SqueezeBertForMultipleChoice.forward)
NNNNNNNNNN)rD   rE   rF   r!   r   r   r   r   r   r   r   r   r.   r   r   r   r   rB   rH   r5   r5   r3   r6   r   7  s@   
          
r   z
    SqueezeBERT Model with a token classification head on top (a linear layer on top of the hidden-states output) e.g.
    for Named-Entity-Recognition (NER) tasks.
    c                       s   e Zd Z fddZeedeee	e
dd	eej eej eej eej eej eej eej ee ee ee eee	f dddZ  ZS )
!SqueezeBertForTokenClassificationc                    sJ   t  | |j| _t|| _t|j| _t	|j
|j| _|   d S rJ   )r    r!   r   r   r   r   r+   r,   r-   r   r)   r   r   r0   r3   r5   r6   r!     s    
z*SqueezeBertForTokenClassification.__init__r   r   Nr   c                 C   s   |
dk	r|
n| j j}
| j||||||||	|
d	}|d }| |}| |}d}|dk	rxt }||d| j|d}|
s|f|dd  }|dk	r|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]`.
        Nr   r   r   rO   r   )r2   r   r   r-   r   r   rr   r   r   r\   r   )r1   r=   r|   r>   r   r   r?   r   r}   r   r   r   r   r   r   r   r_   r5   r5   r6   rB     s8    

z)SqueezeBertForTokenClassification.forward)
NNNNNNNNNN)rD   rE   rF   r!   r   r   r   r   r   r   r   r   r.   r   r   r   r   rB   rH   r5   r5   r3   r6   r     s<             
r   z
     SqueezeBERT Model with a span classification head on top for extractive question-answering tasks like SQuAD (a
     linear layers on top of the hidden-states output to compute `span start logits` and `span end logits`).
     c                       s   e Zd Z fddZeedeee	e
dd	eej eej eej eej eej eej eej eej ee ee ee eee	f dddZ  ZS )
SqueezeBertForQuestionAnsweringc                    s<   t  | |j| _t|| _t|j|j| _| 	  d S rJ   )
r    r!   r   r   r   r   r   r)   
qa_outputsr   r0   r3   r5   r6   r!     s
    
z(SqueezeBertForQuestionAnswering.__init__r   r   N)r=   r|   r>   r   r   r?   start_positionsend_positionsr}   r   r   r   c                 C   sP  |dk	r|n| j j}| j|||||||	|
|d	}|d }| |}|jddd\}}|d }|d }d}|dk	r|dk	rt| dkr|d}t| dkr|d}|d}|	d|}|	d|}t
|d}|||}|||}|| d }|s:||f|dd  }|dk	r6|f| S |S t||||j|jd	S )
a  
        start_positions (`torch.LongTensor` of shape `(batch_size,)`, *optional*):
            Labels for position (index) of the start of the labelled span for computing the token classification loss.
            Positions are clamped to the length of the sequence (*sequence_length*). Position outside of the sequence
            are not taken into account for computing the loss.
        end_positions (`torch.LongTensor` of shape `(batch_size,)`, *optional*):
            Labels for position (index) of the end of the labelled span for computing the token classification loss.
            Positions are clamped to the length of the sequence (*sequence_length*). Position outside of the sequence
            are not taken into account for computing the loss.
        Nr   r   r   r   rb   )Zignore_indexrO   )r   start_logits
end_logitsr\   r   )r2   r   r   r   splitr   rv   r   r:   clampr   r   r\   r   )r1   r=   r|   r>   r   r   r?   r   r   r}   r   r   r   r   r   r   r   Z
total_lossZignored_indexr   Z
start_lossZend_lossr_   r5   r5   r6   rB     sP    






z'SqueezeBertForQuestionAnswering.forward)NNNNNNNNNNN)rD   rE   rF   r!   r   r   r   r   r   r   r   r   r.   r   r   r   r   rB   rH   r5   r5   r3   r6   r     s@   
           
r   )<rG   rz   typingr   r   r   r.   r   Ztorch.nnr   r   r   Zactivationsr
   Zmodeling_outputsr   r   r   r   r   r   r   Zmodeling_utilsr   utilsr   r   r   r   Zconfiguration_squeezebertr   Z
get_loggerrD   loggerr   r   Z)SQUEEZEBERT_PRETRAINED_MODEL_ARCHIVE_LISTModuler   rI   r(   rM   rR   r]   r`   r   r   r   r   r   r   r   ZSQUEEZEBERT_START_DOCSTRINGr   r   r   r   r   r   r   r5   r5   r5   r6   <module>   sv   $	
,Z*=
-2cM\VG