U
    4Af3                     @   sz  d Z ddlZddl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mZmZmZmZmZ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  ddl!m"Z" ddl#m$Z$m%Z%m&Z&m'Z'm(Z(m)Z) e *e+Z,dZ-dZ.G dd dej/Z0G dd dej/Z1G dd dej/Z2G dd dej/Z3G dd dej/Z4G dd dej/Z5G dd dej/Z6G dd  d ej/Z7G d!d" d"ej/Z8G d#d$ d$eZ9d%Z:d&Z;ed'e:G d(d) d)e9Z<ed*e:G d+d, d,e9Z=G d-d. d.ej/Z>ed/e:G d0d1 d1e9Z?ed2e:G d3d4 d4e9Z@ed5e:G d6d7 d7e9ZAG d8d9 d9ej/ZBed:e:G d;d< d<e9ZCd?d=d>ZDdS )@zPyTorch I-BERT model.    N)OptionalTupleUnion)nn)BCEWithLogitsLossCrossEntropyLossMSELoss   )gelu))BaseModelOutputWithPastAndCrossAttentions,BaseModelOutputWithPoolingAndCrossAttentionsMaskedLMOutputMultipleChoiceModelOutputQuestionAnsweringModelOutputSequenceClassifierOutputTokenClassifierOutput)PreTrainedModel) find_pruneable_heads_and_indicesprune_linear_layer)add_code_sample_docstringsadd_start_docstrings%add_start_docstrings_to_model_forwardlogging   )IBertConfig)IntGELUIntLayerNorm
IntSoftmaxQuantActQuantEmbeddingQuantLinearzkssteven/ibert-roberta-baser   c                       s2   e Zd ZdZ fddZd
ddZdd	 Z  ZS )IBertEmbeddingszV
    Same as BertEmbeddings with a tiny tweak for positional embeddings indexing.
    c                    s   t    |j| _d| _d| _d| _d| _d| _t|j	|j
|j| j| jd| _t|j|j
| j| jd| _| jdt|jdd	d
 t|dd| _|j| _t|j|j
| j| j| jd| _t| j| jd| _t| j| jd| _t|j
|j| j| j|jd| _t| j| jd| _t !|j"| _#d S )N             )padding_idx
weight_bit
quant_mode)r'   r(   position_ids)r   F)
persistentposition_embedding_typeabsoluter(   epsZ
output_bitr(   force_dequant)$super__init__r(   Zembedding_bitZembedding_act_bitact_bitln_input_bitln_output_bitr   
vocab_sizehidden_sizeZpad_token_idword_embeddingsZtype_vocab_sizetoken_type_embeddingsZregister_buffertorcharangeZmax_position_embeddingsexpandgetattrr,   r&   position_embeddingsr   embeddings_act1Zembeddings_act2r   layer_norm_epsr1   	LayerNormoutput_activationr   Dropouthidden_dropout_probdropoutselfconfig	__class__ L/tmp/pip-unpacked-wheel-zw5xktn0/transformers/models/ibert/modeling_ibert.pyr3   8   sZ    
     	zIBertEmbeddings.__init__Nr   c                 C   s  |d kr2|d k	r(t || j||j}n
| |}|d k	rD| }n| d d }|d krrtj|tj| j	jd}|d kr| 
|\}}nd }| |\}}	| j||||	d\}
}| jdkr| |\}}| j|
|||d\}
}| |
|\}
}| |
}
| |
|\}
}|
|fS )Nr*   dtypedeviceidentityZidentity_scaling_factorr-   )"create_position_ids_from_input_idsr&   torP   &create_position_ids_from_inputs_embedssizer;   zeroslongr)   r9   r:   r@   r,   r?   rB   rF   rC   )rH   	input_idstoken_type_idsr)   inputs_embedspast_key_values_lengthinput_shapeZinputs_embeds_scaling_factorr:   Z$token_type_embeddings_scaling_factor
embeddingsZembeddings_scaling_factorr?   Z"position_embeddings_scaling_factorrL   rL   rM   forwardl   sJ      





zIBertEmbeddings.forwardc                 C   sN   |  dd }|d }tj| jd || j d tj|jd}|d|S )z
        We are provided embeddings directly. We cannot infer which are padded so just generate sequential position ids.

        Args:
            inputs_embeds: torch.Tensor

        Returns: torch.Tensor
        Nr*   r   rN   r   )rV   r;   r<   r&   rX   rP   Z	unsqueezer=   )rH   r[   r]   Zsequence_lengthr)   rL   rL   rM   rU      s    	   z6IBertEmbeddings.create_position_ids_from_inputs_embeds)NNNNr   )__name__
__module____qualname____doc__r3   r_   rU   __classcell__rL   rL   rJ   rM   r!   3   s   5         
/r!   c                       s.   e Zd Z fddZdd Zd	ddZ  ZS )
IBertSelfAttentionc              	      sx  t    |j|j dkr>t|ds>td|j d|j d|j| _d| _d| _d| _	|j| _t
|j|j | _| j| j | _t|j| jd| j| j| jdd	| _t|j| jd| j| j| jdd	| _t|j| jd| j| j| jdd	| _t| j	| jd
| _t| j	| jd
| _t| j	| jd
| _t| j	| jd
| _t|j| _t|dd| _| jdkr^tdt| j	| j|jd| _d S )Nr   Zembedding_sizezThe hidden size (z6) is not a multiple of the number of attention heads ()r"   r%   Tbiasr'   bias_bitr(   Zper_channelr.   r,   r-   zDI-BERT only supports 'absolute' for `config.position_embedding_type`r(   r1   )r2   r3   r8   num_attention_headshasattr
ValueErrorr(   r'   ri   r4   intattention_head_sizeall_head_sizer    querykeyvaluer   query_activationkey_activationvalue_activationrC   r   rD   Zattention_probs_dropout_probrF   r>   r,   r   r1   softmaxrG   rJ   rL   rM   r3      s`    
		zIBertSelfAttention.__init__c                 C   s6   |  d d | j| jf }|j| }|ddddS )Nr*   r      r   r	   )rV   rk   ro   viewpermute)rH   xZnew_x_shaperL   rL   rM   transpose_for_scores   s    
z'IBertSelfAttention.transpose_for_scoresNFc                 C   s  |  ||\}}| ||\}}	| ||\}
}| ||\}}| ||	\}}| |
|\}}| |}| |}| |}t||	dd}t
| j}|| }| jr|| | }nd }|d k	r|| }| ||\}}| |}|d k	r|| }t||}|d k	r|| }nd }|dddd }| d d | jf }|j| }| ||\}}|rp||fn|f}|r||fn|f}||fS )Nr*   r   rx   r   r	   )rq   rr   rs   rt   ru   rv   r|   r;   matmulZ	transposemathsqrtro   r(   rw   rF   rz   
contiguousrV   rp   ry   rC   )rH   hidden_stateshidden_states_scaling_factorattention_mask	head_maskoutput_attentionsZmixed_query_layerZ mixed_query_layer_scaling_factorZmixed_key_layerZmixed_key_layer_scaling_factorZmixed_value_layerZ mixed_value_layer_scaling_factorZquery_layerZquery_layer_scaling_factorZ	key_layerZkey_layer_scaling_factorZvalue_layerZvalue_layer_scaling_factorZattention_scoresZscaleZattention_scores_scaling_factorZattention_probsZattention_probs_scaling_factorZcontext_layerZcontext_layer_scaling_factorZnew_context_layer_shapeoutputsZoutput_scaling_factorrL   rL   rM   r_      s^    	  


 



 zIBertSelfAttention.forward)NNF)r`   ra   rb   r3   r|   r_   rd   rL   rL   rJ   rM   re      s   :	   re   c                       s$   e Zd Z fddZdd Z  ZS )IBertSelfOutputc              	      s   t    |j| _d| _d| _d| _d| _d| _t|j	|j	d| j| j| jdd| _
t| j| jd| _t|j	|j| j| j|jd| _t| j| jd| _t|j| _d S Nr"   r%   r$   Trg   r.   r/   )r2   r3   r(   r4   r'   ri   r5   r6   r    r8   denser   ln_input_actr   rA   r1   rB   rC   r   rD   rE   rF   rG   rJ   rL   rM   r3   <  s4    
	zIBertSelfOutput.__init__c                 C   sX   |  ||\}}| |}| j||||d\}}| ||\}}| ||\}}||fS NrQ   r   rF   r   rB   rC   rH   r   r   Zinput_tensorZinput_tensor_scaling_factorrL   rL   rM   r_   Y  s    

 zIBertSelfOutput.forwardr`   ra   rb   r3   r_   rd   rL   rL   rJ   rM   r   ;  s   r   c                       s.   e Zd Z fddZdd Zd	ddZ  ZS )
IBertAttentionc                    s2   t    |j| _t|| _t|| _t | _d S N)	r2   r3   r(   re   rH   r   outputsetpruned_headsrG   rJ   rL   rM   r3   k  s
    


zIBertAttention.__init__c                 C   s   t |dkrd S t|| jj| jj| j\}}t| jj|| j_t| jj|| j_t| jj	|| j_	t| j
j|dd| j
_| jjt | | j_| jj| jj | j_| j|| _d S )Nr   r   Zdim)lenr   rH   rk   ro   r   r   rq   rr   rs   r   r   rp   union)rH   headsindexrL   rL   rM   prune_headsr  s       zIBertAttention.prune_headsNFc                 C   s^   |  |||||\}}| |d |d ||\}}	|f|dd   }
|	f|dd   }|
|fS )Nr   r   )rH   r   )rH   r   r   r   r   r   Zself_outputsZself_outputs_scaling_factorattention_outputattention_output_scaling_factorr   Zoutputs_scaling_factorrL   rL   rM   r_     s        zIBertAttention.forward)NNF)r`   ra   rb   r3   r   r_   rd   rL   rL   rJ   rM   r   j  s      r   c                       s$   e Zd Z fddZdd Z  ZS )IBertIntermediatec              	      s   t    |j| _d| _d| _d| _t|j|jd| j| j| jdd| _	|j
dkrXtdt| j|jd| _t| j| jd| _d S )	Nr"   r%   Trg   r
   z3I-BERT only supports 'gelu' for `config.hidden_act`rj   r.   )r2   r3   r(   r4   r'   ri   r    r8   intermediate_sizer   Z
hidden_actrm   r   r1   intermediate_act_fnr   rC   rG   rJ   rL   rM   r3     s$    
	
zIBertIntermediate.__init__c                 C   s8   |  ||\}}| ||\}}| ||\}}||fS r   )r   r   rC   )rH   r   r   rL   rL   rM   r_     s      zIBertIntermediate.forwardr   rL   rL   rJ   rM   r     s   r   c                       s$   e Zd Z fddZdd Z  ZS )IBertOutputc              	      s   t    |j| _d| _d| _d| _d| _d| _t|j	|j
d| j| j| jdd| _t| j| jd| _t|j
|j| j| j|jd| _t| j| jd| _t|j| _d S r   )r2   r3   r(   r4   r'   ri   r5   r6   r    r   r8   r   r   r   r   rA   r1   rB   rC   r   rD   rE   rF   rG   rJ   rL   rM   r3     s4    
	zIBertOutput.__init__c                 C   sX   |  ||\}}| |}| j||||d\}}| ||\}}| ||\}}||fS r   r   r   rL   rL   rM   r_     s    

 zIBertOutput.forwardr   rL   rL   rJ   rM   r     s   r   c                       s.   e Zd Z fddZd	ddZdd Z  ZS )

IBertLayerc                    sd   t    |j| _d| _d| _t|| _t|| _t	|| _
t| j| jd| _t| j| jd| _d S )Nr"   r   r.   )r2   r3   r(   r4   Zseq_len_dimr   	attentionr   intermediater   r   r   pre_intermediate_actpre_output_actrG   rJ   rL   rM   r3     s    



zIBertLayer.__init__NFc                 C   sR   | j |||||d\}}|d }|d }	|dd  }
| ||	\}}|f|
 }
|
S )N)r   r   r   )r   feed_forward_chunk)rH   r   r   r   r   r   Zself_attention_outputsZ%self_attention_outputs_scaling_factorr   r   r   layer_outputlayer_output_scaling_factorrL   rL   rM   r_     s     
 
zIBertLayer.forwardc                 C   sL   |  ||\}}| ||\}}| ||\}}| ||||\}}||fS r   )r   r   r   r   )rH   r   r   Zintermediate_outputZ"intermediate_output_scaling_factorr   r   rL   rL   rM   r     s&          zIBertLayer.feed_forward_chunk)NNF)r`   ra   rb   r3   r_   r   rd   rL   rL   rJ   rM   r     s      
r   c                       s&   e Zd Z fddZdddZ  ZS )	IBertEncoderc                    s<   t     | _ j| _t fddt jD | _d S )Nc                    s   g | ]}t  qS rL   )r   ).0_rI   rL   rM   
<listcomp>+  s     z)IBertEncoder.__init__.<locals>.<listcomp>)	r2   r3   rI   r(   r   Z
ModuleListrangenum_hidden_layerslayerrG   rJ   r   rM   r3   '  s    
zIBertEncoder.__init__NFTc                 C   s   |rdnd }|rdnd }	d }
d }t | jD ]T\}}|r@||f }|d k	rP|| nd }||||||}|d }|r*|	|d f }	q*|r||f }|stdd ||||	|
fD S t||||	|
dS )NrL   r   r   c                 s   s   | ]}|d k	r|V  qd S r   rL   )r   vrL   rL   rM   	<genexpr>R  s   z'IBertEncoder.forward.<locals>.<genexpr>)last_hidden_statepast_key_valuesr   
attentionscross_attentions)	enumerater   tupler   )rH   r   r   r   r   r   output_hidden_statesreturn_dictZall_hidden_statesZall_self_attentionsZall_cross_attentionsZnext_decoder_cacheiZlayer_moduleZlayer_head_maskZlayer_outputsrL   rL   rM   r_   -  sH    


zIBertEncoder.forward)NNFFTr   rL   rL   rJ   rM   r   &  s   
     r   c                       s$   e Zd Z fddZdd Z  ZS )IBertPoolerc                    s2   t    |j| _t|j|j| _t | _d S r   )	r2   r3   r(   r   Linearr8   r   ZTanh
activationrG   rJ   rL   rM   r3   g  s    
zIBertPooler.__init__c                 C   s(   |d d df }|  |}| |}|S Nr   )r   r   )rH   r   Zfirst_token_tensorpooled_outputrL   rL   rM   r_   m  s    

zIBertPooler.forwardr   rL   rL   rJ   rM   r   f  s   r   c                   @   s*   e Zd ZdZeZdZdd ZdddZdS )	IBertPreTrainedModelz
    An abstract class to handle weights initialization and a simple interface for downloading and loading pretrained
    models.
    ibertc                 C   s   t |ttjfr>|jjjd| jjd |j	dk	r|j	j
  nnt |ttjfr|jjjd| jjd |jdk	r|jj|j 
  n*t |ttjfr|j	j
  |jjd dS )zInitialize the weightsg        )ZmeanZstdNg      ?)
isinstancer    r   r   ZweightdataZnormal_rI   Zinitializer_rangerh   Zzero_r   Z	Embeddingr&   r   rB   Zfill_)rH   modulerL   rL   rM   _init_weights  s    

z"IBertPreTrainedModel._init_weightsNc                 C   s   t dd S )Nz6`resize_token_embeddings` is not supported for I-BERT.)NotImplementedError)rH   Znew_num_tokensrL   rL   rM   resize_token_embeddings  s    z,IBertPreTrainedModel.resize_token_embeddings)N)	r`   ra   rb   rc   r   config_classZbase_model_prefixr   r   rL   rL   rL   rM   r   v  s
   r   a?  

    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.

    Parameters:
        config ([`IBertConfig`]): 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.
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.
z`The bare I-BERT Model transformer outputting raw hidden-states without any specific head on top.c                       s   e Zd ZdZd 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ej f d
ddZ  ZS )
IBertModela  

    The model can behave as an encoder (with only self-attention) as well as a decoder, in which case a layer of
    cross-attention is added between the self-attention layers, following the architecture described in [Attention is
    all you need](https://arxiv.org/abs/1706.03762) by Ashish Vaswani, Noam Shazeer, Niki Parmar, Jakob Uszkoreit,
    Llion Jones, Aidan N. Gomez, Lukasz Kaiser and Illia Polosukhin.

    Tc                    sL   t  | || _|j| _t|| _t|| _|r:t|nd | _	| 
  d S r   )r2   r3   rI   r(   r!   r^   r   encoderr   pooler	post_init)rH   rI   add_pooling_layerrJ   rL   rM   r3     s    

zIBertModel.__init__c                 C   s   | j jS r   r^   r9   rH   rL   rL   rM   get_input_embeddings  s    zIBertModel.get_input_embeddingsc                 C   s   || j _d S r   r   )rH   rs   rL   rL   rM   set_input_embeddings  s    zIBertModel.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   r   )rH   Zheads_to_pruner   r   rL   rL   rM   _prune_heads  s    zIBertModel._prune_headsbatch_size, sequence_length
checkpointoutput_typer   N)
rY   r   rZ   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	||f|d}|d krtj
|
tj|d}| ||
}| || j j}| j||||d\}}| j|||||||	d}|d }| jd k	rN| |nd }|	sl||f|d	d   S t|||j|j|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)rP   rN   )rY   r)   rZ   r[   )r   r   r   r   r   r   r   )r   Zpooler_outputr   r   r   r   )rI   r   r   use_return_dictrm   Z%warn_if_padding_and_no_attention_maskrV   rP   r;   ZonesrW   rX   Zget_extended_attention_maskZget_head_maskr   r^   r   r   r   r   r   r   r   )rH   rY   r   rZ   r)   r   r[   r   r   r   r]   Z
batch_sizeZ
seq_lengthrP   Zextended_attention_maskZembedding_outputZembedding_output_scaling_factorZencoder_outputssequence_outputr   rL   rL   rM   r_     s^    


	zIBertModel.forward)T)	NNNNNNNNN)r`   ra   rb   rc   r3   r   r   r   r   IBERT_INPUTS_DOCSTRINGformatr   _CHECKPOINT_FOR_DOCr   _CONFIG_FOR_DOCr   r;   
LongTensorFloatTensorboolr   r   r_   rd   rL   rL   rJ   rM   r     s@   	         r   z4I-BERT 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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ej f dddZ  ZS )IBertForMaskedLMzlm_head.decoder.biaszlm_head.decoder.weightc                    s0   t  | t|dd| _t|| _|   d S NF)r   )r2   r3   r   r   IBertLMHeadlm_headr   rG   rJ   rL   rM   r3   V  s    
zIBertForMaskedLM.__init__c                 C   s   | j jS r   )r   decoderr   rL   rL   rM   get_output_embeddings_  s    z&IBertForMaskedLM.get_output_embeddingsc                 C   s   || j _|j| j _d S r   )r   r   rh   )rH   Znew_embeddingsrL   rL   rM   set_output_embeddingsb  s    z&IBertForMaskedLM.set_output_embeddingsr   z<mask>)r   r   r   maskNrY   r   rZ   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]`
        kwargs (`Dict[str, any]`, *optional*, defaults to `{}`):
            Used to hide legacy arguments that have been deprecated.
        Nr   rZ   r)   r   r[   r   r   r   r   r*   rx   losslogitsr   r   )
rI   r   r   r   r   ry   r7   r   r   r   )rH   rY   r   rZ   r)   r   r[   r   r   r   r   r   r   Zprediction_scoresZmasked_lm_lossloss_fctr   rL   rL   rM   r_   f  s6    
zIBertForMaskedLM.forward)
NNNNNNNNNN)r`   ra   rb   Z_tied_weights_keysr3   r   r   r   r   r   r   r   r   r   r   r;   r   r   r   r   r   r_   rd   rL   rL   rJ   rM   r   R  sD   	          r   c                       s6   e Zd ZdZ fddZdd Zdddd	Z  ZS )
r   z)I-BERT Head for masked language modeling.c                    sd   t    t|j|j| _tj|j|jd| _t|j|j	| _
tt|j	| _| j| j
_d S )N)r0   )r2   r3   r   r   r8   r   rB   rA   
layer_normr7   r   	Parameterr;   rW   rh   rG   rJ   rL   rM   r3     s    
zIBertLMHead.__init__c                 K   s*   |  |}t|}| |}| |}|S r   )r   r
   r   r   )rH   featureskwargsr{   rL   rL   rM   r_     s
    


zIBertLMHead.forwardN)r   c                 C   s*   | j jjjdkr| j| j _n
| j j| _d S )Nmeta)r   rh   rP   typer   rL   rL   rM   _tie_weights  s    zIBertLMHead._tie_weights)r`   ra   rb   rc   r3   r_   r   rd   rL   rL   rJ   rM   r     s   	
r   z
    I-BERT 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ej f dddZ  ZS )
IBertForSequenceClassificationc                    s8   t  | |j| _t|dd| _t|| _|   d S r   )r2   r3   
num_labelsr   r   IBertClassificationHead
classifierr   rG   rJ   rL   rM   r3     s
    
z'IBertForSequenceClassification.__init__r   r   Nr   c                 C   sr  |
dk	r|
n| j j}
| j||||||||	|
d	}|d }| |}d}|dk	r.| j jdkr| jdkrpd| 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r.t }|||}|
s^|f|d	d  }|dk	rZ|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_classificationr*   rx   r   )rI   r   r   r   Zproblem_typer   rO   r;   rX   rn   r   squeezer   ry   r   r   r   r   rH   rY   r   rZ   r)   r   r[   r   r   r   r   r   r   r   r   r   r   rL   rL   rM   r_     sT    



"


z&IBertForSequenceClassification.forward)
NNNNNNNNNN)r`   ra   rb   r3   r   r   r   r   r   r   r   r   r;   r   r   r   r   r   r_   rd   rL   rL   rJ   rM   r     s<   
          r   z
    I-BERT 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ej f dddZ  ZS )
IBertForMultipleChoicec                    s@   t  | t|| _t|j| _t|j	d| _
|   d S )Nr   )r2   r3   r   r   r   rD   rE   rF   r   r8   r   r   rG   rJ   rL   rM   r3   '  s
    
zIBertForMultipleChoice.__init__z(batch_size, num_choices, sequence_lengthr   N)rY   rZ   r   r   r)   r   r[   r   r   r   r   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}   )r)   rZ   r   r   r[   r   r   r   rx   r   )rI   r   shapery   rV   r   rF   r   r   r   r   r   )rH   rY   rZ   r   r   r)   r   r[   r   r   r   Znum_choicesZflat_input_idsZflat_position_idsZflat_token_type_idsZflat_attention_maskZflat_inputs_embedsr   r   r   Zreshaped_logitsr   r   r   rL   rL   rM   r_   1  sL    



zIBertForMultipleChoice.forward)
NNNNNNNNNN)r`   ra   rb   r3   r   r   r   r   r   r   r   r   r;   r   r   r   r   r   r_   rd   rL   rL   rJ   rM   r     s<   
          r   z
    I-BERT 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ej f dddZ  ZS )
IBertForTokenClassificationc                    sN   t  | |j| _t|dd| _t|j| _t	|j
|j| _|   d S r   )r2   r3   r   r   r   r   rD   rE   rF   r   r8   r   r   rG   rJ   rL   rM   r3     s    z$IBertForTokenClassification.__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*   rx   r   )rI   r   r   rF   r   r   ry   r   r   r   r   r   rL   rL   rM   r_     s8    

z#IBertForTokenClassification.forward)
NNNNNNNNNN)r`   ra   rb   r3   r   r   r   r   r   r   r   r   r;   r   r   r   r   r   r_   rd   rL   rL   rJ   rM   r  y  s<             r  c                       s(   e Zd ZdZ fddZdd Z  ZS )r   z-Head for sentence-level classification tasks.c                    s@   t    t|j|j| _t|j| _t|j|j	| _
d S r   )r2   r3   r   r   r8   r   rD   rE   rF   r   out_projrG   rJ   rL   rM   r3     s    
z IBertClassificationHead.__init__c                 K   sL   |d d dd d f }|  |}| |}t|}|  |}| |}|S r   )rF   r   r;   tanhr  )rH   r   r   r   rL   rL   rM   r_     s    




zIBertClassificationHead.forward)r`   ra   rb   rc   r3   r_   rd   rL   rL   rJ   rM   r     s   r   z
    I-BERT 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ej f dddZ  ZS )
IBertForQuestionAnsweringc                    s@   t  | |j| _t|dd| _t|j|j| _| 	  d S r   )
r2   r3   r   r   r   r   r   r8   
qa_outputsr   rG   rJ   rL   rM   r3     s
    z"IBertForQuestionAnswering.__init__r   r   N)rY   r   rZ   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*   r   )Zignore_indexrx   )r   start_logits
end_logitsr   r   )rI   r   r   r  splitr   r   r   rV   clampr   r   r   r   )rH   rY   r   rZ   r)   r   r[   r  r  r   r   r   r   r   r   r  r	  Z
total_lossZignored_indexr   Z
start_lossZend_lossr   rL   rL   rM   r_     sP    






z!IBertForQuestionAnswering.forward)NNNNNNNNNNN)r`   ra   rb   r3   r   r   r   r   r   r   r   r   r;   r   r   r   r   r   r_   rd   rL   rL   rJ   rM   r    s@   
           r  c                 C   s6   |  | }tj|dd|| | }| | S )aM  
    Replace non-padding symbols with their position numbers. Position numbers begin at padding_idx+1. Padding symbols
    are ignored. This is modified from fairseq's *utils.make_positions*.

    Args:
    input_ids (`torch.LongTensor`):
           Indices of input sequence tokens in the vocabulary.

    Returns: torch.Tensor
    r   r   )nern   r;   ZcumsumZtype_asrX   )rY   r&   r\   r   Zincremental_indicesrL   rL   rM   rS   =  s    rS   )r   )Erc   r   typingr   r   r   r;   Ztorch.utils.checkpointr   Ztorch.nnr   r   r   Zactivationsr
   Zmodeling_outputsr   r   r   r   r   r   r   Zmodeling_utilsr   Zpytorch_utilsr   r   utilsr   r   r   r   Zconfiguration_ibertr   Zquant_modulesr   r   r   r   r   r    Z
get_loggerr`   loggerr   r   Moduler!   re   r   r   r   r   r   r   r   r   ZIBERT_START_DOCSTRINGr   r   r   r   r   r   r  r   r  rS   rL   rL   rL   rM   <module>   sv   $	 
z /1"/:@2yPVSG\