U
    9%e                     @   sr  d Z ddlZddlZddlmZ ddlmZmZ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  ddl!m"Z"m#Z#m$Z$m%Z%m&Z&m'Z' ddl(m)Z) e&*e+Z,dZ-dZ.ddddddddgZ/dd Z0G dd dej1Z2G dd dej1Z3G dd dej1Z4G d d! d!ej1Z5G d"d# d#ej1Z6G d$d% d%eZ7eG d&d' d'e"Z8d(Z9d)Z:e$d*e9G d+d, d,e7Z;e$d-e9G d.d/ d/e7Z<G d0d1 d1ej1Z=G d2d3 d3ej1Z>e$d4e9G d5d6 d6e7Z?e$d7e9G d8d9 d9e7Z@e$d:e9G d;d< d<e7ZAe$d=e9G d>d? d?e7ZBe$d@e9G dAdB dBe7ZCdS )CzPyTorch ALBERT model.    N)	dataclass)DictListOptionalTupleUnion)nn)BCEWithLogitsLossCrossEntropyLossMSELoss   )ACT2FN)BaseModelOutputBaseModelOutputWithPoolingMaskedLMOutputMultipleChoiceModelOutputQuestionAnsweringModelOutputSequenceClassifierOutputTokenClassifierOutput)PreTrainedModel)apply_chunking_to_forward find_pruneable_heads_and_indicesprune_linear_layer)ModelOutputadd_code_sample_docstringsadd_start_docstrings%add_start_docstrings_to_model_forwardloggingreplace_return_docstrings   )AlbertConfigzalbert-base-v2r    zalbert-base-v1zalbert-large-v1zalbert-xlarge-v1zalbert-xxlarge-v1zalbert-large-v2zalbert-xlarge-v2zalbert-xxlarge-v2c                 C   sH  zddl }ddl}ddl}W n  tk
r<   td  Y nX tj|}t	d|  |j
|}g }g }	|D ]@\}
}t	d|
 d|  |j
||
}||
 |	| qrt||	D ]\}
}t|
 qt||	D ]f\}
}|
}|
dd}
|
d	d
}
|
dd}
|
dd}
|
dd}
|
dd}
|
dd}
|
dd}
|
dd}
|
dd}
|
dd}
|
dd}
|
dd}
|
dd}
|
dd}
|
d d!}
|
d"d#}
|
d$d%}
t|
dd&krd'|
ksd(|
krd)|
 }
d*|
kr|
d+d,}
|
d-d.}
|
d}
d/|
ksNd0|
ksNd1|
ksNd2|
ksNd3|
krft	d4d|
  q| }|
D ]}|d5|r|d6|}n|g}|d d7ks|d d8krt|d.}n|d d'ks|d d9krt|d:}nz|d d(kr t|d.}n`|d d;krt|d<}nFzt||d }W n2 tk
r^   t	d4d|
  Y qnY nX t|d=krnt|d& }|| }qn|d>d d?krt|d.}n|d7kr||}z,|j|jkrtd@|j dA|j dBW n< tk
r  } z| j|j|jf7  _ W 5 d}~X Y nX tdC|
 dD|  t||_q| S )Ez'Load tf checkpoints in a pytorch model.r   NzLoading a TensorFlow model in PyTorch, requires TensorFlow to be installed. Please see https://www.tensorflow.org/install/ for installation instructions.z&Converting TensorFlow checkpoint from zLoading TF weight z with shape zmodule/ Zffn_1ffnzbert/zalbert/Zattention_1	attentionz
transform/ZLayerNorm_1full_layer_layer_norm	LayerNormzattention/LayerNormztransformer/zintermediate/dense/zffn/intermediate/output/dense/zffn_output/z/output//z/self/zpooler/densepoolerzcls/predictionspredictionszpredictions/attentionzembeddings/attention
embeddingsZinner_group_zalbert_layers/Zgroup_zalbert_layer_groups/r   Zoutput_biasZoutput_weightszclassifier/Zseq_relationshipzseq_relationship/output_zsop_classifier/classifier/weightsweightZadam_mZadam_vZAdamWeightDecayOptimizerZAdamWeightDecayOptimizer_1Zglobal_stepz	Skipping z[A-Za-z]+_\d+z_(\d+)ZkernelgammabetabiasZsquad
classifier   iZ_embeddingszPointer shape z and array shape z mismatchedzInitialize PyTorch weight z from )renumpyZ
tensorflowImportErrorloggererrorospathabspathinfotrainZlist_variablesZload_variableappendzipprintreplacelensplitjoin	fullmatchgetattrAttributeErrorint	transposeshape
ValueErrorargstorchZ
from_numpydata)modelconfigZtf_checkpoint_pathr1   nptfZtf_pathZ	init_varsnamesZarraysnamerG   arrayoriginal_nameZpointerZm_nameZscope_namesnume rV   i/var/www/html/Darija-Ai-API/env/lib/python3.8/site-packages/transformers/models/albert/modeling_albert.pyload_tf_weights_in_albertD   s    

(




rX   c                       sZ   e Zd ZdZed fddZd
eej eej eej eej	 e
ejddd	Z  ZS )AlbertEmbeddingszQ
    Construct the embeddings from word, position and token_type embeddings.
    rM   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 t|dd| _| jd	tj| j tjd
dd d S )N)padding_idxZepsposition_ids)r   F)
persistentposition_embedding_typeabsolutetoken_type_idsdtype)super__init__r   	Embedding
vocab_sizeembedding_sizeZpad_token_idword_embeddingsmax_position_embeddingsposition_embeddingsZtype_vocab_sizetoken_type_embeddingsr%   layer_norm_epsDropouthidden_dropout_probdropoutZregister_bufferrJ   arangeexpandrC   r`   zerosr]   sizelongselfrM   	__class__rV   rW   rf      s"    
    zAlbertEmbeddings.__init__Nr   )	input_idsrb   r]   inputs_embedspast_key_values_lengthreturnc                 C   s   |d k	r|  }n|  d d }|d }|d krL| jd d ||| f }|d krt| dr| jd d d |f }||d |}	|	}ntj|tj| jjd}|d kr| 	|}| 
|}
||
 }| jdkr| |}||7 }| |}| |}|S )Nr^   r   rb   r   rd   devicera   )ru   r]   hasattrrb   rs   rJ   rt   rv   r   rj   rm   r`   rl   r%   rq   )rx   r{   rb   r]   r|   r}   input_shape
seq_lengthbuffered_token_type_ids buffered_token_type_ids_expandedrm   r)   rl   rV   rV   rW   forward   s,    







zAlbertEmbeddings.forward)NNNNr   )__name__
__module____qualname____doc__r    rf   r   rJ   
LongTensorFloatTensorrE   Tensorr   __classcell__rV   rV   ry   rW   rY      s        rY   c                
       s   e Zd Zed fddZejejdddZee	 ddd	d
Z
dejeej eej eeeej eejejf f dddZ  ZS )AlbertAttentionrZ   c                    s4  t    |j|j dkr<t|ds<td|j d|j |j| _|j| _|j|j | _| j| j | _t	|j| j| _
t	|j| j| _t	|j| j| _t|j| _t|j| _t	|j|j| _tj|j|jd| _t | _t|dd| _| jdks| jd	kr0|j| _td
|j d | j| _d S )Nr   ri   zThe hidden size (z6) is not a multiple of the number of attention heads (r\   r`   ra   relative_keyrelative_key_queryr0   r   )re   rf   hidden_sizenum_attention_headsr   rH   attention_head_sizeall_head_sizer   Linearquerykeyvaluero   Zattention_probs_dropout_probattention_dropoutrp   output_dropoutdenser%   rn   setpruned_headsrC   r`   rk   rg   distance_embeddingrw   ry   rV   rW   rf     s*    
zAlbertAttention.__init__)xr~   c                 C   s6   |  d d | j| jf }||}|ddddS )Nr^   r   r0   r   r   )ru   r   r   viewZpermute)rx   r   Znew_x_shaperV   rV   rW   transpose_for_scores$  s    
z$AlbertAttention.transpose_for_scoresN)headsr~   c                 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   dim)r?   r   r   r   r   r   r   r   r   r   r   union)rx   r   indexrV   rV   rW   prune_heads)  s       zAlbertAttention.prune_headsF)hidden_statesattention_mask	head_maskoutput_attentionsr~   c                 C   s  |  |}| |}| |}| |}| |}	| |}
t||	dd}|t| j	 }|d k	rp|| }| j
dks| j
dkrL| d }tj|tj|jddd}tj|tj|jddd}|| }| || j d }|j|jd}| j
dkrtd||}|| }n4| j
dkrLtd||}td	|	|}|| | }tjj|dd
}| |}|d k	rx|| }t||
}|ddd}| |}| |}| || }|r||fS |fS )Nr^   r   r   r   r   rc   zbhld,lrd->bhlrzbhrd,lrd->bhlrr   r0   )r   r   r   r   rJ   matmulrF   mathsqrtr   r`   ru   rr   rv   r   r   r   rk   tord   Zeinsumr   Z
functionalZsoftmaxr   flattenr   r   r%   )rx   r   r   r   r   Zmixed_query_layerZmixed_key_layerZmixed_value_layerZquery_layerZ	key_layerZvalue_layerZattention_scoresr   Zposition_ids_lZposition_ids_rZdistanceZpositional_embeddingZrelative_position_scoresZrelative_position_scores_queryZrelative_position_scores_keyZattention_probsZcontext_layerZprojected_context_layerZprojected_context_layer_dropoutZlayernormed_context_layerrV   rV   rW   r   ;  sD    










zAlbertAttention.forward)NNF)r   r   r   r    rf   rJ   r   r   r   rE   r   r   r   boolr   r   r   r   rV   rV   ry   rW   r     s      r   c                	       sj   e Zd Zed fddZdejeej eej e	e	e
ejejf dddZejejd	d
dZ  ZS )AlbertLayerrZ   c                    s~   t    || _|j| _d| _tj|j|jd| _	t
|| _t|j|j| _t|j|j| _t|j | _t|j| _d S )Nr   r\   )re   rf   rM   chunk_size_feed_forwardseq_len_dimr   r%   r   rn   r$   r   r#   r   Zintermediate_sizer"   
ffn_outputr   
hidden_act
activationro   rp   rq   rw   ry   rV   rW   rf   w  s    

zAlbertLayer.__init__NFr   r   r   r   output_hidden_statesr~   c                 C   sL   |  ||||}t| j| j| j|d }| ||d  }|f|dd   S )Nr   r   )r#   r   ff_chunkr   r   r$   )rx   r   r   r   r   r   attention_outputr   rV   rV   rW   r     s    zAlbertLayer.forward)r   r~   c                 C   s"   |  |}| |}| |}|S N)r"   r   r   )rx   r   r   rV   rV   rW   r     s    


zAlbertLayer.ff_chunk)NNFF)r   r   r   r    rf   rJ   r   r   r   r   r   r   r   r   rV   rV   ry   rW   r   v  s       r   c                       sb   e Zd Zed fddZd
ejeej eej e	e	e
eeje
ej f df ddd	Z  ZS )AlbertLayerGrouprZ   c                    s.   t    t fddt jD | _d S )Nc                    s   g | ]}t  qS rV   )r   .0_rZ   rV   rW   
<listcomp>  s     z-AlbertLayerGroup.__init__.<locals>.<listcomp>)re   rf   r   
ModuleListrangeinner_group_numalbert_layersrw   ry   rZ   rW   rf     s    
zAlbertLayerGroup.__init__NF.r   c                 C   s|   d}d}t | jD ]B\}}	|	|||| |}
|
d }|rF||
d f }|r||f }q|f}|rj||f }|rx||f }|S )NrV   r   r   )	enumerater   )rx   r   r   r   r   r   Zlayer_hidden_statesZlayer_attentionsZlayer_indexZalbert_layerZlayer_outputoutputsrV   rV   rW   r     s    

zAlbertLayerGroup.forward)NNFF)r   r   r   r    rf   rJ   r   r   r   r   r   r   r   r   rV   rV   ry   rW   r     s       r   c                
       sT   e Zd Zed fddZd
ejeej eej e	e	e	e
eef ddd	Z  ZS )AlbertTransformerrZ   c                    sF   t     | _t j j| _t fddt	 j
D | _d S )Nc                    s   g | ]}t  qS rV   )r   r   rZ   rV   rW   r     s     z.AlbertTransformer.__init__.<locals>.<listcomp>)re   rf   rM   r   r   ri   r   embedding_hidden_mapping_inr   r   num_hidden_groupsalbert_layer_groupsrw   ry   rZ   rW   rf     s    
zAlbertTransformer.__init__NFT)r   r   r   r   r   return_dictr~   c                 C   s   |  |}|r|fnd }|r dnd }|d kr:d g| jj n|}t| jjD ]}	t| jj| jj }
t|	| jj| jj  }| j| |||||
 |d |
  ||}|d }|r||d  }|rJ||f }qJ|stdd |||fD S t|||dS )NrV   r   r   r^   c                 s   s   | ]}|d k	r|V  qd S r   rV   )r   vrV   rV   rW   	<genexpr>  s      z,AlbertTransformer.forward.<locals>.<genexpr>)last_hidden_stater   
attentions)	r   rM   num_hidden_layersr   rE   r   r   tupler   )rx   r   r   r   r   r   r   Zall_hidden_statesZall_attentionsiZlayers_per_group	group_idxZlayer_group_outputrV   rV   rW   r     s4    	
  zAlbertTransformer.forward)NNFFT)r   r   r   r    rf   rJ   r   r   r   r   r   r   r   r   r   rV   rV   ry   rW   r     s   
     
r   c                   @   s$   e Zd ZdZeZeZdZdd Z	dS )AlbertPreTrainedModelz
    An abstract class to handle weights initialization and a simple interface for downloading and loading pretrained
    models.
    albertc                 C   s   t |tjr:|jjjd| jjd |jdk	r|jj	  nft |tj
rz|jjjd| jjd |jdk	r|jj|j 	  n&t |tjr|jj	  |jjd dS )zInitialize the weights.g        )ZmeanZstdN      ?)
isinstancer   r   r+   rK   Znormal_rM   Zinitializer_ranger.   Zzero_rg   r[   r%   Zfill_)rx   modulerV   rV   rW   _init_weights  s    

z#AlbertPreTrainedModel._init_weightsN)
r   r   r   r   r    config_classrX   Zload_tf_weightsbase_model_prefixr   rV   rV   rV   rW   r     s
   r   c                   @   sl   e Zd ZU dZdZeej ed< dZ	ejed< dZ
ejed< dZeeej  ed< dZeeej  ed< dS )AlbertForPreTrainingOutputaQ  
    Output type of [`AlbertForPreTraining`].

    Args:
        loss (*optional*, returned when `labels` is provided, `torch.FloatTensor` of shape `(1,)`):
            Total loss as the sum of the masked language modeling loss and the next sequence prediction
            (classification) loss.
        prediction_logits (`torch.FloatTensor` of shape `(batch_size, sequence_length, config.vocab_size)`):
            Prediction scores of the language modeling head (scores for each vocabulary token before SoftMax).
        sop_logits (`torch.FloatTensor` of shape `(batch_size, 2)`):
            Prediction scores of the next sequence prediction (classification) head (scores of True/False continuation
            before SoftMax).
        hidden_states (`tuple(torch.FloatTensor)`, *optional*, returned when `output_hidden_states=True` is passed or when `config.output_hidden_states=True`):
            Tuple of `torch.FloatTensor` (one for the output of the embeddings + one for the output of each layer) of
            shape `(batch_size, sequence_length, hidden_size)`.

            Hidden-states of the model at the output of each layer plus the initial embedding outputs.
        attentions (`tuple(torch.FloatTensor)`, *optional*, returned when `output_attentions=True` is passed or when `config.output_attentions=True`):
            Tuple of `torch.FloatTensor` (one for each layer) of shape `(batch_size, num_heads, sequence_length,
            sequence_length)`.

            Attentions weights after the attention softmax, used to compute the weighted average in the self-attention
            heads.
    Nlossprediction_logits
sop_logitsr   r   )r   r   r   r   r   r   rJ   r   __annotations__r   r   r   r   r   rV   rV   rV   rW   r     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.

    Args:
        config ([`AlbertConfig`]): 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.__call__`] and
            [`PreTrainedTokenizer.encode`] 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 ALBERT Model transformer outputting raw hidden-states without any specific head on top.c                       s   e Zd ZeZdZdeed fddZej	dddZ
ej	d	d
ddZeeee f d	d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 )AlbertModelr   T)rM   add_pooling_layerc                    s`   t  | || _t|| _t|| _|rHt|j	|j	| _
t | _nd | _
d | _|   d S r   )re   rf   rM   rY   r)   r   encoderr   r   r   r'   ZTanhpooler_activation	post_init)rx   rM   r   ry   rV   rW   rf   ~  s    

zAlbertModel.__init__r~   c                 C   s   | j jS r   r)   rj   rx   rV   rV   rW   get_input_embeddings  s    z AlbertModel.get_input_embeddingsN)r   r~   c                 C   s   || j _d S r   r   )rx   r   rV   rV   rW   set_input_embeddings  s    z AlbertModel.set_input_embeddings)heads_to_pruner~   c                 C   sT   |  D ]F\}}t|| jj }t||| jj  }| jj| j| j| qdS )a  
        Prunes heads of the model. heads_to_prune: dict of {layer_num: list of heads to prune in this layer} ALBERT has
        a different architecture in that its layers are shared across groups, which then has inner groups. If an ALBERT
        model has 12 hidden layers and 2 hidden groups, with two inner groups, there is a total of 4 different layers.

        These layers are flattened: the indices [0,1] correspond to the two inner groups of the first hidden layer,
        while [2,3] correspond to the two inner groups of the second hidden layer.

        Any layer with in index other than [0,1,2,3] will result in an error. See base class PreTrainedModel for more
        information about head pruning
        N)	itemsrE   rM   r   r   r   r   r#   r   )rx   r   layerr   r   Zinner_group_idxrV   rV   rW   _prune_heads  s    zAlbertModel._prune_headsbatch_size, sequence_length
checkpointoutput_typer   )
r{   r   rb   r]   r   r|   r   r   r   r~   c
                 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rt
| jdr
| jjd d d |f }|||}|}ntj|
tj|d}|dd}|j| jd	}d
| t| jj }| || j j}| j||||d}| j||||||	d}|d }| jd k	r| | |d d df nd }|	s||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)r   rb   r   r   r0   rc   r   )r]   rb   r|   )r   r   r   r   r   )r   Zpooler_outputr   r   )rM   r   r   use_return_dictrH   Z%warn_if_padding_and_no_attention_maskru   r   rJ   Zonesr   r)   rb   rs   rt   rv   Z	unsqueezer   rd   ZfinfominZget_head_maskr   r   r'   r   r   r   r   )rx   r{   r   rb   r]   r   r|   r   r   r   r   Z
batch_sizer   r   r   r   Zextended_attention_maskZembedding_outputZencoder_outputssequence_outputpooled_outputrV   rV   rW   r     sd    


   	,zAlbertModel.forward)T)	NNNNNNNNN)r   r   r   r    r   r   r   rf   r   rg   r   r   r   rE   r   r   r   ALBERT_INPUTS_DOCSTRINGformatr   _CHECKPOINT_FOR_DOCr   _CONFIG_FOR_DOCr   rJ   r   r   r   r   r   r   rV   rV   ry   rW   r   v  sB            
r   z
    Albert Model with two heads on top as done during the pretraining: a `masked language modeling` head and a
    `sentence order prediction (classification)` head.
    c                       s   e Zd ZddgZed fddZejdddZejd	d
ddZ	ej
dddZeed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 )AlbertForPreTrainingpredictions.decoder.biaspredictions.decoder.weightrZ   c                    s6   t  | t|| _t|| _t|| _|   d S r   )	re   rf   r   r   AlbertMLMHeadr(   AlbertSOPHeadsop_classifierr   rw   ry   rV   rW   rf     s
    


zAlbertForPreTraining.__init__r   c                 C   s   | j jS r   r(   decoderr   rV   rV   rW   get_output_embeddings  s    z*AlbertForPreTraining.get_output_embeddingsNnew_embeddingsr~   c                 C   s   || j _d S r   r  rx   r  rV   rV   rW   set_output_embeddings  s    z*AlbertForPreTraining.set_output_embeddingsc                 C   s
   | j jjS r   r   r)   rj   r   rV   rV   rW   r     s    z)AlbertForPreTraining.get_input_embeddingsr   r   r   )r{   r   rb   r]   r   r|   labelssentence_order_labelr   r   r   r~   c                 C   s   |dk	r|n| j j}| j|||||||	|
|d	}|dd \}}| |}| |}d}|dk	r|dk	rt }||d| j j|d}||dd|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]`
        sentence_order_label (`torch.LongTensor` of shape `(batch_size,)`, *optional*):
            Labels for computing the next sequence prediction (classification) loss. Input should be a sequence pair
            (see `input_ids` docstring) Indices should be in `[0, 1]`. `0` indicates original order (sequence A, then
            sequence B), `1` indicates switched order (sequence B, then sequence A).

        Returns:

        Example:

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

        >>> tokenizer = AutoTokenizer.from_pretrained("albert-base-v2")
        >>> model = AlbertForPreTraining.from_pretrained("albert-base-v2")

        >>> input_ids = torch.tensor(tokenizer.encode("Hello, my dog is cute", add_special_tokens=True)).unsqueeze(0)
        >>> # Batch size 1
        >>> outputs = model(input_ids)

        >>> prediction_logits = outputs.prediction_logits
        >>> sop_logits = outputs.sop_logits
        ```Nr   rb   r]   r   r|   r   r   r   r0   r^   )r   r   r   r   r   )rM   r   r   r(   r  r
   r   rh   r   r   r   )rx   r{   r   rb   r]   r   r|   r  r  r   r   r   r   r   r   prediction_scoresZ
sop_scores
total_lossloss_fctmasked_lm_lossZsentence_order_lossoutputrV   rV   rW   r     s>    ,

zAlbertForPreTraining.forward)NNNNNNNNNNN)r   r   r   _tied_weights_keysr    rf   r   r   r  r
  rg   r   r   r   r   r   r   r   r   rJ   r   r   r   r   r   r   r   rV   rV   ry   rW   r     s@   

           
r   c                       sD   e Zd Zed fddZejejdddZddd	d
Z  Z	S )r  rZ   c                    sp   t    tj|j|jd| _tt|j	| _
t|j|j| _t|j|j	| _t|j | _| j
| j_
d S )Nr\   )re   rf   r   r%   ri   rn   	ParameterrJ   rt   rh   r.   r   r   r   r  r   r   r   rw   ry   rV   rW   rf   e  s    
zAlbertMLMHead.__init__)r   r~   c                 C   s0   |  |}| |}| |}| |}|}|S r   )r   r   r%   r  )rx   r   r  rV   rV   rW   r   o  s    



zAlbertMLMHead.forwardNr   c                 C   s   | j j| _d S r   )r  r.   r   rV   rV   rW   _tie_weightsy  s    zAlbertMLMHead._tie_weights)
r   r   r   r    rf   rJ   r   r   r  r   rV   rV   ry   rW   r  d  s   

r  c                       s6   e Zd Zed fddZejejdddZ  ZS )r  rZ   c                    s.   t    t|j| _t|j|j| _	d S r   )
re   rf   r   ro   classifier_dropout_probrq   r   r   
num_labelsr/   rw   ry   rV   rW   rf     s    
zAlbertSOPHead.__init__)r   r~   c                 C   s   |  |}| |}|S r   )rq   r/   )rx   r   Zdropout_pooled_outputlogitsrV   rV   rW   r     s    

zAlbertSOPHead.forward)	r   r   r   r    rf   rJ   r   r   r   rV   rV   ry   rW   r  ~  s   r  z4Albert Model with a `language modeling` head on top.c                       s   e Zd ZddgZ fddZejdddZejdd	d
dZej	dddZ
eed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 )AlbertForMaskedLMr   r   c                    s0   t  | t|dd| _t|| _|   d S NF)r   )re   rf   r   r   r  r(   r   rw   ry   rV   rW   rf     s    
zAlbertForMaskedLM.__init__r   c                 C   s   | j jS r   r  r   rV   rV   rW   r    s    z'AlbertForMaskedLM.get_output_embeddingsNr  c                 C   s   || j _d S r   r  r	  rV   rV   rW   r
    s    z'AlbertForMaskedLM.set_output_embeddingsc                 C   s
   | j jjS r   r  r   rV   rV   rW   r     s    z&AlbertForMaskedLM.get_input_embeddingsr   r  r{   r   rb   r]   r   r|   r  r   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]`

        Returns:

        Example:

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

        >>> tokenizer = AutoTokenizer.from_pretrained("albert-base-v2")
        >>> model = AlbertForMaskedLM.from_pretrained("albert-base-v2")

        >>> # add mask_token
        >>> inputs = tokenizer("The capital of [MASK] is Paris.", return_tensors="pt")
        >>> with torch.no_grad():
        ...     logits = model(**inputs).logits

        >>> # retrieve index of [MASK]
        >>> mask_token_index = (inputs.input_ids == tokenizer.mask_token_id)[0].nonzero(as_tuple=True)[0]
        >>> predicted_token_id = logits[0, mask_token_index].argmax(axis=-1)
        >>> tokenizer.decode(predicted_token_id)
        'france'
        ```

        ```python
        >>> labels = tokenizer("The capital of France is Paris.", return_tensors="pt")["input_ids"]
        >>> labels = torch.where(inputs.input_ids == tokenizer.mask_token_id, labels, -100)
        >>> outputs = model(**inputs, labels=labels)
        >>> round(outputs.loss.item(), 2)
        0.81
        ```
        N	r{   r   rb   r]   r   r|   r   r   r   r   r^   r0   r   r  r   r   )
rM   r   r   r(   r
   r   rh   r   r   r   )rx   r{   r   rb   r]   r   r|   r  r   r   r   r   Zsequence_outputsr  r  r  r  rV   rV   rW   r     s6    4
zAlbertForMaskedLM.forward)
NNNNNNNNNN)r   r   r   r  rf   r   r   r  r
  rg   r   r   r   r   r   r   r   r   rJ   r   r   r   r   r   r   r   rV   rV   ry   rW   r    s<   	
          
r  z
    Albert 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ed fddZeedede	e
d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f d
ddZ  ZS )AlbertForSequenceClassificationrZ   c                    sR   t  | |j| _|| _t|| _t|j| _	t
|j| jj| _|   d S r   )re   rf   r  rM   r   r   r   ro   r  rq   r   r   r/   r   rw   ry   rV   rW   rf     s    
z(AlbertForSequenceClassification.__init__r   ztextattack/albert-base-v2-imdbz	'LABEL_1'gQ?)r   r   r   expected_outputexpected_lossNr  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^   r0   r  )rM   r   r   rq   r/   Zproblem_typer  rd   rJ   rv   rE   r   squeezer
   r   r	   r   r   r   )rx   r{   r   rb   r]   r   r|   r  r   r   r   r   r   r  r   r  r  rV   rV   rW   r     sV    




"


z'AlbertForSequenceClassification.forward)
NNNNNNNNNN)r   r   r   r    rf   r   r   r   r   r   r   r   rJ   r   r   r   r   r   r   r   rV   rV   ry   rW   r     s@   	          
r   z
    Albert 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ed 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 )AlbertForTokenClassificationrZ   c                    sd   t  | |j| _t|dd| _|jd k	r2|jn|j}t|| _	t
|j| jj| _|   d S r  )re   rf   r  r   r   r  rp   r   ro   rq   r   r   rM   r/   r   )rx   rM   r  ry   rV   rW   rf   g  s    z%AlbertForTokenClassification.__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^   r0   r  )rM   r   r   rq   r/   r
   r   r  r   r   r   )rx   r{   r   rb   r]   r   r|   r  r   r   r   r   r   r  r   r  r  rV   rV   rW   r   w  s8    

z$AlbertForTokenClassification.forward)
NNNNNNNNNN)r   r   r   r    rf   r   r   r   r   r   r   r   r   rJ   r   r   r   r   r   r   r   rV   rV   ry   rW   r$  _  s<             
r$  z
    Albert 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ed fddZeedede	e
ddd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j ee ee ee eeef dddZ  ZS )AlbertForQuestionAnsweringrZ   c                    s@   t  | |j| _t|dd| _t|j|j| _| 	  d S r  )
re   rf   r  r   r   r   r   r   
qa_outputsr   rw   ry   rV   rW   rf     s
    z#AlbertForQuestionAnswering.__init__r   ztwmkn9/albert-base-v2-squad2      z'a nice puppet'gq=
ףp@)r   r   r   Zqa_target_start_indexZqa_target_end_indexr!  r"  N)r{   r   rb   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_indexr0   )r   start_logits
end_logitsr   r   )rM   r   r   r&  r@   r#  
contiguousr?   ru   clampr
   r   r   r   )rx   r{   r   rb   r]   r   r|   r)  r*  r   r   r   r   r   r  r+  r,  r  Zignored_indexr  Z
start_lossZend_lossr  rV   rV   rW   r     sP    "






z"AlbertForQuestionAnswering.forward)NNNNNNNNNNN)r   r   r   r    rf   r   r   r   r   r   r   r   rJ   r   r   r   r   r   r   r   r   rV   rV   ry   rW   r%    sH   
           
r%  z
    Albert 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ed 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 )AlbertForMultipleChoicerZ   c                    s@   t  | t|| _t|j| _t|j	d| _
|   d S )Nr   )re   rf   r   r   r   ro   r  rq   r   r   r/   r   rw   ry   rV   rW   rf   !  s
    
z AlbertForMultipleChoice.__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   r  r0   r  )rM   r   rG   r   ru   r   rq   r/   r
   r   r   r   )rx   r{   r   rb   r]   r   r|   r  r   r   r   Znum_choicesr   r   r  Zreshaped_logitsr   r  r  rV   rV   rW   r   +  sL    



zAlbertForMultipleChoice.forward)
NNNNNNNNNN)r   r   r   r    rf   r   r   r   r   r   r   r   r   rJ   r   r   r   r   r   r   r   r   rV   rV   ry   rW   r/    s<   
          
r/  )Dr   r   r6   dataclassesr   typingr   r   r   r   r   rJ   r   Ztorch.nnr	   r
   r   Zactivationsr   Zmodeling_outputsr   r   r   r   r   r   r   Zmodeling_utilsr   Zpytorch_utilsr   r   r   utilsr   r   r   r   r   r   Zconfiguration_albertr    Z
get_loggerr   r4   r   r   Z$ALBERT_PRETRAINED_MODEL_ARCHIVE_LISTrX   ModulerY   r   r   r   r   r   r   ZALBERT_START_DOCSTRINGr   r   r   r  r  r  r   r$  r%  r/  rV   rV   rV   rW   <module>   s   $	 
~Dp)#5!2zik^L`