o
    ZŽh¹ ã                   @   s–  d 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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!dDd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G d#d$„ d$eƒƒZ-eG d%d&„ d&eƒƒZ.eG d'd(„ d(eƒƒZ/eG d)d*„ d*eƒƒZ0eG d+d,„ d,eƒƒZ1eG d-d.„ d.eƒƒZ2eG d/d0„ d0eƒƒZ3eG d1d2„ d2e,ƒƒZ4ed3d4G d5d6„ d6e,eƒƒZ5ed7d4G d8d9„ d9e,ƒƒZ6eG d:d;„ d;e,ƒƒZ7eG d<d=„ d=e,ƒƒZ8ed>d4G d?d@„ d@e,ƒƒZ9eG dAdB„ dBe,ƒƒZ:g dC¢Z;dS )Ez
PyTorch XLNet model.
é    N)Ú	dataclass)ÚCallableÚListÚOptionalÚTupleÚUnion)Únn)ÚBCEWithLogitsLossÚCrossEntropyLossÚMSELossé   )ÚACT2FNÚget_activation)ÚGenerationMixin)ÚPreTrainedModel)Úapply_chunking_to_forward)ÚModelOutputÚauto_docstringÚloggingé   )ÚXLNetConfigc                 C   s*  i }t | dƒrUt | dƒr| jj|d< t | dƒr)d|v r)| jjj|d< | jjj|d< t | dƒrR|jdurRd	|j› d
|v rR| jj|d	|j› d
< | jj|d	|j› d< | j} | 	| j
j| jdœ¡ t| jƒD ]e\}}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¡ qe|jrùg }g }g }	g }
| jD ]}| |jj¡ | |jj¡ |	 |jj¡ |
 |jj¡ qÙn| 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© r:   úW/var/www/auris/lib/python3.10/site-packages/transformers/models/xlnet/modeling_xlnet.pyÚbuild_tf_xlnet_to_pytorch_map'   sx   

ÿ
þÿóÿ
üüÿr<   c                 C   sœ  z
ddl }ddl}W n ty   t d¡ ‚ w |j |¡}i }|D ]\}}t d|› d|› ¡ |j ||¡}	|	||< q"t	| ||ƒ}
|
 
¡ D ]÷\}}t d|› ¡ ||vr`t |› d¡ qG|| }	d|v r~d	|v std
|v std|v r~t d¡ | |	¡}	t|tƒrët|ƒ|	jd ksœJ dt|ƒ› d|	jd › dƒ‚t|ƒD ]I\}}|	|df }z|j|jks¾J d|j› d|j› dƒ‚W n ty× } z| j|j|jf7  _‚ d}~ww t d|› d|› ¡ t |¡|_q n=z|j|	jksÿJ d|j› d|	j› dƒ‚W n ty } z| j|j|	jf7  _‚ d}~ww t d|› ¡ t |	¡|_| |d¡ | |d d¡ | |d d¡ qGt dd | ¡ ¡› ¡ | S )z&Load tf checkpoints in a pytorch modelr   NzšLoading 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)r4   r5   Ztf_pathÚnpÚtfZ	init_varsr6   ÚnamerH   Úarrayr7   Zpointerr8   Zp_iZarr_iÚer:   r:   r;   Úload_tf_weights_in_xlnetz   sv   ÿû
 


ÿÿ€þöÿ€þrU   c                       sn   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rt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   ç      à?é   ©Zeps)ÚsuperÚ__init__Úd_modelZn_headÚ
ValueErrorZd_headÚscaler   Ú	ParameterrK   ÚFloatTensorr(   r)   r+   r'   r*   r0   r2   r1   r3   Ú	LayerNormÚlayer_norm_epsr&   ÚDropoutÚdropout©Úselfr5   ©Ú	__class__r:   r;   r[   ¾   s,   

ÿÿzXLNetRelativeAttention.__init__c                 C   ó   t ‚©N©ÚNotImplementedError)rf   Zheadsr:   r:   r;   Úprune_headsÚ   ó   z"XLNetRelativeAttention.prune_headséÿÿÿÿc              	   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   rX   r   N.©ÚdeviceÚdtype©rH   ZreshaperK   Úindex_selectÚarangerq   Úlong©ÚxÚklenZx_sizer:   r:   r;   Ú	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   rX   rp   rs   rw   r:   r:   r;   Úrel_shift_bnijê   s     $z%XLNetRelativeAttention.rel_shift_bnijNFc	                 C   s  t  d|| j |¡}	t  d|| j |¡}
| j|
|	jd d}
|du r%d}nt  d|| j | j¡}t  d||¡}|	|
 | | j }|dur_|j	t j
krU|dt  d	|¡  }n
|d
t  d	|¡  }tjj|dd}|  |¡}|durx|t  d	|¡ }t  d||¡}|r‰|t  d|¡fS |S )z.Core relative positional attention operations.zibnd,jbnd->bnijr   )ry   Nr   zibnd,snd->ibnszijbs,ibns->bnijéÜÿ  z
ijbn->bnijçêŒ 9Y>)F©Údimzbnij,jbnd->ibndz
bnij->ijbn)rK   Úeinsumr1   r0   r{   rH   r2   r3   r^   rr   Úfloat16r   Ú
functionalÚsoftmaxrd   )rf   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_vecr:   r:   r;   Úrel_attn_coreù   s(   
z$XLNetRelativeAttention.rel_attn_coreTc                 C   s4   t  d|| j¡}|  |¡}|r|| }|  |¡}|S )zPost-attention processing.zibnd,hnd->ibh)rK   r€   r'   rd   r&   )rf   Úhr   ZresidualZattn_outÚoutputr:   r:   r;   Úpost_attention-  s   

z%XLNetRelativeAttention.post_attentionc              
   C   s
  |d ur¡|d ur|  ¡ dkrtj||gdd}n|}t d|| j¡}t d|| j¡}t d|| j¡}t d|| j¡}| j|||||||	|
d}|
rM|\}}|  	||¡}t d|| j¡}|d urt d||¡}| j|||||||	|
d}|
ry|\}}t d||¡}n| j|||||||	|
d}|
r”|\}}|  	||¡}|
r ||f}nV|d urµ|  ¡ dkrµt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   rK   Úcatr€   r)   r+   r*   r(   rŽ   r‘   Útyperr   )rf   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   Úoutputsr:   r:   r;   Úforward9  sœ   øøø€ø
zXLNetRelativeAttention.forward©ro   ©NNNF)T)Ú__name__Ú
__module__Ú__qualname__r[   rm   Ústaticmethodrz   r{   rŽ   r‘   rœ   Ú__classcell__r:   r:   rg   r;   rV   ½   s$    
÷
4õrV   c                       s$   e Zd Z‡ fdd„Zdd„ Z‡  ZS )ÚXLNetFeedForwardc                    sx   t ƒ  ¡  tj|j|jd| _t |j|j¡| _	t |j|j¡| _
t |j¡| _t|jtƒr6t|j | _d S |j| _d S )NrY   )rZ   r[   r   ra   r\   rb   r&   ÚLinearZd_innerr-   r.   rc   rd   rE   Zff_activationÚstrr   Úactivation_functionre   rg   r:   r;   r[   Â  s   
zXLNetFeedForward.__init__c                 C   sH   |}|   |¡}|  |¡}|  |¡}|  |¡}|  |¡}|  || ¡}|S rj   )r-   r§   rd   r.   r&   )rf   Úinpr   r:   r:   r;   rœ   Í  s   




zXLNetFeedForward.forward)rŸ   r    r¡   r[   rœ   r£   r:   r:   rg   r;   r¤   Á  s    r¤   c                       s6   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   )rZ   r[   rV   r%   r¤   r,   r   rc   rd   Úchunk_size_feed_forwardÚseq_len_dimre   rg   r:   r;   r[   Ù  s   



zXLNetLayer.__init__NFc                 C   sv   | j |||||||||	|
d
}|d d… \}}|d ur%t| j| j| j|ƒ}t| j| j| j|ƒ}||f|dd …  }|S )N)r—   r˜   r‰   rŠ   rX   )r%   r   Úff_chunkr«   r¬   )rf   r™   rš   r•   r–   r*   r‡   r—   r˜   r‰   rŠ   r›   r:   r:   r;   rœ   á  s(   öÿzXLNetLayer.forwardc                 C   s   |   |¡}|S rj   )r,   )rf   Zoutput_xr:   r:   r;   r­     s   
zXLNetLayer.ff_chunkrž   )rŸ   r    r¡   r[   rœ   r­   r£   r:   r:   rg   r;   r©   Ø  s    
õ$r©   c                       sJ   e Zd ZdZdef‡ fdd„Z	ddejdeej dejfd	d
„Z	‡  Z
S )Ú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.
    r5   c                    s   t ƒ  ¡  t |jd¡| _d S rª   )rZ   r[   r   r¥   Úhidden_sizeÚdensere   rg   r:   r;   r[     s   
zXLNetPoolerStartLogits.__init__NÚhidden_statesÚp_maskÚreturnc                 C   sT   |   |¡ d¡}|dur(|jtjkr|d|  d|  }|S |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.
        ro   Nr   r|   r}   )r°   Úsqueezerr   rK   r   )rf   r±   r²   rx   r:   r:   r;   rœ     s   þzXLNetPoolerStartLogits.forwardrj   )rŸ   r    r¡   Ú__doc__r   r[   rK   r`   r   rœ   r£   r:   r:   rg   r;   r®     s    ÿÿÿþr®   c                       sb   e Zd ZdZdef‡ fdd„Z			ddejdeej deej	 d	eej d
ejf
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.
    r5   c                    sR   t ƒ  ¡  t |jd |j¡| _t ¡ | _tj|j|j	d| _t |jd¡| _
d S )NrX   rY   r   )rZ   r[   r   r¥   r¯   Údense_0ÚTanhÚ
activationra   rb   Údense_1re   rg   r:   r;   r[   <  s
   

zXLNetPoolerEndLogits.__init__Nr±   Ústart_statesÚstart_positionsr²   r³   c                 C   sè   |dus|dusJ dƒ‚|dur4|j dd… \}}|dd…ddf  dd|¡}| d|¡}| d|d¡}|  tj||gdd¡}|  |¡}|  |¡}|  |¡ 	d¡}|durr|j
tjkrh|d|  d|  }|S |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.
        Nú7One of start_states, start_positions should be not Noneéþÿÿÿro   r~   r   r|   r}   )rH   ÚexpandÚgatherr·   rK   r’   r¹   ra   rº   r´   rr   r   )rf   r±   r»   r¼   r²   ÚslenÚhszrx   r:   r:   r;   rœ   C  s$   ÿ

þzXLNetPoolerEndLogits.forward©NNN©rŸ   r    r¡   rµ   r   r[   rK   r`   r   Ú
LongTensorrœ   r£   r:   r:   rg   r;   r¶   2  s"    	
ûþýüûúr¶   c                       sb   e Zd ZdZdef‡ fdd„Z			ddejdeej deej	 d	eej	 d
ejf
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.
    r5   c                    sB   t ƒ  ¡  t |jd |j¡| _t ¡ | _tj|jddd| _d S )NrX   r   F©r   )	rZ   r[   r   r¥   r¯   r·   r¸   r¹   rº   re   rg   r:   r;   r[     s   

zXLNetPoolerAnswerClass.__init__Nr±   r»   r¼   Ú	cls_indexr³   c                 C   sÜ   |j d }|dus|dusJ dƒ‚|dur,|dd…ddf  dd|¡}| d|¡ d¡}|durH|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.
        ro   Nr½   r¾   r~   )	rH   r¿   rÀ   r´   r·   rK   r’   r¹   rº   )rf   r±   r»   r¼   rÈ   rÂ   Zcls_token_staterx   r:   r:   r;   rœ   ‡  s   
ÿ
zXLNetPoolerAnswerClass.forwardrÃ   rÄ   r:   r:   rg   r;   rÆ   x  s"    	ûþýüûúrÆ   c                       sJ   e Zd ZdZdef‡ fdd„Z	ddejdeej	 dejfd	d
„Z
‡  ZS )Ú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.
    r5   c                    sþ   t ƒ  ¡  t|ddƒ| _| jdkrt‚t ¡ | _t|dƒr<|j	r<t|dƒr1|j
r1|jdkr1|j}n|j}t |j|¡| _t|dd ƒ}|rHt|ƒnt ¡ | _t ¡ | _t|dƒrc|jdkrct |j¡| _t ¡ | _t|d	ƒr{|jdkr}t |j¡| _d S d S d S )
NÚsummary_typeÚlastÚattnÚsummary_use_projÚsummary_proj_to_labelsr   Zsummary_activationÚsummary_first_dropoutÚsummary_last_dropout)rZ   r[   ÚgetattrrÊ   rl   r   ZIdentityr   r   rÍ   rÎ   Ú
num_labelsr¯   r¥   r   r¹   Úfirst_dropoutrÏ   rc   Úlast_dropoutrÐ   )rf   r5   Únum_classesZactivation_stringrg   r:   r;   r[   Ô  s&   




ÿzXLNetSequenceSummary.__init__Nr±   rÈ   r³   c                 C   s  | j dkr|dd…df }ne| j dkr|dd…df }nW| j dkr(|jdd}nK| j d	krl|du rItj|d
dd…dd…f |jd d tjd}n| d¡ d¡}| d| ¡ d  | 	d¡f ¡}| 
d|¡ d¡}n| j dkrst‚|  |¡}|  |¡}|  |¡}|  |¡}|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Ë   Nro   Úfirstr   Úmeanr   r~   rÈ   .r¾   ©rr   r   rÌ   )rÊ   r×   rK   Z	full_likerH   rv   Ú	unsqueezer¿   r   ÚsizerÀ   r´   rl   rÓ   r   r¹   rÔ   )rf   r±   rÈ   r   r:   r:   r;   rœ   ñ  s.   



ý"




zXLNetSequenceSummary.forwardrj   rÄ   r:   r:   rg   r;   rÉ   º  s    ÿÿÿþrÉ   c                   @   s    e Zd ZeZeZdZdd„ ZdS )ÚXLNetPreTrainedModelr   c              	   C   s(  t |tjƒr |jjjd| jjd |jdur|jj 	¡  dS dS t |tj
ƒrC|jjjd| jjd |jdurA|jj|j  	¡  dS dS t |tjƒrX|jj 	¡  |jj d¡ dS t |tƒr€|j|j|j|j|j|j|j|j|jf	D ]}|jjd| jjd qqdS t |tƒr’|jjjd| jjd dS dS )zInitialize the weights.g        )r×   ZstdNç      ð?)rE   r   r¥   r   rL   Znormal_r5   Zinitializer_ranger   Zzero_Ú	EmbeddingZpadding_idxra   Zfill_rV   r(   r)   r+   r'   r*   r0   r2   r1   r3   Ú
XLNetModelr"   )rf   ÚmoduleÚparamr:   r:   r;   Ú_init_weights#  s:   
ÿ
ÿ
÷õ
ÿz"XLNetPreTrainedModel._init_weightsN)	rŸ   r    r¡   r   Zconfig_classrU   Zload_tf_weightsZbase_model_prefixrá   r:   r:   r:   r;   rÛ     s
    rÛ   c                   @   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@  
    Output type of [`XLNetModel`].

    Args:
        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.
        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.
    Úlast_hidden_stateNr—   .r±   Ú
attentions)rŸ   r    r¡   rµ   rK   r`   Ú__annotations__r—   r   r   r±   r   rä   r:   r:   r:   r;   râ   C  s   
 
râ   c                   @   ó€   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 )	ÚXLNetLMHeadModelOutputa  
    Output type of [`XLNetLMHeadModel`].

    Args:
        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.
        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Úlogitsr—   .r±   rä   ©rŸ   r    r¡   rµ   rè   r   rK   r`   rå   ré   r—   r   r±   r   rä   r:   r:   r:   r;   rç   e  s   
 rç   c                   @   ræ   )	Ú$XLNetForSequenceClassificationOutputa_  
    Output type of [`XLNetForSequenceClassification`].

    Args:
        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.
        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.
    Nrè   ré   r—   .r±   rä   rê   r:   r:   r:   r;   rë   Š  ó   
 rë   c                   @   ræ   )	Ú!XLNetForTokenClassificationOutputa%  
    Output type of [`XLNetForTokenClassificationOutput`].

    Args:
        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.
        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.
    Nrè   ré   r—   .r±   rä   rê   r:   r:   r:   r;   rí   ¬  rì   rí   c                   @   ræ   )	ÚXLNetForMultipleChoiceOutputad  
    Output type of [`XLNetForMultipleChoice`].

    Args:
        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.
        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.
    Nrè   ré   r—   .r±   rä   rê   r:   r:   r:   r;   rî   Î  s   
 rî   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Ù  
    Output type of [`XLNetForQuestionAnsweringSimple`].

    Args:
        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.
        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.
    Nrè   Ústart_logitsÚ
end_logitsr—   .r±   rä   )rŸ   r    r¡   rµ   rè   r   rK   r`   rå   rð   rñ   r—   r   r±   r   rä   r:   r:   r:   r;   rï   ò  s   
 rï   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 )ÚXLNetForQuestionAnsweringOutputam  
    Output type of [`XLNetForQuestionAnswering`].

    Args:
        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.
        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.
    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   rK   r`   rå   ró   rô   rÅ   rõ   rö   r÷   r—   r   r±   r   rä   r:   r:   r:   r;   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#deej deej deej deej deej deej deej deej deej dee dee dee dee deeef f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 r:   )r©   )Ú.0Ú_©r5   r:   r;   Ú
<listcomp>W  s    z'XLNetModel.__init__.<locals>.<listcomp>)rZ   r[   Úmem_lenÚ	reuse_lenr\   Úsame_lengthÚ	attn_typeÚbi_dataÚ	clamp_lenÚn_layerr   rÝ   Ú
vocab_sizer!   r_   rK   r`   r"   Z
ModuleListÚranger$   rc   rd   Ú	post_initre   rg   rú   r;   r[   I  s    zXLNetModel.__init__c                 C   ó   | j S rj   ©r!   ©rf   r:   r:   r;   Úget_input_embeddings]  ó   zXLNetModel.get_input_embeddingsc                 C   ó
   || _ d S rj   r  ©rf   Znew_embeddingsr:   r:   r;   Úset_input_embeddings`  ó   
zXLNetModel.set_input_embeddingsc                 C   ri   rj   rk   )rf   Zheads_to_pruner:   r:   r;   Ú_prune_headsc  rn   zXLNetModel._prune_headsc                 C   sx   t j||| f| jd}| jr3|dd…d|…f  d¡}| |d ¡ |dd…d|…f  |7  < |S | |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]

        )rq   Nro   r   )rK   Zonesrq   rþ   ZtrilZtriu_)rf   ÚqlenÚmlenÚmaskZmask_lor:   r:   r;   Úcreate_maskf  s   þzXLNetModel.create_maskc                 C   s‚   | j d ur| j dkr|d | j … }| jd u s| jdkrd}n| j }|d u r0||d … }| ¡ S tj||gdd|d … }| ¡ S )Nr   r~   )rý   rü   rK   r’   Údetach)rf   Zcurr_outZprev_memÚcutoffZnew_memr:   r:   r;   Ú	cache_mem‚  s   þzXLNetModel.cache_memNc                 C   s\   t  d| |¡}t jt  |¡t  |¡gdd}|d d …d d d …f }|d ur,| d|d¡}|S )Nzi,d->idro   r~   )rK   r€   r’   ÚsinÚcosr¿   )Zpos_seqÚinv_freqÚbszZsinusoid_inpÚpos_embr:   r:   r;   Úpositional_embedding—  s   zXLNetModel.positional_embeddingc                 C   sz  t jd| jdt jd ¡ }dt  d|| j ¡ }| jdkr$|| }}n| jdkr/|d}}n	td	| j› d
ƒ‚| jršt j||dt jd ¡ }t j| | dt jd ¡ }	| j	dkrl| 
| j	 | j	¡}|	 
| j	 | j	¡}	|d urƒ|  |||d ¡}
|  |	||d ¡}n|  ||¡}
|  |	|¡}t j|
|gdd}|S t j||dt jd ¡ }| j	dkr´| 
| j	 | j	¡}|  |||¡}|S )Nr   g       @rØ   r   i'  ÚbiÚuniro   zUnknown `attn_type` Ú.g      ð¿rÜ   rX   r~   )rK   ru   r\   Zint64ÚfloatÚpowrÿ   r]   r   r  Úclampr  r’   )rf   r  ry   r  Zfreq_seqr  ÚbegÚendZfwd_pos_seqZbwd_pos_seqZfwd_pos_embZbwd_pos_embr  r:   r:   r;   Úrelative_positional_encoding¢  s2   


û
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r|n| j j}d|v r,t dt¡ |d }
| jr:|
dur5|
n| j j}
n
|
dur@|
n| j j	}
|durP|	durPt
dƒ‚|durh| 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rž| dd¡ ¡ nd}|dur¬| 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 s!|du s!J dƒ‚	 |du r0|dur0d| }|durA|durA|d | }n|durP|du rP|d }n|du r]|dur]|}nd}|dur¤|dkr€t |jd ||g¡ |¡}tj||gdd}|du r”|dd…dd…dd…df }n||dd…dd…dd…df 7 }|dur°|dk |¡}|durèt |¡ |¡ }|dkrÔtjt ||g¡ |¡|gdd}||dd…dd…ddf  dk |¡}nd}|	durò|	}n|  |¡}|  |¡}|dur| j |jd |d¡}|  |¡}nd}|durS|dkr3t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r«| !¡ dkr| "d¡ "d¡ "d¡ "d¡}| | j#dddd¡}n| !¡ dkrŸ| "d¡ "d¡ "d¡}|jt$|  %¡ ƒjd}ndg| j# }d}!|du rÀdgt&| j'ƒ }|rÅg nd}"|rÌg nd}#t(| j'ƒD ]H\}$}%|
rå|!|  )|||$ ¡f }!|rö|# *|duró||fn|¡ |%||||| |||$ |||$ |d
}&|&dd… \}}|r|" *|&d ¡ qÓ|r-|# *|dur*||fn|¡ |  |dur6|n|¡}'|' ddd¡ ¡ }'|
sGd}!|rb|durYt+dd„ |#D ƒƒ}#n	t+dd„ |#D ƒƒ}#|r}|durtt+dd„ |"D ƒƒ}"n	t+dd„ |"D ƒƒ}"|st+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_embedsrX   r  r  zUnsupported attention type: z8You can only use one of input_mask (uses 1 for padding) rÜ   r~   ro   ©rr   rq   )rÕ   )r  rØ   r:   )r•   r–   r*   r‡   r—   r˜   r‰   rŠ   c                 s   s,    | ]}|D ]}|  d dd¡ ¡ V  qqdS ©r   r   rX   N©ÚpermuteÚ
contiguous)rø   Úhsr   r:   r:   r;   Ú	<genexpr>µ  ó   €* z%XLNetModel.forward.<locals>.<genexpr>c                 s   s"    | ]}|  d dd¡ ¡ V  qdS r1  r2  )rø   r5  r:   r:   r;   r6  ·  s   €  c                 s   s"    | ]}t d d„ |D ƒƒV  qdS )c                 s   ó$    | ]}|  d ddd¡ ¡ V  qdS ©rX   r   r   r   Nr2  )rø   Z
att_streamr:   r:   r;   r6  ½  ó   €" z/XLNetModel.forward.<locals>.<genexpr>.<genexpr>N)Útuple©rø   Útr:   r:   r;   r6  ¼  s   € 
ÿc                 s   r8  r9  r2  r<  r:   r:   r;   r6  À  r:  c                 s   s    | ]	}|d ur|V  qd S rj   r:   )rø   r+   r:   r:   r;   r6  Ã  s   € )rã   r—   r±   rä   )-r5   rŠ   r-  Úuse_return_dictÚwarningsÚwarnÚFutureWarningZtrainingZuse_mems_trainZuse_mems_evalr]   rD   r4  rH   r3  rr   rq   rÿ   r  rK   ÚzerosÚtor’   Úeyer!   rd   r"   r¿   rv   r   r‚   Zone_hotr%  r   rÙ   r  ÚnextÚ
parametersrG   r$   r#   r  r/   r;  râ   )(rf   r&  r'  r—   r(  r˜   r)  r*  r‰   r+  r,  rŠ   r-  r.  Úkwargsr  r  r  ry   Zdtype_floatrq   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±   r8   Zlayer_moduler›   r   r:   r:   r;   rœ   È  s  4ÿý&



 


"(





$

ÿ
ö€


ÿÿzXLNetModel.forwardrj   )NNNNNNNNNNNNN)rŸ   r    r¡   r[   r	  r  r  r  r  r¢   r  r%  r   r   rK   ÚTensorÚboolr   r   râ   rœ   r£   r:   r:   rg   r;   rÞ   G  sj    

&òþýüûúùø	÷
öõôóò
ðrÞ   zt
    XLNet Model with a language modeling head on top (linear layer with weights tied to the input embeddings).
    )Zcustom_introc                "       s   e Zd ZdgZ‡ fdd„Zdd„ Zdd„ Zdd	d
„Ze														d de	e
j de	e
j de	e
j de	e
j de	e
j de	e
j de	e
j de	e
j de	e
j de	e
j de	e de	e de	e de	e deeef fdd„ƒZedee
j de
jdee
j fdd„ƒZ‡  ZS )!ÚXLNetLMHeadModelzlm_loss.weightc                    sH   t ƒ  |¡ |j| _|j| _t|ƒ| _tj|j|j	dd| _
|  ¡  d S )NTrÇ   )rZ   r[   rÿ   rþ   rÞ   r   r   r¥   r\   r  r   r  re   rg   r:   r;   r[   Ò  s   
zXLNetLMHeadModel.__init__c                 C   r  rj   ©r   r  r:   r:   r;   Úget_output_embeddingsÝ  r
  z&XLNetLMHeadModel.get_output_embeddingsc                 C   r  rj   rK  r  r:   r:   r;   Úset_output_embeddingsà  r  z&XLNetLMHeadModel.set_output_embeddingsNc                    sø   |j d }tj|dftj|jd}d‰ |r(t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œ}
|rzt‡ fd	d
„|D ƒƒ|
d< |
S )Nr   r   r0  rX   r~   rÜ   ro   )r&  r(  r˜   r,  c                 3   s,    | ]}|d ˆ  …d d …d d …f V  qd S rj   r:   ©rø   Z
layer_past©Úoffsetr:   r;   r6    r7  zAXLNetLMHeadModel.prepare_inputs_for_generation.<locals>.<genexpr>r—   )rH   rK   rB  rv   rq   r’   r   r;  )rf   r&  Zpast_key_valuesr,  rG  Zeffective_batch_sizeZdummy_tokenZsequence_lengthr(  r˜   Zinputsr:   rO  r;   Úprepare_inputs_for_generationã  s.   
&
ÿÿüz.XLNetLMHeadModel.prepare_inputs_for_generationr&  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¡ƒ}|sU|f|dd…  }|durS|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   ro   r   ©rè   ré   r—   r±   rä   )r5   r>  r   r   r
   ÚviewrÚ   rç   r—   r±   rä   )rf   r&  r'  r—   r(  r˜   r)  r*  r‰   r+  rR  r,  rŠ   r-  r.  rG  Útransformer_outputsré   rè   Úloss_fctr   r:   r:   r;   rœ     sD   uÿóòûzXLNetLMHeadModel.forwardÚbeam_idxc                    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   )rt   rC  rq   rN  ©rX  r:   r;   rû   ²  s     z3XLNetLMHeadModel._reorder_cache.<locals>.<listcomp>r:   )r—   rX  r:   rY  r;   Ú_reorder_cache«  s   zXLNetLMHeadModel._reorder_cache)NN©NNNNNNNNNNNNNN)rŸ   r    r¡   Z_tied_weights_keysr[   rL  rM  rQ  r   r   rK   rH  rI  r   r   rç   rœ   r¢   r   rZ  r£   r:   r:   rg   r;   rJ  Ê  sn    
,ñþýüûúùø	÷
öõôóòñ
ï .rJ  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                "       óØ   e Zd Z‡ fdd„Ze														ddeej deej deej deej deej d	eej d
eej deej deej deej dee dee dee dee de	e
ef fdd„ƒZ‡  ZS )ÚXLNetForSequenceClassificationc                    sL   t ƒ  |¡ |j| _|| _t|ƒ| _t|ƒ| _t 	|j
|j¡| _|  ¡  d S rj   )rZ   r[   rÒ   r5   rÞ   r   rÉ   r   r   r¥   r\   r   r  re   rg   r:   r;   r[   ¼  s   

z'XLNetForSequenceClassification.__init__Nr&  r'  r—   r(  r˜   r)  r*  r‰   r+  rR  r,  rŠ   r-  r.  r³   c                 K   s†  |dur|n| j j}| j|f||||||||	||||dœ|¤Ž}|d }|  |¡}|  |¡}d}|
dur¡| j jdu r^| jdkrDd| j _n| jdkrZ|
jtj	ksU|
jtj
krZd| j _nd| j _| j jdkr|tƒ }| jdkrv|| ¡ |
 ¡ ƒ}n+|||
ƒ}n%| j jdkr“tƒ }|| d| j¡|
 d¡ƒ}n| j jdkr¡tƒ }|||
ƒ}|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 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.
        NrS  r   r   Z
regressionZsingle_label_classificationZmulti_label_classificationro   rT  )r5   r>  r   r   r   Zproblem_typerÒ   rr   rK   rv   Úintr   r´   r
   rU  r	   rë   r—   r±   rä   )rf   r&  r'  r—   r(  r˜   r)  r*  r‰   r+  rR  r,  rŠ   r-  r.  rG  rV  r   ré   rè   rW  r:   r:   r;   rœ   È  sf   9ÿóò



"


ûz&XLNetForSequenceClassification.forwardr[  )rŸ   r    r¡   r[   r   r   rK   rH  rI  r   r   rë   rœ   r£   r:   r:   rg   r;   r]  µ  s`    ñþýüûúùø	÷
öõôóòñ
ïr]  c                "       r\  )ÚXLNetForTokenClassificationc                    ó<   t ƒ  |¡ |j| _t|ƒ| _t |j|j¡| _|  	¡  d S rj   )
rZ   r[   rÒ   rÞ   r   r   r¥   r¯   Ú
classifierr  re   rg   r:   r;   r[   >  ó
   
z$XLNetForTokenClassification.__init__Nr&  r'  r—   r(  r˜   r)  r*  r‰   r+  rR  r,  rŠ   r-  r.  r³   c                 K   sº   |dur|n| j j}| j|||||||||	||||d}|d }|  |¡}d}|
dur;tƒ }|| d| j¡|
 d¡ƒ}|sQ|f|dd…  }|durO|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.
        NrS  r   ro   r   rT  )r5   r>  r   ra  r
   rU  rÒ   rí   r—   r±   rä   )rf   r&  r'  r—   r(  r˜   r)  r*  r‰   r+  rR  r,  rŠ   r-  r.  rG  r›   Úsequence_outputré   rè   rW  r   r:   r:   r;   rœ   H  s@   :ó
ûz#XLNetForTokenClassification.forwardr[  )rŸ   r    r¡   r[   r   r   rK   rH  rI  r   r   rí   rœ   r£   r:   r:   rg   r;   r_  <  ó`    
ñþýüûúùø	÷
öõôóòñ
ïr_  c                "       r\  )ÚXLNetForMultipleChoicec                    s<   t ƒ  |¡ t|ƒ| _t|ƒ| _t |jd¡| _	|  
¡  d S rª   )rZ   r[   rÞ   r   rÉ   r   r   r¥   r\   r   r  re   rg   r:   r;   r[   ¬  s
   

zXLNetForMultipleChoice.__init__Nr&  r)  r*  r'  r—   r(  r˜   r‰   r+  rR  r,  rŠ   r-  r.  r³   c                 K   sˆ  |dur|n| j j}|dur|jd n|	jd }|dur%| d| d¡¡nd}|dur4| d| d¡¡nd}|durC| d| d¡¡nd}|durR| d| d¡¡nd}|	dure|	 d|	 d¡|	 d¡¡nd}| j|f||||||||||||dœ|¤Ž}|d }|  |¡}|  |¡}| d|¡}d}|
dur¢tƒ }|||
 d¡ƒ}|s¸|f|dd…  }|dur¶|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   ro   r¾   )r)  r*  r'  r—   r(  r˜   r‰   r+  r,  rŠ   r-  r.  r   rT  )r5   r>  rH   rU  rÚ   r   r   r   r
   rî   r—   r±   rä   )rf   r&  r)  r*  r'  r—   r(  r˜   r‰   r+  rR  r,  rŠ   r-  r.  rG  Znum_choicesZflat_input_idsZflat_token_type_idsZflat_attention_maskZflat_input_maskZflat_inputs_embedsrV  r   ré   Zreshaped_logitsrè   rW  r:   r:   r;   rœ   ¶  s\   Jÿýÿóò

ûzXLNetForMultipleChoice.forwardr[  )rŸ   r    r¡   r[   r   r   rK   rH  rI  r   r   rî   rœ   r£   r:   r:   rg   r;   re  ª  rd  re  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deej deej deej deej deej d	eej d
eej deej deej deej deej dee dee dee dee de	e
ef f dd„ƒZ‡  ZS )ÚXLNetForQuestionAnsweringSimplec                    r`  rj   )
rZ   r[   rÒ   rÞ   r   r   r¥   r¯   Ú
qa_outputsr  re   rg   r:   r;   r[   >  rb  z(XLNetForQuestionAnsweringSimple.__init__Nr&  r'  r—   r(  r˜   r)  r*  r‰   r+  r¼   Úend_positionsr,  rŠ   r-  r.  r³   c                 K   s\  |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rW|
 d¡}
t| ¡ ƒdkrd| d¡}| d¡}|
 	d|¡}
| 	d|¡}t
|d}|||
ƒ}|||ƒ}|| d }|s¡||f|dd…  }|durŸ|f| S |S t||||j|j|jd	S )
r/  NrS  r   r   ro   r~   )Zignore_indexrX   )rè   rð   rñ   r—   r±   rä   )r5   r>  r   rg  Úsplitr´   r4  rG   rÚ   r"  r
   rï   r—   r±   rä   )rf   r&  r'  r—   r(  r˜   r)  r*  r‰   r+  r¼   rh  r,  rŠ   r-  r.  rG  r›   rc  ré   rð   rñ   Ú
total_lossZignored_indexrW  Ú
start_lossÚend_lossr   r:   r:   r;   rœ   H  s`   6ÿóò






úz'XLNetForQuestionAnsweringSimple.forward)NNNNNNNNNNNNNNN)rŸ   r    r¡   r[   r   r   rK   rH  rI  r   r   rï   rœ   r£   r:   r:   rg   r;   rf  7  sf    
ðþýüûúùø	÷
öõôóòñð
îrf  c                *       s  e Zd Z‡ fdd„Ze																		ddeej deej deej deej deej d	eej d
eej deej deej deej deej deej deej deej dee dee dee dee de	e
ef f&dd„ƒZ‡  ZS )ÚXLNetForQuestionAnsweringc                    sP   t ƒ  |¡ |j| _|j| _t|ƒ| _t|ƒ| _t|ƒ| _	t
|ƒ| _|  ¡  d S rj   )rZ   r[   Ústart_n_topÚ	end_n_toprÞ   r   r®   rð   r¶   rñ   rÆ   Úanswer_classr  re   rg   r:   r;   r[   ¹  s   



z"XLNetForQuestionAnswering.__init__Nr&  r'  r—   r(  r˜   r)  r*  r‰   r+  r¼   rh  Ú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r¡|dur¡|
|||fD ]}|durP| ¡ dkrP| d¡ q?| j||
|d}tƒ }|||
ƒ}|||ƒ}|| d }|dur‹|dur‹| j||
|d	}t	 
¡ }|||ƒ} || d
 7 }|s–|f|dd…  S t||j|j|jdS | ¡ \}!}"}#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 )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
        ```NrS  r   )r²   r   ro   )r¼   r²   rX   )r¼   rÈ   rW   )rè   r—   r±   rä   r~   r¾   )r»   r²   z
blh,bl->bh)r»   rÈ   )ró   rô   rõ   rö   r÷   r—   r±   rä   )r5   r>  r   rð   r   Zsqueeze_rñ   r
   rp  r   r	   rò   r—   r±   rä   rÚ   r‚   rƒ   rK   Ztopkrn  rÙ   r¿   rÀ   Z	expand_asro  rU  r€   )-rf   r&  r'  r—   r(  r˜   r)  r*  r‰   r+  r¼   rh  rq  rÈ   r²   r,  rŠ   r-  r.  rG  rV  r±   rð   r›   rx   rñ   rW  rk  rl  rj  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ö   r:   r:   r;   rœ   Æ  s¦   Sÿóò
€


ü	
ÿ
ÿ
ÿÿÿøz!XLNetForQuestionAnswering.forward)NNNNNNNNNNNNNNNNNN)rŸ   r    r¡   r[   r   r   rK   rH  rI  r   r   rò   rœ   r£   r:   r:   rg   r;   rm  ·  sx    íþýüûúùø	÷
öõôóòñðïîí
ërm  )	re  rm  rf  r]  r_  rJ  rÞ   rÛ   rU   rj   )<rµ   r?  Údataclassesr   Útypingr   r   r   r   r   rK   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<   rU   ÚModulerV   r¤   r©   r®   r¶   rÆ   rÉ   rÛ   râ   rç   rë   rí   rî   rï   rò   rÞ   rJ  r]  r_  re  rf  rm  Ú__all__r:   r:   r:   r;   Ú<module>   sŠ   

SC  3'FBc%!$!!#$/   ÿ gÿ m ÿz J