a
    h                    @   s  d Z ddlZddlm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mZ dd	lmZ dd
lmZ ddlmZ ddlmZmZmZ ddlmZ eeZdKddZ dd 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)eG d!d" d"eZ*eed#d$G d%d& d&eZ+eed'd$G d(d) d)eZ,eed*d$G d+d, d,eZ-eed-d$G d.d/ d/eZ.eed0d$G d1d2 d2eZ/eed3d$G d4d5 d5eZ0eed6d$G d7d8 d8eZ1eG d9d: d:e*Z2ed;d$G d<d= d=e*eZ3ed>d$G d?d@ d@e*Z4eG dAdB dBe*Z5eG dCdD dDe*Z6edEd$G dFdG dGe*Z7eG dHdI dIe*Z8g dJZ9dS )Lz
PyTorch XLNet model.
    N)	dataclass)CallableOptionalUnion)nn)BCEWithLogitsLossCrossEntropyLossMSELoss   )ACT2FNget_activation)GenerationMixin)PreTrainedModel)apply_chunking_to_forward)ModelOutputauto_docstringlogging   )XLNetConfigc                 C   s.  i }t | drt | dr$| jj|d< t | drRd|v rR| jjj|d< | jjj|d< t | dr|jdurd	|j d
|v r| jj|d	|j d
< | jj|d	|j d< | j} |	| j
j| jd t| jD ]\}}d| d}|	|d |jjj|d |jjj|d |jj|d |jj|d |jj|d |jj|d |jj|d |jjj|d |jjj|d |jjj|d |jjj|d |jjj|d |jjji q|jrg }g }g }	g }
| jD ]>}||jj ||jj |	|jj |
|jj qn | jg}| jg}| jg}	| jg}
|	|||	|
d |S )z
    A map of modules from TF to PyTorch. I use a map to keep the PyTorch model as identical to the original PyTorch
    model as possible.
    transformerlm_losszmodel/lm_loss/biassequence_summaryz%model/sequnece_summary/summary/kernelz#model/sequnece_summary/summary/biaslogits_projNzmodel/regression_z/logit/kernelz/logit/bias)z-model/transformer/word_embedding/lookup_tablez#model/transformer/mask_emb/mask_embzmodel/transformer/layer_/zrel_attn/LayerNorm/gammazrel_attn/LayerNorm/betazrel_attn/o/kernelzrel_attn/q/kernelzrel_attn/k/kernelzrel_attn/r/kernelzrel_attn/v/kernelzff/LayerNorm/gammazff/LayerNorm/betazff/layer_1/kernelzff/layer_1/biaszff/layer_2/kernelzff/layer_2/bias)zmodel/transformer/r_r_biaszmodel/transformer/r_w_biaszmodel/transformer/r_s_biaszmodel/transformer/seg_embed)hasattrr   biasr   summaryweightZfinetuning_taskr   r   updateword_embeddingmask_emb	enumeratelayerrel_attn
layer_normoqkrvfflayer_1layer_2Zuntie_rappendr_r_biasr_w_biasr_s_bias	seg_embed)modelconfig
tf_weightstf_to_pt_mapibZ	layer_strZr_r_listZr_w_listZr_s_listZseg_embed_list r8   d/var/www/html/assistant/venv/lib/python3.9/site-packages/transformers/models/xlnet/modeling_xlnet.pybuild_tf_xlnet_to_pytorch_map'   sz    


r:   c                 C   s  zddl }ddl}W n ty2   td  Y n0 |j|}i }|D ]4\}}td| d|  |j||}	|	||< qHt	| ||}
|

 D ]\}}td|  ||vrt| d q|| }	d|v rd	|v sd
|v sd|v rtd ||	}	t|trt||	jd ksFJ dt| d|	jd  dt|D ]\}}|	|df }z,|j|jksJ d|j d|j dW n> ty } z$| j|j|jf7  _ W Y d}~n
d}~0 0 td| d|  t||_qNnz,|j|	jks J d|j d|	j dW n> ty` } z$| j|j|	jf7  _ W Y d}~n
d}~0 0 td|  t|	|_||d ||d d ||d d qtdd|   | S )z&Load tf checkpoints in a pytorch modelr   NzLoading a TensorFlow models in PyTorch, requires TensorFlow to be installed. Please see https://www.tensorflow.org/install/ for installation instructions.zLoading TF weight z with shape z
Importing z( not in tf pre-trained weights, skippingZkernelr*   r   ZlogitZTransposingzPointer length z and array length z mismatched.zPointer shape z and array shape zInitialize PyTorch weight z for layer z/Adamz/Adam_1z%Weights not copied to PyTorch model: z, )numpyZ
tensorflowImportErrorloggererrortrainZlist_variablesinfoZload_variabler:   items	transpose
isinstancelistlenshaper!   AssertionErrorargstorchZ
from_numpydatapopjoinkeys)r2   r3   Ztf_pathnptfZ	init_varsr4   namerF   arrayr5   Zpointerr6   Zp_iZarr_ier8   r8   r9   load_tf_weights_in_xlnetz   sj    
$

rS   c                       s^   e Zd Z fddZdd ZedddZeddd	ZdddZdddZ	dddZ
  ZS )XLNetRelativeAttentionc                    sn  t    |j|j dkr2td|j d|j |j| _|j| _|j| _d|jd  | _tt	
|j| j| j| _tt	
|j| j| j| _tt	
|j| j| j| _tt	
|j| j| j| _tt	
|j| j| j| _tt	
| j| j| _tt	
| j| j| _tt	
| j| j| _tt	
d| j| j| _tj|j|jd| _t|j| _d S )Nr   zThe hidden size (z6) is not a multiple of the number of attention heads (r         ?   eps)super__init__d_modelZn_head
ValueErrorZd_headscaler   	ParameterrI   FloatTensorr&   r'   r)   r%   r(   r.   r0   r/   r1   	LayerNormlayer_norm_epsr$   Dropoutdropoutselfr3   	__class__r8   r9   rZ      s,    

zXLNetRelativeAttention.__init__c                 C   s   t d S NNotImplementedError)re   Zheadsr8   r8   r9   prune_heads   s    z"XLNetRelativeAttention.prune_headsc              	   C   s|   | j }| |d |d |d |d } | dddf } | |d |d d |d |d } t| dtj|| jtjd} | S )z<perform relative shift to form the relative attention score.r   r   rV   r
   N.devicedtyperF   ZreshaperI   index_selectarangern   longxklenZx_sizer8   r8   r9   	rel_shift   s     $z XLNetRelativeAttention.rel_shiftc              	   C   s   | j }| |d |d |d |d } | d d d d dd d d f } | |d |d |d |d d } t| dtj|| jtjd} | S )Nr   r   r
   rV   rm   rp   rt   r8   r8   r9   rel_shift_bnij   s      $z%XLNetRelativeAttention.rel_shift_bnijNFc	                 C   s  t d|| j |}	t d|| j |}
| j|
|	jd d}
|du rJd}n$t d|| j | j}t d||}|	|
 | | j }|dur|j	t j
kr|dt d	|  }n|d
t d	|  }tjj|dd}| |}|dur|t d	| }t d||}|r|t d|fS |S )z.Core relative positional attention operations.zibnd,jbnd->bnijr
   )rv   Nr   zibnd,snd->ibnszijbs,ibns->bnij  z
ijbn->bnijꌠ9Y>)Fdimzbnij,jbnd->ibndz
bnij->ijbn)rI   einsumr/   r.   rx   rF   r0   r1   r]   ro   float16r   
functionalsoftmaxrc   )re   Zq_headk_head_hv_head_hk_head_rseg_mat	attn_mask	head_maskoutput_attentionsacZbdZefZ
attn_score	attn_probattn_vecr8   r8   r9   rel_attn_core   s(    
z$XLNetRelativeAttention.rel_attn_coreTc                 C   s4   t d|| j}| |}|r&|| }| |}|S )zPost-attention processing.zibnd,hnd->ibh)rI   r}   r%   rc   r$   )re   hr   ZresidualZattn_outoutputr8   r8   r9   post_attention-  s    

z%XLNetRelativeAttention.post_attentionc              
   C   s  |d urJ|d ur2|  dkr2tj||gdd}n|}td|| j}td|| j}td|| j}td|| j}| j|||||||	|
d}|
r|\}}| 	||}td|| j}|d urtd||}| j|||||||	|
d}|
r|\}}td||}n(| j|||||||	|
d}|
r.|\}}| 	||}|
r||f}n|d urv|  dkrvtj||gdd}n|}td|| j}td|| j}td|| j}td|
| jj| j}| j|||||||	|
d}|
r|\}}| 	||}d }||f}|
r||f }|S )Nr   r   r{   zibh,hnd->ibnd)r   r   r   r   zmbnd,mlb->lbndzlbnd,mlb->mbnd)r|   rI   catr}   r'   r)   r(   r&   r   r   typero   )re   r   gattn_mask_hattn_mask_gr(   r   memstarget_mappingr   r   r   r   r   r   Zq_head_hZ
attn_vec_hZattn_prob_houtput_hZq_head_gZ
attn_vec_gZattn_prob_goutput_gr   r   outputsr8   r8   r9   forward9  s    



zXLNetRelativeAttention.forward)rl   )rl   )NNNF)T)NNNF)__name__
__module____qualname__rZ   rk   staticmethodrw   rx   r   r   r   __classcell__r8   r8   rf   r9   rT      s"       
4
    rT   c                       s$   e Zd Z fddZdd Z  ZS )XLNetFeedForwardc                    sv   t    tj|j|jd| _t|j|j| _	t|j|j| _
t|j| _t|jtrjt|j | _n|j| _d S )NrW   )rY   rZ   r   r`   r[   ra   r$   LinearZd_innerr+   r,   rb   rc   rC   Zff_activationstrr   activation_functionrd   rf   r8   r9   rZ     s    
zXLNetFeedForward.__init__c                 C   sH   |}|  |}| |}| |}| |}| |}| || }|S rh   )r+   r   rc   r,   r$   )re   inpr   r8   r8   r9   r     s    




zXLNetFeedForward.forward)r   r   r   rZ   r   r   r8   r8   rf   r9   r     s   r   c                       s.   e Zd Z fddZd	ddZdd Z  ZS )

XLNetLayerc                    s>   t    t|| _t|| _t|j| _|j	| _	d| _
d S Nr   )rY   rZ   rT   r#   r   r*   r   rb   rc   chunk_size_feed_forwardseq_len_dimrd   rf   r8   r9   rZ     s    


zXLNetLayer.__init__NFc                 C   sv   | j |||||||||	|
d
}|d d \}}|d urJt| j| j| j|}t| j| j| j|}||f|dd   }|S )N)r   r   r   r   rV   )r#   r   ff_chunkr   r   )re   r   r   r   r   r(   r   r   r   r   r   r   r8   r8   r9   r     s(    zXLNetLayer.forwardc                 C   s   |  |}|S rh   )r*   )re   Zoutput_xr8   r8   r9   r     s    
zXLNetLayer.ff_chunk)NNNF)r   r   r   rZ   r   r   r   r8   r8   rf   r9   r     s       
$r   c                       sD   e Zd ZdZed fddZd	ejeej ejdddZ	  Z
S )
XLNetPoolerStartLogitsz
    Compute SQuAD start logits from sequence hidden states.

    Args:
        config ([`XLNetConfig`]):
            The config used by the model, will be used to grab the `hidden_size` of the model.
    r3   c                    s   t    t|jd| _d S r   )rY   rZ   r   r   hidden_sizedenserd   rf   r8   r9   rZ     s    
zXLNetPoolerStartLogits.__init__N)hidden_statesp_maskreturnc                 C   sR   |  |d}|durN|jtjkr:|d|  d|  }n|d|  d|  }|S )a  
        Args:
            hidden_states (`torch.FloatTensor` of shape `(batch_size, seq_len, hidden_size)`):
                The final hidden states of the model.
            p_mask (`torch.FloatTensor` of shape `(batch_size, seq_len)`, *optional*):
                Mask for tokens at invalid position, such as query and special symbols (PAD, SEP, CLS). 1.0 means token
                should be masked.

        Returns:
            `torch.FloatTensor`: The start logits for SQuAD.
        rl   Nr   ry   rz   )r   squeezero   rI   r~   )re   r   r   ru   r8   r8   r9   r     s    zXLNetPoolerStartLogits.forward)N)r   r   r   __doc__r   rZ   rI   r_   r   r   r   r8   r8   rf   r9   r     s    r   c                       sT   e Zd ZdZed fddZd	ejeej eej	 eej ejdddZ
  ZS )
XLNetPoolerEndLogitsz
    Compute SQuAD end logits from sequence hidden states.

    Args:
        config ([`XLNetConfig`]):
            The config used by the model, will be used to grab the `hidden_size` of the model and the `layer_norm_eps`
            to use.
    r   c                    sR   t    t|jd |j| _t | _tj|j|j	d| _t|jd| _
d S )NrV   rW   r   )rY   rZ   r   r   r   dense_0Tanh
activationr`   ra   dense_1rd   rf   r8   r9   rZ   <  s
    

zXLNetPoolerEndLogits.__init__N)r   start_statesstart_positionsr   r   c                 C   s   |dus|dusJ d|durh|j dd \}}|ddddf dd|}|d|}|d|d}| tj||gdd}| |}| |}| |	d}|dur|j
tjkr|d|  d|  }n|d|  d|  }|S )	a  
        Args:
            hidden_states (`torch.FloatTensor` of shape `(batch_size, seq_len, hidden_size)`):
                The final hidden states of the model.
            start_states (`torch.FloatTensor` of shape `(batch_size, seq_len, hidden_size)`, *optional*):
                The hidden states of the first tokens for the labeled span.
            start_positions (`torch.LongTensor` of shape `(batch_size,)`, *optional*):
                The position of the first token for the labeled span.
            p_mask (`torch.FloatTensor` of shape `(batch_size, seq_len)`, *optional*):
                Mask for tokens at invalid position, such as query and special symbols (PAD, SEP, CLS). 1.0 means token
                should be masked.

        <Tip>

        One of `start_states` or `start_positions` should be not `None`. If both are set, `start_positions` overrides
        `start_states`.

        </Tip>

        Returns:
            `torch.FloatTensor`: The end logits for SQuAD.
        N7One of start_states, start_positions should be not Nonerl   r{   r   ry   rz   )rF   expandgatherr   rI   r   r   r`   r   r   ro   r~   )re   r   r   r   r   slenhszru   r8   r8   r9   r   C  s"    

zXLNetPoolerEndLogits.forward)NNNr   r   r   r   r   rZ   rI   r_   r   
LongTensorr   r   r8   r8   rf   r9   r   2  s   	
   r   c                       sT   e Zd ZdZed fddZd	ejeej eej	 eej	 ejdddZ
  ZS )
XLNetPoolerAnswerClassz
    Compute SQuAD 2.0 answer class from classification and start tokens hidden states.

    Args:
        config ([`XLNetConfig`]):
            The config used by the model, will be used to grab the `hidden_size` of the model.
    r   c                    sB   t    t|jd |j| _t | _tj|jddd| _d S )NrV   r   Fr   )	rY   rZ   r   r   r   r   r   r   r   rd   rf   r8   r9   rZ     s    

zXLNetPoolerAnswerClass.__init__N)r   r   r   	cls_indexr   c                 C   s   |j d }|dus"|dus"J d|durX|ddddf dd|}|d|d}|dur|ddddf dd|}|d|d}n|dddddf }| tj||gdd}| |}| |d}|S )a  
        Args:
            hidden_states (`torch.FloatTensor` of shape `(batch_size, seq_len, hidden_size)`):
                The final hidden states of the model.
            start_states (`torch.FloatTensor` of shape `(batch_size, seq_len, hidden_size)`, *optional*):
                The hidden states of the first tokens for the labeled span.
            start_positions (`torch.LongTensor` of shape `(batch_size,)`, *optional*):
                The position of the first token for the labeled span.
            cls_index (`torch.LongTensor` of shape `(batch_size,)`, *optional*):
                Position of the CLS token for each sentence in the batch. If `None`, takes the last token.

        <Tip>

        One of `start_states` or `start_positions` should be not `None`. If both are set, `start_positions` overrides
        `start_states`.

        </Tip>

        Returns:
            `torch.FloatTensor`: The SQuAD 2.0 answer class.
        rl   Nr   r   r{   )	rF   r   r   r   r   rI   r   r   r   )re   r   r   r   r   r   Zcls_token_stateru   r8   r8   r9   r     s    

zXLNetPoolerAnswerClass.forward)NNNr   r8   r8   rf   r9   r   x  s   	   r   c                       sD   e Zd ZdZed fddZd	ejeej	 ejdddZ
  ZS )
XLNetSequenceSummarya  
    Compute a single vector summary of a sequence hidden states.

    Args:
        config ([`XLNetConfig`]):
            The config used by the model. Relevant arguments in the config class of the model are (refer to the actual
            config class of your model for the default values it uses):

            - **summary_type** (`str`) -- The method to use to make this summary. Accepted values are:

                - `"last"` -- Take the last token hidden state (like XLNet)
                - `"first"` -- Take the first token hidden state (like Bert)
                - `"mean"` -- Take the mean of all tokens hidden states
                - `"cls_index"` -- Supply a Tensor of classification token position (GPT/GPT-2)
                - `"attn"` -- Not implemented now, use multi-head attention

            - **summary_use_proj** (`bool`) -- Add a projection after the vector extraction.
            - **summary_proj_to_labels** (`bool`) -- If `True`, the projection outputs to `config.num_labels` classes
              (otherwise to `config.hidden_size`).
            - **summary_activation** (`Optional[str]`) -- Set to `"tanh"` to add a tanh activation to the output,
              another string or `None` will add no activation.
            - **summary_first_dropout** (`float`) -- Optional dropout probability before the projection and activation.
            - **summary_last_dropout** (`float`)-- Optional dropout probability after the projection and activation.
    r   c                    s   t    t|dd| _| jdkr&tt | _t|drx|j	rxt|drb|j
rb|jdkrb|j}n|j}t|j|| _t|dd }|rt|nt | _t | _t|dr|jdkrt|j| _t | _t|d	r|jdkrt|j| _d S )
Nsummary_typelastattnsummary_use_projsummary_proj_to_labelsr   Zsummary_activationsummary_first_dropoutsummary_last_dropout)rY   rZ   getattrr   rj   r   ZIdentityr   r   r   r   
num_labelsr   r   r   r   first_dropoutr   rb   last_dropoutr   )re   r3   num_classesZactivation_stringrf   r8   r9   rZ     s$    




zXLNetSequenceSummary.__init__N)r   r   r   c                 C   s  | j dkr|dddf }n| j dkr8|dddf }n| j dkrP|jdd}n| j d	kr|du rtj|d
ddddf |jd d tjd}n2|dd}|d| d  |	df }|
d|d}n| j dkrt| |}| |}| |}| |}|S )ak  
        Compute a single vector summary of a sequence hidden states.

        Args:
            hidden_states (`torch.FloatTensor` of shape `[batch_size, seq_len, hidden_size]`):
                The hidden states of the last layer.
            cls_index (`torch.LongTensor` of shape `[batch_size]` or `[batch_size, ...]` where ... are optional leading dimensions of `hidden_states`, *optional*):
                Used if `summary_type == "cls_index"` and takes the last token of the sequence as classification token.

        Returns:
            `torch.FloatTensor`: The summary of the sequence hidden states.
        r   Nrl   firstr   meanr   r{   r   .r   ro   )rl   r   )r   r   rI   Z	full_likerF   rs   	unsqueezer   r|   sizer   r   rj   r   r   r   r   )re   r   r   r   r8   r8   r9   r     s.    



"




zXLNetSequenceSummary.forward)Nr   r8   r8   rf   r9   r     s    r   c                   @   s&   e Zd ZU eed< eZdZdd ZdS )XLNetPreTrainedModelr3   r   c              	   C   s  t |tjr:|jjjd| jjd |jdur8|jj	  nt |tj
rz|jjjd| jjd |jdurx|jj|j 	  nt |tjr|jj	  |jjd npt |tr|j|j|j|j|j|j|j|j|jf	D ]}|jjd| jjd qn"t |tr|jjjd| jjd dS )zInitialize the weights.g        )r   ZstdN      ?)rC   r   r   r   rJ   Znormal_r3   Zinitializer_ranger   Zzero_	EmbeddingZpadding_idxr`   Zfill_rT   r&   r'   r)   r%   r(   r.   r0   r/   r1   
XLNetModelr    )re   moduleparamr8   r8   r9   _init_weights#  s2    


z"XLNetPreTrainedModel._init_weightsN)	r   r   r   r   __annotations__rS   Zload_tf_weightsZbase_model_prefixr   r8   r8   r8   r9   r     s   
r   z(
    Output type of [`XLNetModel`].
    )Zcustom_introc                   @   sf   e Zd ZU dZejed< dZee	ej  ed< dZ
eeejdf  ed< dZeeejdf  ed< dS )XLNetModelOutputa  
    last_hidden_state (`torch.FloatTensor` of shape `(batch_size, num_predict, hidden_size)`):
        Sequence of hidden-states at the last layer of the model.

        `num_predict` corresponds to `target_mapping.shape[1]`. If `target_mapping` is `None`, then `num_predict`
        corresponds to `sequence_length`.
    mems (`list[torch.FloatTensor]` of length `config.n_layers`):
        Contains pre-computed hidden-states. Can be used (see `mems` input) to speed up sequential decoding. The
        token ids which have their past given to this model should not be passed as `input_ids` as they have
        already been computed.
    last_hidden_stateNr   .r   
attentions)r   r   r   r   rI   r_   r   r   r   rD   r   tupler   r8   r8   r8   r9   r   C  s
   

r   z.
    Output type of [`XLNetLMHeadModel`].
    c                   @   s   e Zd ZU dZdZeej ed< dZ	eej ed< dZ
eeej  ed< dZeeejdf  ed< dZeeejdf  ed< dS )	XLNetLMHeadModelOutputaB  
    loss (`torch.FloatTensor` of shape *(1,)*, *optional*, returned when `labels` is provided):
        Language modeling loss (for next-token prediction).
    logits (`torch.FloatTensor` of shape `(batch_size, num_predict, config.vocab_size)`):
        Prediction scores of the language modeling head (scores for each vocabulary token before SoftMax).

        `num_predict` corresponds to `target_mapping.shape[1]`. If `target_mapping` is `None`, then `num_predict`
        corresponds to `sequence_length`.
    mems (`list[torch.FloatTensor]` of length `config.n_layers`):
        Contains pre-computed hidden-states. Can be used (see `mems` input) to speed up sequential decoding. The
        token ids which have their past given to this model should not be passed as `input_ids` as they have
        already been computed.
    Nlosslogitsr   .r   r   r   r   r   r   r   r   rI   r_   r   r   r   rD   r   r   r   r8   r8   r8   r9   r   \  s   
r   z<
    Output type of [`XLNetForSequenceClassification`].
    c                   @   s   e Zd ZU dZdZeej ed< dZ	eej ed< dZ
eeej  ed< dZeeejdf  ed< dZeeejdf  ed< dS )	$XLNetForSequenceClassificationOutputa  
    loss (`torch.FloatTensor` of shape `(1,)`, *optional*, returned when `label` is provided):
        Classification (or regression if config.num_labels==1) loss.
    logits (`torch.FloatTensor` of shape `(batch_size, config.num_labels)`):
        Classification (or regression if config.num_labels==1) scores (before SoftMax).
    mems (`list[torch.FloatTensor]` of length `config.n_layers`):
        Contains pre-computed hidden-states. Can be used (see `mems` input) to speed up sequential decoding. The
        token ids which have their past given to this model should not be passed as `input_ids` as they have
        already been computed.
    Nr   r   r   .r   r   r   r8   r8   r8   r9   r   x  s   
r   z?
    Output type of [`XLNetForTokenClassificationOutput`].
    c                   @   s   e Zd ZU dZdZeej ed< dZ	eej ed< dZ
eeej  ed< dZeeejdf  ed< dZeeejdf  ed< dS )	!XLNetForTokenClassificationOutputaO  
    loss (`torch.FloatTensor` of shape `(1,)`, *optional*, returned when `labels` is provided):
        Classification loss.
    logits (`torch.FloatTensor` of shape `(batch_size, sequence_length, config.num_labels)`):
        Classification scores (before SoftMax).
    mems (`list[torch.FloatTensor]` of length `config.n_layers`):
        Contains pre-computed hidden-states. Can be used (see `mems` input) to speed up sequential decoding. The
        token ids which have their past given to this model should not be passed as `input_ids` as they have
        already been computed.
    Nr   r   r   .r   r   r   r8   r8   r8   r9   r     s   
r   z4
    Output type of [`XLNetForMultipleChoice`].
    c                   @   s   e Zd ZU dZdZeej ed< dZ	eej ed< dZ
eeej  ed< dZeeejdf  ed< dZeeejdf  ed< dS )	XLNetForMultipleChoiceOutputa  
    loss (`torch.FloatTensor` of shape *(1,)*, *optional*, returned when `labels` is provided):
        Classification loss.
    logits (`torch.FloatTensor` of shape `(batch_size, num_choices)`):
        *num_choices* is the second dimension of the input tensors. (see *input_ids* above).

        Classification scores (before SoftMax).
    mems (`list[torch.FloatTensor]` of length `config.n_layers`):
        Contains pre-computed hidden-states. Can be used (see `mems` input) to speed up sequential decoding. The
        token ids which have their past given to this model should not be passed as `input_ids` as they have
        already been computed.
    Nr   r   r   .r   r   r   r8   r8   r8   r9   r     s   
r   z=
    Output type of [`XLNetForQuestionAnsweringSimple`].
    c                   @   s   e Zd ZU dZdZeej ed< dZ	eej ed< dZ
eej ed< dZeeej  ed< dZeeejdf  ed< dZeeejdf  ed	< dS )
%XLNetForQuestionAnsweringSimpleOutputa  
    loss (`torch.FloatTensor` of shape `(1,)`, *optional*, returned when `labels` is provided):
        Total span extraction loss is the sum of a Cross-Entropy for the start and end positions.
    start_logits (`torch.FloatTensor` of shape `(batch_size, sequence_length,)`):
        Span-start scores (before SoftMax).
    end_logits (`torch.FloatTensor` of shape `(batch_size, sequence_length,)`):
        Span-end scores (before SoftMax).
    mems (`list[torch.FloatTensor]` of length `config.n_layers`):
        Contains pre-computed hidden-states. Can be used (see `mems` input) to speed up sequential decoding. The
        token ids which have their past given to this model should not be passed as `input_ids` as they have
        already been computed.
    Nr   start_logits
end_logitsr   .r   r   )r   r   r   r   r   r   rI   r_   r   r   r   r   rD   r   r   r   r8   r8   r8   r9   r     s   
r   z7
    Output type of [`XLNetForQuestionAnswering`].
    c                   @   s   e Zd ZU dZdZeej ed< dZ	eej ed< dZ
eej ed< dZeej ed< dZeej ed< dZeej ed< dZeeej  ed	< dZeeejd
f  ed< dZeeejd
f  ed< dS )XLNetForQuestionAnsweringOutputax  
    loss (`torch.FloatTensor` of shape `(1,)`, *optional*, returned if both `start_positions` and `end_positions` are provided):
        Classification loss as the sum of start token, end token (and is_impossible if provided) classification
        losses.
    start_top_log_probs (`torch.FloatTensor` of shape `(batch_size, config.start_n_top)`, *optional*, returned if `start_positions` or `end_positions` is not provided):
        Log probabilities for the top config.start_n_top start token possibilities (beam-search).
    start_top_index (`torch.LongTensor` of shape `(batch_size, config.start_n_top)`, *optional*, returned if `start_positions` or `end_positions` is not provided):
        Indices for the top config.start_n_top start token possibilities (beam-search).
    end_top_log_probs (`torch.FloatTensor` of shape `(batch_size, config.start_n_top * config.end_n_top)`, *optional*, returned if `start_positions` or `end_positions` is not provided):
        Log probabilities for the top `config.start_n_top * config.end_n_top` end token possibilities
        (beam-search).
    end_top_index (`torch.LongTensor` of shape `(batch_size, config.start_n_top * config.end_n_top)`, *optional*, returned if `start_positions` or `end_positions` is not provided):
        Indices for the top `config.start_n_top * config.end_n_top` end token possibilities (beam-search).
    cls_logits (`torch.FloatTensor` of shape `(batch_size,)`, *optional*, returned if `start_positions` or `end_positions` is not provided):
        Log probabilities for the `is_impossible` label of the answers.
    mems (`list[torch.FloatTensor]` of length `config.n_layers`):
        Contains pre-computed hidden-states. Can be used (see `mems` input) to speed up sequential decoding. The
        token ids which have their past given to this model should not be passed as `input_ids` as they have
        already been computed.
    Nr   start_top_log_probsstart_top_indexend_top_log_probsend_top_index
cls_logitsr   .r   r   )r   r   r   r   r   r   rI   r_   r   r   r   r   r   r   r   r   rD   r   r   r   r8   r8   r8   r9   r     s   
r   c                       s   e Zd Z fddZdd Zdd Zdd Zd	d
 Zdd Ze	dddZ
dddZe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j ee ee ee ee eeef dddZ  ZS )r   c                    s   t     j| _ j| _ j| _ j| _ j| _ j| _ j| _ j	| _	t
 j j| _t
tdd j| _t
 fddt j	D | _t
 j| _|   d S )Nr   c                    s   g | ]}t  qS r8   )r   ).0_r   r8   r9   
<listcomp>      z'XLNetModel.__init__.<locals>.<listcomp>)rY   rZ   mem_len	reuse_lenr[   same_length	attn_typebi_data	clamp_lenn_layerr   r   
vocab_sizer   r^   rI   r_   r    Z
ModuleListranger"   rb   rc   	post_initrd   rf   r   r9   rZ   
  s     zXLNetModel.__init__c                 C   s   | j S rh   r   re   r8   r8   r9   get_input_embeddings  s    zXLNetModel.get_input_embeddingsc                 C   s
   || _ d S rh   r   re   Znew_embeddingsr8   r8   r9   set_input_embeddings!  s    zXLNetModel.set_input_embeddingsc                 C   s   t d S rh   ri   )re   Zheads_to_pruner8   r8   r9   _prune_heads$  s    zXLNetModel._prune_headsc                 C   sv   t j||| f| jd}| jrd|ddd|f d}||d  |ddd|f  |7  < n||d  |S )aD  
        Creates causal attention mask. Float mask where 1.0 indicates masked, 0.0 indicates not-masked.

        Args:
            qlen: Sequence length
            mlen: Mask length

        ::

                  same_length=False: same_length=True: <mlen > < qlen > <mlen > < qlen >
               ^ [0 0 0 0 0 1 1 1 1] [0 0 0 0 0 1 1 1 1]
                 [0 0 0 0 0 0 1 1 1] [1 0 0 0 0 0 1 1 1]
            qlen [0 0 0 0 0 0 0 1 1] [1 1 0 0 0 0 0 1 1]
                 [0 0 0 0 0 0 0 0 1] [1 1 1 0 0 0 0 0 1]
               v [0 0 0 0 0 0 0 0 0] [1 1 1 1 0 0 0 0 0]

        )rn   Nrl   r   )rI   Zonesrn   r   ZtrilZtriu_)re   qlenmlenmaskZmask_lor8   r8   r9   create_mask'  s    zXLNetModel.create_maskc                 C   s|   | j d ur"| j dkr"|d | j  }| jd u s6| jdkr<d}n| j }|d u rZ||d  }ntj||gdd|d  }| S )Nr   r{   )r   r   rI   r   detach)re   Zcurr_outZprev_memcutoffZnew_memr8   r8   r9   	cache_memC  s    zXLNetModel.cache_memNc                 C   s\   t d| |}t jt |t |gdd}|d d d d d f }|d urX|d|d}|S )Nzi,d->idrl   r{   )rI   r}   r   sincosr   )Zpos_seqinv_freqbszZsinusoid_inppos_embr8   r8   r9   positional_embeddingX  s    zXLNetModel.positional_embeddingc                 C   s~  t jd| jdt jd }dt d|| j  }| jdkrH||  }}n(| jdkr^|d }}ntd	| j d
| jr6t j||dt jd }t j| | dt jd }	| j	dkr|
| j	 | j	}|	
| j	 | j	}	|d ur
| |||d }
| |	||d }n| ||}
| |	|}t j|
|gdd}nDt j||dt jd }| j	dkrl|
| j	 | j	}| |||}|S )Nr   g       @r   r   i'  biunirl   zUnknown `attn_type` .g      r   rV   r{   )rI   rr   r[   Zint64floatpowr   r\   r   r   clampr  r   )re   r  rv   r  Zfreq_seqr  begendZfwd_pos_seqZbwd_pos_seqZfwd_pos_embZbwd_pos_embr  r8   r8   r9   relative_positional_encodingc  s0    



z'XLNetModel.relative_positional_encoding)	input_idsattention_maskr   	perm_maskr   token_type_ids
input_maskr   inputs_embedsuse_memsr   output_hidden_statesreturn_dictr   c           (      K   s:  |dur|n| j j}|dur |n| j j}|dur4|n| j j}d|v rXtdt |d }
| jrt|
durj|
n| j j}
n|
dur|
n| j j	}
|dur|	durt
dnj|dur|dd }|jd |jd  }}n:|	dur|	dd }	|	jd |	jd  }}nt
d|dur&|dd nd}|durD|dd nd}|durb|dd nd}|dur|ddd nd}|dur|ddd nd}|dur|d dur|d jd nd}|| }| j}| j}| jd	kr| ||}|ddddddf }n"| jd
kr(d}nt
d| j |du sT|du sTJ d|du rp|durpd| }|dur|dur|d | }n<|dur|du r|d }n|du r|dur|}nd}|durX|dkrt|jd ||g|}tj||gdd}|du r8|dddddddf }n ||dddddddf 7 }|durp|dk|}|durt|| }|dkrtjt||g||gdd}||ddddddf  dk|}nd}|	dur|	}n
| |}| |}|dur4| j|jd |d}| |}nd}|dur|dkrvtj||gtj|d}tj||gdd}n|}|dddf |dddf k }tjj|dd|}nd}| j |||d} | |j} | | } |durf|! dkr*|"d"d"d"d}|| j#dddd}n$|! dkrN|"d"d"d}|jt$| % jd}ndg| j# }d}!|du rdgt&| j' }|rg nd}"|rg nd}#t(| j'D ]\}$}%|
r|!| )|||$ f }!|r|#*|dur||fn| |%||||| |||$ |||$ |d
}&|&dd \}}|r|"*|&d  q|rj|#*|durd||fn| | |dur||n|}'|'ddd }'|
sd}!|r|durt+dd |#D }#nt+dd |#D }#|r
|durt+dd |"D }"nt+dd |"D }"|s*t+dd |'|!|#|"fD S t,|'|!|#|"dS )  
        mems (`list[torch.FloatTensor]` of length `config.n_layers`):
            Contains pre-computed hidden-states (see `mems` output below) . Can be used to speed up sequential
            decoding. The token ids which have their past given to this model should not be passed as `input_ids` as
            they have already been computed.

            `use_mems` has to be set to `True` to make use of `mems`.
        perm_mask (`torch.FloatTensor` of shape `(batch_size, sequence_length, sequence_length)`, *optional*):
            Mask to indicate the attention pattern for each input token with values selected in `[0, 1]`:

            - if `perm_mask[k, i, j] = 0`, i attend to j in batch k;
            - if `perm_mask[k, i, j] = 1`, i does not attend to j in batch k.

            If not set, each token attends to all the others (full bidirectional attention). Only used during
            pretraining (to define factorization order) or for sequential decoding (generation).
        target_mapping (`torch.FloatTensor` of shape `(batch_size, num_predict, sequence_length)`, *optional*):
            Mask to indicate the output tokens to use. If `target_mapping[k, i, j] = 1`, the i-th predict in batch k is
            on the j-th token. Only used during pretraining for partial prediction or for sequential decoding
            (generation).
        input_mask (`torch.FloatTensor` of shape `batch_size, sequence_length`, *optional*):
            Mask to avoid performing attention on padding token indices. Negative of `attention_mask`, i.e. with 0 for
            real tokens and 1 for padding which is kept for compatibility with the original code base.

            Mask values selected in `[0, 1]`:

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

            You can only uses one of `input_mask` and `attention_mask`.
        use_mems (`bool`, *optional*):
            Whether to use memory states to speed up sequential decoding. If set to `True`, the model will use the hidden
            states from previous forward passes to compute attention, which can significantly improve performance for
            sequential decoding tasks.
        NZ	use_cachezgThe `use_cache` argument is deprecated and will be removed in a future version, use `use_mems` instead.zDYou cannot specify both input_ids and inputs_embeds at the same timer   r   z5You have to specify either input_ids or inputs_embedsrV   r  r  zUnsupported attention type: z8You can only use one of input_mask (uses 1 for padding) r   r{   rl   ro   rn   )r   )r  r   r8   )r   r   r(   r   r   r   r   r   c                 s   s*   | ]"}|D ]}| d dd V  q
qdS r   r   rV   Npermute
contiguous)r   hsr   r8   r8   r9   	<genexpr>v  r   z%XLNetModel.forward.<locals>.<genexpr>c                 s   s    | ]}| d dd V  qdS r'  r(  )r   r+  r8   r8   r9   r,  x  r   c                 s   s    | ]}t d d |D V  qdS )c                 s   s"   | ]}| d ddd V  qdS rV   r
   r   r   Nr(  )r   Z
att_streamr8   r8   r9   r,  ~  r   z/XLNetModel.forward.<locals>.<genexpr>.<genexpr>N)r   r   tr8   r8   r9   r,  }  s   c                 s   s"   | ]}| d ddd V  qdS r-  r(  r.  r8   r8   r9   r,    r   c                 s   s   | ]}|d ur|V  qd S rh   r8   )r   r)   r8   r8   r9   r,    r   )r   r   r   r   )-r3   r   r#  use_return_dictwarningswarnFutureWarningZtrainingZuse_mems_trainZuse_mems_evalr\   rB   r*  rF   r)  ro   rn   r   r	  rI   zerostor   eyer   rc   r    r   rs   r   r   Zone_hotr  r|   r   r   next
parametersrE   r"   r!   r  r-   r   r   )(re   r  r  r   r  r   r  r   r   r!  r"  r   r#  r$  kwargsr  r  r  rv   Zdtype_floatrn   r   Z	data_maskZ	mems_maskZnon_tgt_maskZ
word_emb_kr   Z
word_emb_qr   Zmem_padZcat_idsr   r  Znew_memsr   r   r6   Zlayer_moduler   r   r8   r8   r9   r     s   4

  *



 


"(





$





zXLNetModel.forward)N)N)NNNNNNNNNNNNN)r   r   r   rZ   r  r  r  r	  r  r   r  r  r   r   rI   Tensorboolr   r   r   r   r   r8   r8   rf   r9   r     sN   

&             
r   zt
    XLNet Model with a language modeling head on top (linear layer with weights tied to the input embeddings).
    c                       s   e Zd ZdgZ fddZdd Zdd Zdd	d
Ze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
j e	e
j e	e e	e e	e e	e eeef dddZeee
j e
jee
j dddZ  ZS )XLNetLMHeadModelzlm_loss.weightc                    sH   t  | |j| _|j| _t|| _tj|j|j	dd| _
|   d S )NTr   )rY   rZ   r   r   r   r   r   r   r[   r   r   r   rd   rf   r8   r9   rZ     s    
zXLNetLMHeadModel.__init__c                 C   s   | j S rh   r   r  r8   r8   r9   get_output_embeddings  s    z&XLNetLMHeadModel.get_output_embeddingsc                 C   s
   || _ d S rh   r=  r  r8   r8   r9   set_output_embeddings  s    z&XLNetLMHeadModel.set_output_embeddingsNc                    s   |j d }tj|dftj|jd}d |rPtj|d d   d f |gdd}ntj||gdd}|j d }tj|||ftj|jd}d|d d d d df< tj|d|ftj|jd}	d|	d d ddf< |||	|d}
|rt fd	d
|D |
d< |
S )Nr   r   r&  rV   r{   r   rl   )r  r  r   r"  c                 3   s*   | ]"}|d   d d d d f V  qd S rh   r8   r   Z
layer_pastoffsetr8   r9   r,    r   zAXLNetLMHeadModel.prepare_inputs_for_generation.<locals>.<genexpr>r   )rF   rI   r4  rs   rn   r   r  r   )re   r  Zpast_key_valuesr"  r9  Zeffective_batch_sizeZdummy_tokenZsequence_lengthr  r   inputsr8   rA  r9   prepare_inputs_for_generation  s.    
&
z.XLNetLMHeadModel.prepare_inputs_for_generationr  r  r   r  r   r  r   r   r!  labelsr"  r   r#  r$  r   c                 K   s   |dur|n| j j}| j|f||||||||	||||d|}| |d }d}|
dur~t }||d|d|
d}|s|f|dd  }|dur|f| S |S t|||j|j	|j
dS )a  
        mems (`list[torch.FloatTensor]` of length `config.n_layers`):
            Contains pre-computed hidden-states (see `mems` output below) . Can be used to speed up sequential
            decoding. The token ids which have their past given to this model should not be passed as `input_ids` as
            they have already been computed.

            `use_mems` has to be set to `True` to make use of `mems`.
        perm_mask (`torch.FloatTensor` of shape `(batch_size, sequence_length, sequence_length)`, *optional*):
            Mask to indicate the attention pattern for each input token with values selected in `[0, 1]`:

            - if `perm_mask[k, i, j] = 0`, i attend to j in batch k;
            - if `perm_mask[k, i, j] = 1`, i does not attend to j in batch k.

            If not set, each token attends to all the others (full bidirectional attention). Only used during
            pretraining (to define factorization order) or for sequential decoding (generation).
        target_mapping (`torch.FloatTensor` of shape `(batch_size, num_predict, sequence_length)`, *optional*):
            Mask to indicate the output tokens to use. If `target_mapping[k, i, j] = 1`, the i-th predict in batch k is
            on the j-th token. Only used during pretraining for partial prediction or for sequential decoding
            (generation).
        input_mask (`torch.FloatTensor` of shape `batch_size, sequence_length`, *optional*):
            Mask to avoid performing attention on padding token indices. Negative of `attention_mask`, i.e. with 0 for
            real tokens and 1 for padding which is kept for compatibility with the original code base.

            Mask values selected in `[0, 1]`:

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

            You can only uses one of `input_mask` and `attention_mask`.
        labels (`torch.LongTensor` of shape `(batch_size, num_predict)`, *optional*):
            Labels for masked language modeling. `num_predict` corresponds to `target_mapping.shape[1]`. If
            `target_mapping` is `None`, then `num_predict` corresponds to `sequence_length`.

            The labels should correspond to the masked input words that should be predicted and depends on
            `target_mapping`. Note in order to perform standard auto-regressive language modeling a *<mask>* token has
            to be added to the `input_ids` (see the `prepare_inputs_for_generation` function and examples below)

            Indices are selected in `[-100, 0, ..., config.vocab_size]` All labels set to `-100` are ignored, the loss
            is only computed for labels in `[0, ..., config.vocab_size]`
        use_mems (`bool`, *optional*):
            Whether to use memory states to speed up sequential decoding. If set to `True`, the model will use the hidden
            states from previous forward passes to compute attention, which can significantly improve performance for
            sequential decoding tasks.

        Examples:

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

        >>> tokenizer = AutoTokenizer.from_pretrained("xlnet/xlnet-large-cased")
        >>> model = XLNetLMHeadModel.from_pretrained("xlnet/xlnet-large-cased")

        >>> # We show how to setup inputs to predict a next token using a bi-directional context.
        >>> input_ids = torch.tensor(
        ...     tokenizer.encode("Hello, my dog is very <mask>", add_special_tokens=False)
        ... ).unsqueeze(
        ...     0
        ... )  # We will predict the masked token
        >>> perm_mask = torch.zeros((1, input_ids.shape[1], input_ids.shape[1]), dtype=torch.float)
        >>> perm_mask[:, :, -1] = 1.0  # Previous tokens don't see last token
        >>> target_mapping = torch.zeros(
        ...     (1, 1, input_ids.shape[1]), dtype=torch.float
        ... )  # Shape [1, 1, seq_length] => let's predict one token
        >>> target_mapping[
        ...     0, 0, -1
        ... ] = 1.0  # Our first (and only) prediction will be the last token of the sequence (the masked token)

        >>> outputs = model(input_ids, perm_mask=perm_mask, target_mapping=target_mapping)
        >>> next_token_logits = outputs[
        ...     0
        ... ]  # Output has shape [target_mapping.size(0), target_mapping.size(1), config.vocab_size]

        >>> # The same way can the XLNetLMHeadModel be used to be trained by standard auto-regressive language modeling.
        >>> input_ids = torch.tensor(
        ...     tokenizer.encode("Hello, my dog is very <mask>", add_special_tokens=False)
        ... ).unsqueeze(
        ...     0
        ... )  # We will predict the masked token
        >>> labels = torch.tensor(tokenizer.encode("cute", add_special_tokens=False)).unsqueeze(0)
        >>> assert labels.shape[0] == 1, "only one word will be predicted"
        >>> perm_mask = torch.zeros((1, input_ids.shape[1], input_ids.shape[1]), dtype=torch.float)
        >>> perm_mask[
        ...     :, :, -1
        ... ] = 1.0  # Previous tokens don't see last token as is done in standard auto-regressive lm training
        >>> target_mapping = torch.zeros(
        ...     (1, 1, input_ids.shape[1]), dtype=torch.float
        ... )  # Shape [1, 1, seq_length] => let's predict one token
        >>> target_mapping[
        ...     0, 0, -1
        ... ] = 1.0  # Our first (and only) prediction will be the last token of the sequence (the masked token)

        >>> outputs = model(input_ids, perm_mask=perm_mask, target_mapping=target_mapping, labels=labels)
        >>> loss = outputs.loss
        >>> next_token_logits = (
        ...     outputs.logits
        ... )  # Logits have shape [target_mapping.size(0), target_mapping.size(1), config.vocab_size]
        ```Nr  r   r  r   r  r   r   r!  r"  r   r#  r$  r   rl   r   r   r   r   r   r   )r3   r0  r   r   r   viewr   r   r   r   r   )re   r  r  r   r  r   r  r   r   r!  rF  r"  r   r#  r$  r9  transformer_outputsr   r   loss_fctr   r8   r8   r9   r     sD    uzXLNetLMHeadModel.forward)r   beam_idxr   c                    s    fdd| D S )z
        This function is used to re-order the `mems` cache if [`~PreTrainedModel.beam_search`] or
        [`~PreTrainedModel.beam_sample`] is called. This is required to match `mems` with the correct beam_idx at every
        generation step.
        c                    s    g | ]}| d  |jqS )r   )rq   r5  rn   r@  rL  r8   r9   r   s  r   z3XLNetLMHeadModel._reorder_cache.<locals>.<listcomp>r8   )r   rL  r8   rM  r9   _reorder_cachel  s    zXLNetLMHeadModel._reorder_cache)NN)NNNNNNNNNNNNNN)r   r   r   Z_tied_weights_keysrZ   r>  r?  rD  r   r   rI   r:  r;  r   r   r   r   r   rD   rN  r   r8   r8   rf   r9   r<    sP   
,              
 r<  z
    XLNet Model 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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j eej ee ee ee ee e	e
ef dddZ  ZS )XLNetForSequenceClassificationc                    sL   t  | |j| _|| _t|| _t|| _t	|j
|j| _|   d S rh   )rY   rZ   r   r3   r   r   r   r   r   r   r[   r   r   rd   rf   r8   r9   rZ   }  s    

z'XLNetForSequenceClassification.__init__NrE  c                 K   s  |dur|n| j j}| j|f||||||||	||||d|}|d }| |}| |}d}|
durH| j jdu r| jdkrd| 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rHt }|||
}|sx|f|dd  }|durt|f| S |S t|||j|j|jd	S )
a.
  
        mems (`list[torch.FloatTensor]` of length `config.n_layers`):
            Contains pre-computed hidden-states (see `mems` output below) . Can be used to speed up sequential
            decoding. The token ids which have their past given to this model should not be passed as `input_ids` as
            they have already been computed.

            `use_mems` has to be set to `True` to make use of `mems`.
        perm_mask (`torch.FloatTensor` of shape `(batch_size, sequence_length, sequence_length)`, *optional*):
            Mask to indicate the attention pattern for each input token with values selected in `[0, 1]`:

            - if `perm_mask[k, i, j] = 0`, i attend to j in batch k;
            - if `perm_mask[k, i, j] = 1`, i does not attend to j in batch k.

            If not set, each token attends to all the others (full bidirectional attention). Only used during
            pretraining (to define factorization order) or for sequential decoding (generation).
        target_mapping (`torch.FloatTensor` of shape `(batch_size, num_predict, sequence_length)`, *optional*):
            Mask to indicate the output tokens to use. If `target_mapping[k, i, j] = 1`, the i-th predict in batch k is
            on the j-th token. Only used during pretraining for partial prediction or for sequential decoding
            (generation).
        input_mask (`torch.FloatTensor` of shape `batch_size, sequence_length`, *optional*):
            Mask to avoid performing attention on padding token indices. Negative of `attention_mask`, i.e. with 0 for
            real tokens and 1 for padding which is kept for compatibility with the original code base.

            Mask values selected in `[0, 1]`:

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

            You can only uses one of `input_mask` and `attention_mask`.
        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).
        use_mems (`bool`, *optional*):
            Whether to use memory states to speed up sequential decoding. If set to `True`, the model will use the hidden
            states from previous forward passes to compute attention, which can significantly improve performance for
            sequential decoding tasks.
        NrG  r   r   Z
regressionZsingle_label_classificationZmulti_label_classificationrl   rH  )r3   r0  r   r   r   Zproblem_typer   ro   rI   rs   intr	   r   r   rI  r   r   r   r   r   )re   r  r  r   r  r   r  r   r   r!  rF  r"  r   r#  r$  r9  rJ  r   r   r   rK  r8   r8   r9   r     sf    9




"


z&XLNetForSequenceClassification.forward)NNNNNNNNNNNNNN)r   r   r   rZ   r   r   rI   r:  r;  r   r   r   r   r   r8   r8   rf   r9   rO  v  sB                 
rO  c                       s   e Zd Z fddZe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j eej ee ee ee ee e	e
ef dddZ  ZS )XLNetForTokenClassificationc                    s<   t  | |j| _t|| _t|j|j| _| 	  d S rh   )
rY   rZ   r   r   r   r   r   r   
classifierr   rd   rf   r8   r9   rZ     s
    
z$XLNetForTokenClassification.__init__NrE  c                 K   s   |dur|n| j j}| j|||||||||	||||d}|d }| |}d}|
durvt }||d| j|
d}|s|f|dd  }|dur|f| S |S t|||j|j	|j
dS )a
  
        mems (`list[torch.FloatTensor]` of length `config.n_layers`):
            Contains pre-computed hidden-states (see `mems` output below) . Can be used to speed up sequential
            decoding. The token ids which have their past given to this model should not be passed as `input_ids` as
            they have already been computed.

            `use_mems` has to be set to `True` to make use of `mems`.
        perm_mask (`torch.FloatTensor` of shape `(batch_size, sequence_length, sequence_length)`, *optional*):
            Mask to indicate the attention pattern for each input token with values selected in `[0, 1]`:

            - if `perm_mask[k, i, j] = 0`, i attend to j in batch k;
            - if `perm_mask[k, i, j] = 1`, i does not attend to j in batch k.

            If not set, each token attends to all the others (full bidirectional attention). Only used during
            pretraining (to define factorization order) or for sequential decoding (generation).
        target_mapping (`torch.FloatTensor` of shape `(batch_size, num_predict, sequence_length)`, *optional*):
            Mask to indicate the output tokens to use. If `target_mapping[k, i, j] = 1`, the i-th predict in batch k is
            on the j-th token. Only used during pretraining for partial prediction or for sequential decoding
            (generation).
        input_mask (`torch.FloatTensor` of shape `batch_size, sequence_length`, *optional*):
            Mask to avoid performing attention on padding token indices. Negative of `attention_mask`, i.e. with 0 for
            real tokens and 1 for padding which is kept for compatibility with the original code base.

            Mask values selected in `[0, 1]`:

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

            You can only uses one of `input_mask` and `attention_mask`.
        labels (`torch.LongTensor` of shape `(batch_size,)`, *optional*):
            Labels for computing the multiple choice classification loss. Indices should be in `[0, ..., num_choices]`
            where *num_choices* is the size of the second dimension of the input tensors. (see *input_ids* above)
        use_mems (`bool`, *optional*):
            Whether to use memory states to speed up sequential decoding. If set to `True`, the model will use the hidden
            states from previous forward passes to compute attention, which can significantly improve performance for
            sequential decoding tasks.emory states to speed up sequential decoding. If set to `True`, the model will use the hidden
            states from previous forward passes to compute attention, which can significantly improve performance for
            sequential decoding tasks.
        NrG  r   rl   r   rH  )r3   r0  r   rR  r   rI  r   r   r   r   r   )re   r  r  r   r  r   r  r   r   r!  rF  r"  r   r#  r$  r9  r   sequence_outputr   r   rK  r   r8   r8   r9   r   	  s@    :
z#XLNetForTokenClassification.forward)NNNNNNNNNNNNNN)r   r   r   rZ   r   r   rI   r:  r;  r   r   r   r   r   r8   r8   rf   r9   rQ    sB   
              
rQ  c                       s   e Zd Z fddZe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j eej ee ee ee ee e	e
ef dddZ  ZS )XLNetForMultipleChoicec                    s<   t  | t|| _t|| _t|jd| _	| 
  d S r   )rY   rZ   r   r   r   r   r   r   r[   r   r   rd   rf   r8   r9   rZ   m  s
    

zXLNetForMultipleChoice.__init__N)r  r  r   r  r   r  r   r   r!  rF  r"  r   r#  r$  r   c                 K   s  |dur|n| j j}|dur&|jd n|	jd }|durJ|d|dnd}|durh|d|dnd}|dur|d|dnd}|dur|d|dnd}|	dur|	d|	d|	dnd}| j|f||||||||||||d|}|d }| |}| |}|d|}d}|
durFt }|||
d}|sv|f|dd  }|durr|f| S |S t	|||j
|j|jdS )a&  
        input_ids (`torch.LongTensor` of shape `(batch_size, num_choices, sequence_length)`):
            Indices of input sequence tokens in the vocabulary.

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

            [What are input IDs?](../glossary#input-ids)
        token_type_ids (`torch.LongTensor` of shape `(batch_size, num_choices, sequence_length)`, *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)
        input_mask (`torch.FloatTensor` of shape `batch_size, num_choices, sequence_length`, *optional*):
            Mask to avoid performing attention on padding token indices. Negative of `attention_mask`, i.e. with 0 for
            real tokens and 1 for padding which is kept for compatibility with the original code base.

            Mask values selected in `[0, 1]`:

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

            You can only uses one of `input_mask` and `attention_mask`.
        mems (`list[torch.FloatTensor]` of length `config.n_layers`):
            Contains pre-computed hidden-states (see `mems` output below) . Can be used to speed up sequential
            decoding. The token ids which have their past given to this model should not be passed as `input_ids` as
            they have already been computed.

            `use_mems` has to be set to `True` to make use of `mems`.
        perm_mask (`torch.FloatTensor` of shape `(batch_size, sequence_length, sequence_length)`, *optional*):
            Mask to indicate the attention pattern for each input token with values selected in `[0, 1]`:

            - if `perm_mask[k, i, j] = 0`, i attend to j in batch k;
            - if `perm_mask[k, i, j] = 1`, i does not attend to j in batch k.

            If not set, each token attends to all the others (full bidirectional attention). Only used during
            pretraining (to define factorization order) or for sequential decoding (generation).
        target_mapping (`torch.FloatTensor` of shape `(batch_size, num_predict, sequence_length)`, *optional*):
            Mask to indicate the output tokens to use. If `target_mapping[k, i, j] = 1`, the i-th predict in batch k is
            on the j-th token. Only used during pretraining for partial prediction or for sequential decoding
            (generation).
        inputs_embeds (`torch.FloatTensor` of shape `(batch_size, num_choices, sequence_length, hidden_size)`, *optional*):
            Optionally, instead of passing `input_ids` you can choose to directly pass an embedded representation. This
            is useful if you want more control over how to convert `input_ids` indices into associated vectors than the
            model's internal embedding lookup matrix.
        labels (`torch.LongTensor` of shape `(batch_size,)`, *optional*):
            Labels for computing the multiple choice classification loss. Indices should be in `[0, ...,
        use_mems (`bool`, *optional*):
            Whether to use memory states to speed up sequential decoding. If set to `True`, the model will use the hidden
            states from previous forward passes to compute attention, which can significantly improve performance for
            sequential decoding tasks.
        Nr   rl   r   )r  r   r  r   r  r   r   r!  r"  r   r#  r$  r   rH  )r3   r0  rF   rI  r   r   r   r   r   r   r   r   r   )re   r  r  r   r  r   r  r   r   r!  rF  r"  r   r#  r$  r9  Znum_choicesZflat_input_idsZflat_token_type_idsZflat_attention_maskZflat_input_maskZflat_inputs_embedsrJ  r   r   Zreshaped_logitsr   rK  r8   r8   r9   r   w  s\    J


zXLNetForMultipleChoice.forward)NNNNNNNNNNNNNN)r   r   r   rZ   r   r   rI   r:  r;  r   r   r   r   r   r8   r8   rf   r9   rT  k  sB   
              
rT  z
    XLNet 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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j eej eej ee ee ee ee e	e
ef dddZ  ZS )XLNetForQuestionAnsweringSimplec                    s<   t  | |j| _t|| _t|j|j| _| 	  d S rh   )
rY   rZ   r   r   r   r   r   r   
qa_outputsr   rd   rf   r8   r9   rZ     s
    
z(XLNetForQuestionAnsweringSimple.__init__N)r  r  r   r  r   r  r   r   r!  r   end_positionsr"  r   r#  r$  r   c                 K   sd  |dur|n| j j}| j|f||||||||	||||d|}|d }| |}|jddd\}}|d }|d }d}|
dur|durt|
 dkr|
d}
t| dkr|d}|d}|
	d|}
|	d|}t
|d}|||
}|||}|| d }|sJ||f|dd  }|durF|f| S |S t||||j|j|jd	S )
r%  NrG  r   r   rl   r{   )Zignore_indexrV   )r   r   r   r   r   r   )r3   r0  r   rV  splitr   r*  rE   r   r  r   r   r   r   r   )re   r  r  r   r  r   r  r   r   r!  r   rW  r"  r   r#  r$  r9  r   rS  r   r   r   
total_lossZignored_indexrK  
start_lossend_lossr   r8   r8   r9   r   	  s`    6






z'XLNetForQuestionAnsweringSimple.forward)NNNNNNNNNNNNNNN)r   r   r   rZ   r   r   rI   r:  r;  r   r   r   r   r   r8   r8   rf   r9   rU    sF   
               
rU  c                       s   e Zd Z fddZe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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
ef dddZ  ZS )XLNetForQuestionAnsweringc                    sP   t  | |j| _|j| _t|| _t|| _t|| _	t
|| _|   d S rh   )rY   rZ   start_n_top	end_n_topr   r   r   r   r   r   r   answer_classr   rd   rf   r8   r9   rZ   z  s    



z"XLNetForQuestionAnswering.__init__N)r  r  r   r  r   r  r   r   r!  r   rW  is_impossibler   r   r"  r   r#  r$  r   c           -      K   s  |dur|n| j j}| j|f||||||||	||||d|}|d }| j||d}|dd }|
durP|durP|
|||fD ]"}|dur| dkr|d q| j||
|d}t }|||
}|||}|| d }|dur|dur| j||
|d	}t	
 }|||} || d
 7 }|s6|f|dd  S t||j|j|jdS nR| \}!}"}#t	jj|dd}$tj|$| jdd\}%}&|&ddd|#}'t|d|'}(|(dd|"dd}(|d|(})|dur|dnd}| j|)|(|d}t	jj|dd}*tj|*| jdd\}+},|+d| j| j }+|,d| j| j },td||$}(| j||(|d}|s|%|&|+|,|f}||dd  S t|%|&|+|,||j|j|jdS dS )a  
        mems (`list[torch.FloatTensor]` of length `config.n_layers`):
            Contains pre-computed hidden-states (see `mems` output below) . Can be used to speed up sequential
            decoding. The token ids which have their past given to this model should not be passed as `input_ids` as
            they have already been computed.

            `use_mems` has to be set to `True` to make use of `mems`.
        perm_mask (`torch.FloatTensor` of shape `(batch_size, sequence_length, sequence_length)`, *optional*):
            Mask to indicate the attention pattern for each input token with values selected in `[0, 1]`:

            - if `perm_mask[k, i, j] = 0`, i attend to j in batch k;
            - if `perm_mask[k, i, j] = 1`, i does not attend to j in batch k.

            If not set, each token attends to all the others (full bidirectional attention). Only used during
            pretraining (to define factorization order) or for sequential decoding (generation).
        target_mapping (`torch.FloatTensor` of shape `(batch_size, num_predict, sequence_length)`, *optional*):
            Mask to indicate the output tokens to use. If `target_mapping[k, i, j] = 1`, the i-th predict in batch k is
            on the j-th token. Only used during pretraining for partial prediction or for sequential decoding
            (generation).
        input_mask (`torch.FloatTensor` of shape `batch_size, sequence_length`, *optional*):
            Mask to avoid performing attention on padding token indices. Negative of `attention_mask`, i.e. with 0 for
            real tokens and 1 for padding which is kept for compatibility with the original code base.

            Mask values selected in `[0, 1]`:

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

            You can only uses one of `input_mask` and `attention_mask`.
        is_impossible (`torch.LongTensor` of shape `(batch_size,)`, *optional*):
            Labels whether a question has an answer or no answer (SQuAD 2.0)
        cls_index (`torch.LongTensor` of shape `(batch_size,)`, *optional*):
            Labels for position (index) of the classification token to use as input for computing plausibility of the
            answer.
        p_mask (`torch.FloatTensor` of shape `(batch_size, sequence_length)`, *optional*):
            Optional mask of tokens which can't be in answers (e.g. [CLS], [PAD], ...). 1.0 means token should be
            masked. 0.0 mean token is not masked.
        use_mems (`bool`, *optional*):
            Whether to use memory states to speed up sequential decoding. If set to `True`, the model will use the hidden
            states from previous forward passes to compute attention, which can significantly improve performance for
            sequential decoding tasks.

        Example:

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

        >>> tokenizer = AutoTokenizer.from_pretrained("xlnet/xlnet-base-cased")
        >>> model = XLNetForQuestionAnswering.from_pretrained("xlnet/xlnet-base-cased")

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

        >>> loss = outputs.loss
        ```NrG  r   )r   r   rl   )r   r   rV   )r   r   rU   )r   r   r   r   r{   r   )r   r   z
blh,bl->bh)r   r   )r   r   r   r   r   r   r   r   )r3   r0  r   r   r|   Zsqueeze_r   r   r_  r   r   r   r   r   r   r   r   r   rI   Ztopkr]  r   r   r   Z	expand_asr^  rI  r}   )-re   r  r  r   r  r   r  r   r   r!  r   rW  r`  r   r   r"  r   r#  r$  r9  rJ  r   r   r   ru   r   rK  rZ  r[  rY  r   Zloss_fct_clsZcls_lossr  r   r   Zstart_log_probsr   r   Zstart_top_index_expr   Zhidden_states_expandedZend_log_probsr   r   r8   r8   r9   r     s    S



	


z!XLNetForQuestionAnswering.forward)NNNNNNNNNNNNNNNNNN)r   r   r   rZ   r   r   rI   r:  r;  r   r   r   r   r   r8   r8   rf   r9   r\  x  sR                     
r\  )	rT  r\  rU  rO  rQ  r<  r   r   rS   )N):r   r1  dataclassesr   typingr   r   r   rI   r   Ztorch.nnr   r   r	   Zactivationsr   r   Z
generationr   Zmodeling_utilsr   Zpytorch_utilsr   utilsr   r   r   Zconfiguration_xlnetr   Z
get_loggerr   r=   r:   rS   ModulerT   r   r   r   r   r   r   r   r   r   r   r   r   r   r   r   r<  rO  rQ  rT  rU  r\  __all__r8   r8   r8   r9   <module>   s   

SC  3'FBc%!    g m z J