
    sg#/                   @   d Z ddlmZ ddlZddlmZ ddlmZmZm	Z	m
Z
 ddlZddlZddlmZ ddlmZmZmZmZmZmZmZmZmZmZmZmZmZ dd	lm Z m!Z!m"Z" dd
l#m$Z$m%Z%m&Z&m'Z'm(Z(m)Z) ddl*m+Z+  e(jX                  e-      Z.dZ/dZ0 G d dejb                  jd                        Z3 G d dejb                  jd                        Z4 G d dejb                  jd                        Z5 G d dejb                  jd                        Z6e G d dejb                  jd                               Z7 G d de      Z8e G d de$             Z9e G d de$             Z:e G d d e$             Z;e G d! d"e$             Z<e G d# d$e$             Z=e G d% d&e$             Z>d'Z?d(Z@ e&d)e?       G d* d+e8             ZA e&d,e?       G d- d.e8e             ZB e&d/e?       G d0 d1e8e             ZC e&d2e?       G d3 d4e8e             ZD e&d5e?       G d6 d7e8e             ZE e&d8e?       G d9 d:e8e             ZFy);z
TF 2.0 XLNet model.
    )annotationsN)	dataclass)ListOptionalTupleUnion   )get_tf_activation)TFCausalLanguageModelingLossTFModelInputTypeTFMultipleChoiceLossTFPreTrainedModelTFQuestionAnsweringLossTFSequenceClassificationLossTFSequenceSummaryTFSharedEmbeddingsTFTokenClassificationLossget_initializerkeraskeras_serializableunpack_inputs)check_embeddings_within_bounds
shape_liststable_softmax)ModelOutputadd_code_sample_docstringsadd_start_docstrings%add_start_docstrings_to_model_forwardloggingreplace_return_docstrings   )XLNetConfigzxlnet/xlnet-base-casedr"   c                  l     e Zd Z fdZddZd Zd	dZ	 d
dZddZ	 	 	 	 	 d	 	 	 	 	 	 	 	 	 ddZ	 xZ
S )TFXLNetRelativeAttentionc                H   t        |   di | |j                  |j                  z  dk7  r%t	        d|j                   d|j                         |j                  | _        |j
                  | _        |j                  | _        d|j
                  dz  z  | _        |j                  | _        |j                  | _        t        j                  j                  |j                  d      | _        t        j                  j                  |j                        | _        || _        y )	Nr   zThe hidden size (z6) is not a multiple of the number of attention heads (r!   g      ?
layer_normepsilonname )super__init__d_modeln_head
ValueErrord_headscaleinitializer_rangeoutput_attentionsr   layersLayerNormalizationlayer_norm_epsr&   Dropoutdropoutconfigselfr9   kwargs	__class__s      ^/var/www/html/venv/lib/python3.12/site-packages/transformers/models/xlnet/modeling_tf_xlnet.pyr,   z!TFXLNetRelativeAttention.__init__@   s    "6">>FMM)Q.#FNN#3 4 --* 
 mmmm~~&--,-
!'!9!9!'!9!9,,99&BWBW^j9k||++FNN;    c                "   t        | j                        }| j                  | j                  | j                  | j
                  f|dd      | _        | j                  | j                  | j                  | j
                  f|dd      | _        | j                  | j                  | j                  | j
                  f|dd      | _        | j                  | j                  | j                  | j
                  f|dd      | _	        | j                  | j                  | j                  | j
                  f|dd      | _
        | j                  | j                  | j
                  fddd	      | _        | j                  | j                  | j
                  fddd
      | _        | j                  | j                  | j
                  fddd      | _        | j                  d| j                  | j
                  f|dd      | _        | j                  ry d| _        t!        | dd       et#        j$                  | j&                  j(                        5  | j&                  j+                  d d | j,                  j                  g       d d d        y y # 1 sw Y   y xY w)NTqshapeinitializer	trainabler)   kvorzerosr_r_biasr_s_biasr_w_bias   	seg_embedr&   )r   r2   
add_weightr-   r.   r0   rA   rF   rG   rH   rI   rK   rL   rM   rO   builtgetattrtf
name_scoper&   r)   buildr9   )r;   input_shaperD   s      r>   rU   zTFXLNetRelativeAttention.buildT   sS   %d&<&<=<<dkk:_cjm ! 
 <<dkk:_cjm ! 
 <<dkk:_cjm ! 
 <<dkk:_cjm ! 
 <<dkk:_cjm ! 
 ;;,'TXb ( 
 ;;,'TXb ( 
 ;;,'TXb ( 
 dkk4;;/[TX_j ) 
 ::
4t,8t334 I%%tT4;;3F3F&GHI I 9I Is   3JJc                    t         NNotImplementedError)r;   headss     r>   prune_headsz$TFXLNetRelativeAttention.prune_headsy       !!r?   c                    t        |      }t        j                  ||d   |d   |d   |d   f      }|dddf   }t        j                  ||d   |d   dz
  |d   |d   f      }|ddd|ddddf   }|S )z<perform relative shift to form the relative attention score.r!   r   rN   r	   N.)r   rS   reshape)r;   xklenx_sizes       r>   	rel_shiftz"TFXLNetRelativeAttention.rel_shift|   s    AJJq6!9fQiF1IFGab#gJJJq6!9fQi!mVAYq	JKa4Ao r?   c
                   t        j                  d|| j                  z   |      }
t        j                  d|| j                  z   |      }| j	                  |t        |
      d         }|d}nEt        j                  d|| j                  z   | j                        }t        j                  d||      }|
|z   |z   | j                  z  }|K|j                  t         j                  k(  s|j                  t         j                  k(  r	|d|z  z
  }n|d|z  z
  }t        |d	      }| j                  ||	
      }|||z  }t        j                  d||      }|r||fS |S )z.Core relative positional attention operations.zibnd,jbnd->ijbnr!   )ra   r   zibnd,snd->ibnszijbs,ibns->ijbni  gꌠ9Y>)Faxistrainingzijbn,jbnd->ibnd)rS   einsumrM   rK   rc   r   rL   rO   r1   dtypefloat16bfloat16r   r8   )r;   q_headk_head_hv_head_hk_head_rseg_mat	attn_mask	head_maskr3   rh   acbdef
attn_score	attn_probattn_vecs                   r>   rel_attn_corez&TFXLNetRelativeAttention.rel_attn_core   sM   
 YY(&4==*@(K YY(&4==*@(K^^BZ^A%6^7 ?B+Vdmm-CT^^TB,gr:B 2gldjj0
 "**,	2;;0N'%)*;;
'$*::
 #:A6	LLXL>	  !I-I 99.	8DY&&r?   c                    t        j                  d|| j                        }| j                  ||      }|r||z   }| j	                  |      }|S )zPost-attention processing.zibnd,hnd->ibhrg   )rS   ri   rH   r8   r&   )r;   hry   residualrh   attn_outoutputs          r>   post_attentionz'TFXLNetRelativeAttention.post_attention   sK     99_h?<<8<<!|H*r?   c                >   ||1t        t        |            dkD  rt        j                  ||gd      }n|}t        j                  d|| j
                        }t        j                  d|| j                        }t        j                  d|| j                        }t        j                  d|| j                        }| j                  |||||||	|
|	      }|
r|\  }}| j                  |||      }t        j                  d|| j                        }|Pt        j                  d||      }| j                  |||||||	|
|	      }|
r|\  }}t        j                  d||      }n!| j                  |||||||	|
|	      }|
r|\  }}| j                  |||      }|
rf}n|1t        t        |            dkD  rt        j                  ||gd      }n|}t        j                  d|| j                        }t        j                  d|| j
                        }t        j                  d|| j                        }t        j                  d|| j                        }| j                  |||||||	|
|	      }|
r|\  }}| j                  |||      }d }||f}|
r|fz   }|S )Nr!   r   re   zibh,hnd->ibndrg   zmbnd,mlb->lbndzlbnd,mlb->mbnd)lenr   rS   concatri   rF   rG   rI   rA   rz   r   )r;   r|   gattn_mask_hattn_mask_grI   rq   memstarget_mappingrs   r3   rh   catrn   ro   rp   q_head_h
attn_vec_hattn_prob_houtput_hq_head_g
attn_vec_gattn_prob_goutput_grx   ry   outputss                              r>   callzTFXLNetRelativeAttention.call   s    = C
4(8$9A$=iiq	2 yy#tvv>H yy#tvv>H yy!TVV<H yy!TVV<H ++!! , 
J !*4'
K **1j8*LH yy!TVV<H )99%5xP!//%% 0 

 %.8+JYY'7^T
!//%% 0 

 %.8+J **1j8*LH '4	 C
4(8$9A$=iiq	2 yy!TVV<Hyy#tvv>Hyy#tvv>H yy!TVV<H ))!! * 
H !&.#) **1h*JHHX&,Gr?   rX   )F)TFNNNFF
r   np.ndarray | tf.Tensor | Noner   r   rs   r   r3   Optional[bool]rh   bool)__name__
__module____qualname__r,   rU   r\   rc   rz   r   r   __classcell__r=   s   @r>   r$   r$   ?   sy    (#IJ"
 pu*X* /38<37,1I ,I 6I 1I *I Ir?   r$   c                  .     e Zd Z fdZddZddZ xZS )TFXLNetFeedForwardc                   t        |   di | t        j                  j	                  |j
                  d      | _        t        j                  j                  |j                  t        |j                        d      | _        t        j                  j                  |j                  t        |j                        d      | _        t        j                  j                  |j                        | _        t!        |j"                  t$              r"t'        |j"                        | _        || _        y |j"                  | _        || _        y )Nr&   r'   layer_1kernel_initializerr)   layer_2r*   )r+   r,   r   r4   r5   r6   r&   Densed_innerr   r2   r   r-   r   r7   r8   
isinstanceff_activationstrr
   activation_functionr9   r:   s      r>   r,   zTFXLNetFeedForward.__init__N  s    "6",,99&BWBW^j9k||))NNv?W?W/X_h * 
 ||))NNv?W?W/X_h * 
 ||++FNN;f**C0'89M9M'ND$  (.';';D$r?   c                    |}| j                  |      }| j                  |      }| j                  ||      }| j                  |      }| j                  ||      }| j	                  ||z         }|S )Nrg   )r   r   r8   r   r&   )r;   inprh   r   s       r>   r   zTFXLNetFeedForward.call^  sn    f%))&1fx8f%fx8#.r?   c                   | j                   ry d| _         t        | dd       dt        j                  | j                  j
                        5  | j                  j                  d d | j                  j                  g       d d d        t        | dd       dt        j                  | j                  j
                        5  | j                  j                  d d | j                  j                  g       d d d        t        | dd       et        j                  | j                  j
                        5  | j                  j                  d d | j                  j                  g       d d d        y y # 1 sw Y   xY w# 1 sw Y   xY w# 1 sw Y   y xY w)NTr&   r   r   )rQ   rR   rS   rT   r&   r)   rU   r9   r-   r   r   r   r;   rV   s     r>   rU   zTFXLNetFeedForward.buildh  sA   ::
4t,8t334 I%%tT4;;3F3F&GHI4D)5t||001 F""D$0C0C#DEF4D)5t||001 F""D$0C0C#DEF F 6I IF FF Fs$   3E*<3E6-3F*E36E?Fr   rX   r   r   r   r,   r   rU   r   r   s   @r>   r   r   M  s     Fr?   r   c                  L     e Zd Z fdZ	 	 	 	 	 d	 	 	 	 	 	 	 	 	 ddZddZ xZS )TFXLNetLayerc                    t        |   di | t        |d      | _        t	        |d      | _        t        j                  j                  |j                        | _	        y )Nrel_attnr)   ffr*   )
r+   r,   r$   r   r   r   r   r4   r7   r8   r:   s      r>   r,   zTFXLNetLayer.__init__x  sI    "6"0jI$V$7||++FNN;r?   c                    | j                  |||||||||	|
|      }|d d \  }}|| j                  ||      }| j                  ||      }||f|dd  z   }|S )Nrg   rN   )r   r   )r;   r   r   non_tgt_maskrr   pos_embrq   r   r   rs   r3   rh   r   s                r>   r   zTFXLNetLayer.call~  s     --   
 %Ra[(wwx(w;H778h77X&4r?   c                   | j                   ry d| _         t        | dd       Mt        j                  | j                  j
                        5  | j                  j                  d        d d d        t        | dd       Nt        j                  | j                  j
                        5  | j                  j                  d        d d d        y y # 1 sw Y   exY w# 1 sw Y   y xY w)NTr   r   )rQ   rR   rS   rT   r   r)   rU   r   r   s     r>   rU   zTFXLNetLayer.build  s    ::
4T*6t}}112 *##D)*4t$0tww||, $d#$ $ 1* *$ $   C%CCC r   r   rX   r   r   s   @r>   r   r   w  sV    < /38<37,1" ," 6" 1" *" "H	$r?   r   c                  F     e Zd Z fdZ fdZd Zd Zd Zd Zd Z	 xZ
S )TFXLNetLMHeadc                @    t        |   di | || _        || _        y )Nr*   )r+   r,   r9   input_embeddings)r;   r9   r   r<   r=   s       r>   r,   zTFXLNetLMHead.__init__  s$    "6" !1r?   c                    | j                  | j                  j                  fddd      | _        t        |   |       y )NrJ   TbiasrB   )rP   r9   
vocab_sizer   r+   rU   )r;   rV   r=   s     r>   rU   zTFXLNetLMHead.build  s7    OO4;;+A+A*CQXdhouOv	k"r?   c                    | j                   S rX   )r   r;   s    r>   get_output_embeddingsz#TFXLNetLMHead.get_output_embeddings  s    $$$r?   c                `    || j                   _        t        |      d   | j                   _        y Nr   )r   weightr   r   r;   values     r>   set_output_embeddingsz#TFXLNetLMHead.set_output_embeddings  s(    ',$+5e+<Q+?(r?   c                    d| j                   iS )Nr   )r   r   s    r>   get_biaszTFXLNetLMHead.get_bias  s    		""r?   c                X    |d   | _         t        |d         d   | j                  _        y )Nr   r   )r   r   r9   r   r   s     r>   set_biaszTFXLNetLMHead.set_bias  s'    &M	!+E&M!:1!=r?   c                J    | j                  |d      }|| j                  z   }|S )Nlinear)mode)r   r   )r;   hidden_statess     r>   r   zTFXLNetLMHead.call  s+    --m(-K%		1r?   )r   r   r   r,   rU   r   r   r   r   r   r   r   s   @r>   r   r     s'    1#%@#>r?   r   c                       e Zd ZeZ fdZd Zd ZddZd Z	d Z
d Zedd       Zdd	Ze	 	 	 	 	 	 	 	 	 	 	 	 	 	 d	 	 	 	 	 	 	 	 	 	 	 	 	 	 	 	 	 	 	 	 	 	 	 	 	 	 	 dd
       Z xZS )TFXLNetMainLayerc                f   t        |   di | || _        |j                  | _        |j                  | _        |j
                  | _        |j                  | _        |j                  | _        |j                  | _        |j                  | _	        |j                  | _
        |j                  | _        |j                  | _        |j                  | _        |j                  | _        |j                  | _        t!        |j"                  |j                  |j                  d      | _        t'        |j                        D cg c]  }t)        |d|        c}| _        t,        j.                  j1                  |j2                        | _        |j4                  | _        |j6                  | _        y c c}w )Nword_embeddingr2   r)   zlayer_._r   r*   )r+   r,   r9   output_hidden_statesr3   return_dictmem_len	reuse_lenr-   same_length	attn_typebi_data	clamp_lenn_layeruse_bfloat16r2   r   r   r   ranger   layerr   r4   r7   r8   use_mems_evaluse_mems_train)r;   r9   r<   ir=   s       r>   r,   zTFXLNetMainLayer.__init__  sP   "6"$*$?$?!!'!9!9!--~~))~~!--))~~))~~"//!'!9!90v~~AYAY`p
 JOv~~I^_Al6(1#?_
||++FNN;#11$33	 `s   >F.c                    | j                   S rX   )r   r   s    r>   get_input_embeddingsz%TFXLNetMainLayer.get_input_embeddings  s    """r?   c                `    || j                   _        t        |      d   | j                   _        y r   )r   r   r   r   r   s     r>   set_input_embeddingsz%TFXLNetMainLayer.set_input_embeddings  s(    %*")3E):1)=&r?   c                8   t        | j                        }| j                  dd| j                  f|dd      | _        | j
                  ry d| _        t        | dd       Mt        j                  | j                  j                        5  | j                  j                  d        d d d        t        | dd       K| j                  D ];  }t        j                  |j                        5  |j                  d        d d d        = y y # 1 sw Y   bxY w# 1 sw Y   UxY w)Nr!   Tmask_embrB   r   r   )r   r2   rP   r-   r   rQ   rR   rS   rT   r   r)   rU   r   )r;   rV   rD   r   s       r>   rU   zTFXLNetMainLayer.build  s    %d&<&<=a&K4V` ( 
 ::
4)40<t22778 0##))$/04$'3 &]]5::. &KK%& && 40 0& &s   D&DDD	c                    t         rX   rY   )r;   heads_to_prunes     r>   _prune_headszTFXLNetMainLayer._prune_heads  r]   r?   c                   t        j                  ||g      }t         j                  j                  |dd      }t         j                  j                  |dd      }t        j                  ||g      }t        j
                  |||z
  gd      }| j                  rQt         j                  j                  |dd      }t        j
                  |ddd|f   |z   |z
  |dd|df   gd      }|S )a  
        Creates causal attention mask. Float mask where 1.0 indicates masked, 0.0 indicates not-masked.

        Args:
            qlen: TODO Lysandre didn't fill
            mlen: TODO Lysandre didn't fill

        ```

                  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]
        ```
        r   r   r!   N)rS   oneslinalg	band_partrJ   r   r   )	r;   qlenmlenrr   mask_umask_diaattn_mask_padretmask_ls	            r>   create_maskzTFXLNetMainLayer.create_mask	  s    & GGT4L)	$$Y2699&&y!Q7$.ii(9:A>YY((B:F))SETE]V3h>AtuHNPQRC
r?   c                   | j                   | j                   dkD  r|d | j                    }| j                  | j                  dk(  rd}n| j                   }|||d  }nt        j                  ||gd      |d  }t        j                  |      S r   )r   r   rS   r   stop_gradient)r;   curr_outprev_memcutoffnew_mems        r>   	cache_memzTFXLNetMainLayer.cache_mem&  s    >>%$..1*< 0$..1H<<4<<1#4 F ll]Fvw'Gii8 4a8AG((r?   c                    t        j                  d| |      }t        j                  t        j                  |      t        j                  |      gd      }|d d d d d f   }|t        j
                  |d|dg      }|S )Nzi,d->idr   re   r!   )rS   ri   r   sincostile)pos_seqinv_freqbszsinusoid_inpr   s        r>   positional_embeddingz%TFXLNetMainLayer.positional_embedding;  sk    yyGX>))RVVL1266,3GHrR!T1*%?ggg3{3Gr?   c                   t        j                  d| j                  d      }dd|| j                  z  z  z  }| j                  dk(  r|| }}n-| j                  dk(  r|d}}nt	        d| j                   d	      | j
                  rt        j                  ||d
      }t        j                  | | d      }	| j                  dkD  rXt        j                  || j                   | j                        }t        j                  |	| j                   | j                        }	|D|dz  dk7  rt	        d| d      | j                  |||dz        }
| j                  |	||dz        }n$| j                  ||      }
| j                  |	|      }t        j                  |
|gd      }|S t        j                  ||d
      }| j                  dkD  r,t        j                  || j                   | j                        }| j                  |||      }|S )z$create relative positional encoding.r   g       @r!   i'  biunir   zUnknown `attn_type` .g            ?rN   zWith bi_data, the batch size z should be divisible by 2re   )
rS   r   r-   r   r/   r   r   clip_by_valuer  r   )r;   r   ra   r  freq_seqr
  begendfwd_pos_seqbwd_pos_seqfwd_pos_embbwd_pos_embr   s                r>   relative_positional_encodingz-TFXLNetMainLayer.relative_positional_encodingF  s   88At||S1(T\\"9:;>>T!dUC^^u$RC3DNN3C1EFF<<((3T2K((C4#s3K~~! ..{T^^OT^^\ ..{T^^OT^^\7a<$'DSEIb%cdd"77XsVWxX"77XsVWxX"77XN"77XNiik :CG  ((3T2K~~! ..{T^^OT^^\//XsKGr?   c                   |r|
| j                   }
n| j                  }
||	t        d      |)t        j                  |d      }t        |      d d \  }}n6|	)t        j                  |	d      }	t        |	      d d \  }}nt        d      |t        j                  |d      nd }|t        j                  |d      nd }|t        j                  |d      nd }|t        j                  |d      nd }|t        j                  |d      nd }||d   t        |d         d   nd}||z   }| j                  d	k(  r | j                  ||      }|d d d d d d f   }n*| j                  d
k(  rd }nt        d| j                         |	|J d       |;|9t        j                  d      }dt        j                  ||j                        z
  }||	|d    |z   }n|||d    }n	|||}nd }|f|dkD  r=t        j                  t        |      d   ||g      }t        j                  ||gd      }||d d d d d d d f   }n||d d d d d d d f   z  }|$t        j                  |dkD  |j                        }||t        j                  |       }|dkD  r.t        j                  t        j                  ||g      |gd      }t        j                  ||d d d d d d f   z   dkD  |j                        }nd }|	|	}n1t        || j                  j                          | j                  |      }| j#                  ||      }|Ct        j$                  | j&                  t        |      d   |dg      }| j#                  ||      }nd }||dkD  r<t        j                  ||g|j                        }t        j                  ||gd      }n|}t        j                  t        j(                  t        j*                  |d d d f   |d d d f               |j                        }t        j,                  |d      }nd }| j/                  |||      }| j#                  ||      }|t0        d g| j2                  z  }d} |d gt5        | j6                        z  }|rg nd }!|rg nd }"t9        | j6                        D ]q  \  }#}$|
r| | j;                  |||#         fz   } |r|"j=                  |||fn|        |$||||||||#   |||#   ||      }%|%d d \  }}|s^|!j=                  |%d          s |r|"j=                  |||fn|       | j#                  ||n||      }&t        j                  |&d      }&|
sd } |r'|t?        d |"D              }"nt?        d |"D              }"|r'|t?        d |!D              }!nt?        d |!D              }!|st?        d |&| |"|!fD              S tA        |&| |"|!      S )NzDYou cannot specify both input_ids and inputs_embeds at the same time)r!   r   permrN   r!   r   rN   z5You have to specify either input_ids or inputs_embeds)r!   rN   r   r   r  r  zUnsupported attention type: zYou can only use one of input_mask (uses 1 for padding) or attention_mask (uses 0 for padding, added for compatibility with BERT). Please choose one.r  rj   r!   re   r   rg   )r  r*   c              3  X   K   | ]"  }|D ]  }t        j                  |d         $ ywr  r  NrS   	transpose).0hsr|   s      r>   	<genexpr>z(TFXLNetMainLayer.call.<locals>.<genexpr>(  s-     %j"gi%jbcbll19&E&E%j&E%js   (*c              3  J   K   | ]  }t        j                  |d         ywr"  r#  )r%  r&  s     r>   r'  z(TFXLNetMainLayer.call.<locals>.<genexpr>*  s     %_2bll2I&F&F%_   !#c              3  @   K   | ]  }t        d  |D                yw)c              3  J   K   | ]  }t        j                  |d         yw)rN   r	   r   r!   r  Nr#  )r%  attn_streams     r>   r'  z2TFXLNetMainLayer.call.<locals>.<genexpr>.<genexpr>/  s     \;",,{FF\r)  N)tupler%  ts     r>   r'  z(TFXLNetMainLayer.call.<locals>.<genexpr>.  s!      #abE\Z[\\#s   c              3  J   K   | ]  }t        j                  |d         ywr,  r#  r/  s     r>   r'  z(TFXLNetMainLayer.call.<locals>.<genexpr>2  s     "Z!2<<#E#E"Zr)  c              3  &   K   | ]	  }||  y wrX   r*   )r%  rG   s     r>   r'  z(TFXLNetMainLayer.call.<locals>.<genexpr>5  s     cqUVUbcs   )last_hidden_stater   r   
attentions)!r   r   r/   rS   r$  r   r   r   constantcastrj   rJ   r   eyer   r   r   r8   r  r   logical_notequalone_hotr  rZ   r   r   r   	enumerater  appendr.  TFXLNetModelOutput)'r;   	input_idsattention_maskr   	perm_maskr   token_type_ids
input_maskrs   inputs_embedsuse_memsr3   r   r   rh   r   r  r   ra   rr   one_cst	data_mask	mems_maskr   
word_emb_kr   
word_emb_qr   mem_padcat_idsrq   r   new_memsr4  r   r   layer_moduler   r   s'                                          r>   r   zTFXLNetMainLayer.calln  sp   $ (**H))H  ]%>cdd"YV<I"9-bq1ID#&LLYGM"=1"15ID#TUUFTF`n6Bfj>H>TR\\*6:Z^
FTF`n6Bfj?H?TBLL;Z^	IWIcn9Eim)-)9d1g>Qz$q'"1%WXd{ >>U"((t4I!!Qd"23I^^t#I;DNN;KLMM !^%; 	
l	
; ."<kk#&Grww~W]]KKJ!i&;"4(94I#	(9"4(II$9!II axHHj&;A&>c%JK	IIy)&<1E	 %aAtm4	Yq!Q}55	 	AY__EI FF4L=Lax!yy"((D$<*@,)OVXY77IQ4=M0N$NRS#S[g[m[mnLL $&J*9d6I6I6T6TU,,Y7J<<
X<>%N1KA1NPSUV0WXJ ||J|BHH %ax((D#;n6J6JK))Wn$=qA( ggrxxq$w(?qAQRS$**G jj!,GG 33D$C3H,,w,:  %%-I<6C

O+D,R$
2(4 	.OA|#t~~hQ'H&JJ#$$X=Qh%9W_`"Q!!!G ")!Hh !!'!*--	.2    9M(H!5S[\(*>hHW_` f95H# %%jP]%j j %%_Q^%_ _)" #fp# 
 #"Zz"ZZ
cVX}j$Qccc!$8=]g
 	
r?   rX   NNNNNNNNNNNNNF)r>  TFModelInputType | Noner?  r   r   r   r@  r   r   r   rA  r   rB  r   rs   r   rC  r   rD  r   r3   r   r   r   r   r   rh   r   )r   r   r   r"   config_classr,   r   r   rU   r   r   r  staticmethodr  r  r   r   r   r   s   @r>   r   r     s   L48#>&"":)*  &P  .28<.2378<8<48377;#',0/3&*J
*J
 6J
 ,	J

 1J
 6J
 6J
 2J
 1J
 5J
 !J
 *J
 -J
 $J
 J
 J
r?   r   c                      e Zd ZdZeZdZy)TFXLNetPreTrainedModelz
    An abstract class to handle weights initialization and a simple interface for downloading and loading pretrained
    models.
    transformerN)r   r   r   __doc__r"   rP  base_model_prefixr*   r?   r>   rS  rS  <  s    
 L%r?   rS  c                  J    e Zd ZU dZdZded<   dZded<   dZded<   dZded	<   y)
r=  a  
    Output type of [`TFXLNetModel`].

    Args:
        last_hidden_state (`tf.Tensor` 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[tf.Tensor]` 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(tf.Tensor)`, *optional*, returned when `output_hidden_states=True` is passed or when `config.output_hidden_states=True`):
            Tuple of `tf.Tensor` (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(tf.Tensor)`, *optional*, returned when `output_attentions=True` is passed or when `config.output_attentions=True`):
            Tuple of `tf.Tensor` (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	tf.Tensorr3  List[tf.Tensor] | Noner   Tuple[tf.Tensor, ...] | Noner   r4  )	r   r   r   rU  r3  __annotations__r   r   r4  r*   r?   r>   r=  r=  F  s5    4 $(y'#'D
 '26M/6/3J,3r?   r=  c                  X    e Zd ZU dZdZded<   dZded<   dZded<   dZd	ed
<   dZ	d	ed<   y)TFXLNetLMHeadModelOutputa  
    Output type of [`TFXLNetLMHeadModel`].

    Args:
        loss (`tf.Tensor` of shape *(1,)*, *optional*, returned when `labels` is provided)
            Language modeling loss (for next-token prediction).
        logits (`tf.Tensor` 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[tf.Tensor]` 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(tf.Tensor)`, *optional*, returned when `output_hidden_states=True` is passed or when `config.output_hidden_states=True`):
            Tuple of `tf.Tensor` (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(tf.Tensor)`, *optional*, returned when `output_attentions=True` is passed or when `config.output_attentions=True`):
            Tuple of `tf.Tensor` (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tf.Tensor | NonelossrX  logitsrY  r   rZ  r   r4  
r   r   r   rU  r_  r[  r`  r   r   r4  r*   r?   r>   r]  r]  h  s?    8 "D
!FI#'D
 '26M/6/3J,3r?   r]  c                  X    e Zd ZU dZdZded<   dZded<   dZded<   dZd	ed
<   dZ	d	ed<   y)&TFXLNetForSequenceClassificationOutputa)  
    Output type of [`TFXLNetForSequenceClassification`].

    Args:
        loss (`tf.Tensor` of shape `(1,)`, *optional*, returned when `label` is provided):
            Classification (or regression if config.num_labels==1) loss.
        logits (`tf.Tensor` of shape `(batch_size, config.num_labels)`):
            Classification (or regression if config.num_labels==1) scores (before SoftMax).
        mems (`List[tf.Tensor]` 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(tf.Tensor)`, *optional*, returned when `output_hidden_states=True` is passed or when `config.output_hidden_states=True`):
            Tuple of `tf.Tensor` (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(tf.Tensor)`, *optional*, returned when `output_attentions=True` is passed or when `config.output_attentions=True`):
            Tuple of `tf.Tensor` (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_  rX  r`  rY  r   rZ  r   r4  ra  r*   r?   r>   rc  rc    ?    2 "D
!FI#'D
 '26M/6/3J,3r?   rc  c                  X    e Zd ZU dZdZded<   dZded<   dZded<   dZd	ed
<   dZ	d	ed<   y)#TFXLNetForTokenClassificationOutputa  
    Output type of [`TFXLNetForTokenClassificationOutput`].

    Args:
        loss (`tf.Tensor` of shape `(1,)`, *optional*, returned when `labels` is provided) :
            Classification loss.
        logits (`tf.Tensor` of shape `(batch_size, sequence_length, config.num_labels)`):
            Classification scores (before SoftMax).
        mems (`List[tf.Tensor]` 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(tf.Tensor)`, *optional*, returned when `output_hidden_states=True` is passed or when `config.output_hidden_states=True`):
            Tuple of `tf.Tensor` (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(tf.Tensor)`, *optional*, returned when `output_attentions=True` is passed or when `config.output_attentions=True`):
            Tuple of `tf.Tensor` (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_  rX  r`  rY  r   rZ  r   r4  ra  r*   r?   r>   rf  rf    rd  r?   rf  c                  X    e Zd ZU dZdZded<   dZded<   dZded<   dZd	ed
<   dZ	d	ed<   y)TFXLNetForMultipleChoiceOutputa.  
    Output type of [`TFXLNetForMultipleChoice`].

    Args:
        loss (`tf.Tensor` of shape *(1,)*, *optional*, returned when `labels` is provided):
            Classification loss.
        logits (`tf.Tensor` 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[tf.Tensor]` 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(tf.Tensor)`, *optional*, returned when `output_hidden_states=True` is passed or when `config.output_hidden_states=True`):
            Tuple of `tf.Tensor` (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(tf.Tensor)`, *optional*, returned when `output_attentions=True` is passed or when `config.output_attentions=True`):
            Tuple of `tf.Tensor` (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_  rX  r`  rY  r   rZ  r   r4  ra  r*   r?   r>   rh  rh    s?    6 "D
!FI#'D
 '26M/6/3J,3r?   rh  c                  f    e Zd ZU dZdZded<   dZded<   dZded<   dZded	<   dZ	d
ed<   dZ
d
ed<   y)'TFXLNetForQuestionAnsweringSimpleOutputa  
    Output type of [`TFXLNetForQuestionAnsweringSimple`].

    Args:
        loss (`tf.Tensor` 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 (`tf.Tensor` of shape `(batch_size, sequence_length,)`):
            Span-start scores (before SoftMax).
        end_logits (`tf.Tensor` of shape `(batch_size, sequence_length,)`):
            Span-end scores (before SoftMax).
        mems (`List[tf.Tensor]` 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(tf.Tensor)`, *optional*, returned when `output_hidden_states=True` is passed or when `config.output_hidden_states=True`):
            Tuple of `tf.Tensor` (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(tf.Tensor)`, *optional*, returned when `output_attentions=True` is passed or when `config.output_attentions=True`):
            Tuple of `tf.Tensor` (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_  rX  start_logits
end_logitsrY  r   rZ  r   r4  )r   r   r   rU  r_  r[  rk  rl  r   r   r4  r*   r?   r>   rj  rj    sI    6 "D
!"L)" J	 #'D
 '26M/6/3J,3r?   rj  a{	  

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

    This model is also a [keras.Model](https://www.tensorflow.org/api_docs/python/tf/keras/Model) subclass. Use it
    as a regular TF 2.0 Keras Model and refer to the TF 2.0 documentation for all matter related to general usage and
    behavior.

    <Tip>

    TensorFlow models and layers in `transformers` accept two formats as input:

    - having all inputs as keyword arguments (like PyTorch models), or
    - having all inputs as a list, tuple or dict in the first positional argument.

    The reason the second format is supported is that Keras methods prefer this format when passing inputs to models
    and layers. Because of this support, when using methods like `model.fit()` things should "just work" for you - just
    pass your inputs and labels in any format that `model.fit()` supports! If, however, you want to use the second
    format outside of Keras methods like `fit()` and `predict()`, such as when creating your own layers or models with
    the Keras `Functional` API, there are three possibilities you can use to gather all the input Tensors in the first
    positional argument:

    - a single Tensor with `input_ids` only and nothing else: `model(input_ids)`
    - a list of varying length with one or several input Tensors IN THE ORDER given in the docstring:
    `model([input_ids, attention_mask])` or `model([input_ids, attention_mask, token_type_ids])`
    - a dictionary with one or several input Tensors associated to the input names given in the docstring:
    `model({"input_ids": input_ids, "token_type_ids": token_type_ids})`

    Note that when creating models and layers with
    [subclassing](https://keras.io/guides/making_new_layers_and_models_via_subclassing/) then you don't need to worry
    about any of this, as you can just pass inputs like you would to any other Python function!

    </Tip>

    Parameters:
        config ([`XLNetConfig`]): Model configuration class with all the parameters of the model.
            Initializing with a config file does not load the weights associated with the model, only the
            configuration. Check out the [`~PreTrainedModel.from_pretrained`] method to load the model weights.
aP  
    Args:
        input_ids (`torch.LongTensor` of shape `({0})`):
            Indices of input sequence tokens in the vocabulary.

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

            [What are input IDs?](../glossary#input-ids)
        attention_mask (`torch.FloatTensor` of shape `({0})`, *optional*):
            Mask to avoid performing attention on padding token indices. Mask values selected in `[0, 1]`:

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

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

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

            [What are token type IDs?](../glossary#token-type-ids)
        input_mask (`torch.FloatTensor` of shape `{0}`, *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`.
        head_mask (`torch.FloatTensor` of shape `(num_heads,)` or `(num_layers, num_heads)`, *optional*):
            Mask to nullify selected heads of the self-attention modules. Mask values selected in `[0, 1]`:

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

        inputs_embeds (`torch.FloatTensor` of shape `({0}, hidden_size)`, *optional*):
            Optionally, instead of passing `input_ids` you can choose to directly pass an embedded representation. This
            is useful if you want more control over how to convert `input_ids` indices into associated vectors than the
            model's internal embedding lookup matrix.
        output_attentions (`bool`, *optional*):
            Whether or not to return the attentions tensors of all attention layers. See `attentions` under returned
            tensors for more detail.
        output_hidden_states (`bool`, *optional*):
            Whether or not to return the hidden states of all layers. See `hidden_states` under returned tensors for
            more detail.
        return_dict (`bool`, *optional*):
            Whether or not to return a [`~utils.ModelOutput`] instead of a plain tuple.
z_The bare XLNet Model transformer outputting raw hidden-states without any specific head on top.c                       e Zd Z fdZe eej                  d             ee	e
e      	 	 	 	 	 	 	 	 	 	 	 	 	 	 d	 	 	 	 	 	 	 	 	 	 	 	 	 	 	 	 	 	 	 	 	 	 	 	 	 	 	 	 	 dd                     ZddZ xZS )	TFXLNetModelc                P    t        |   |g|i | t        |d      | _        y )NrT  r   )r+   r,   r   rT  r;   r9   inputsr<   r=   s       r>   r,   zTFXLNetModel.__init__  s)    3&3F3+FGr?   batch_size, sequence_length
checkpointoutput_typerP  c                D    | j                  |||||||||	|
||||      }|S )Nr>  r?  r   r@  r   rA  rB  rs   rC  rD  r3   r   r   rh   )rT  )r;   r>  r?  r   r@  r   rA  rB  rs   rC  rD  r3   r   r   rh   r   s                   r>   r   zTFXLNetModel.call  sJ    0 "")))!'/!5# # 
" r?   c                    | j                   ry d| _         t        | dd       Nt        j                  | j                  j
                        5  | j                  j                  d        d d d        y y # 1 sw Y   y xY w)NTrT  )rQ   rR   rS   rT   rT  r)   rU   r   s     r>   rU   zTFXLNetModel.build  sm    ::
4-9t//445 -  &&t,- - :- -s   A11A:rN  )r>  rO  r?  r   r   r   r@  r   r   r   rA  r   rB  r   rs   r   rC  r   rD  r   r3   r   r   r   r   r   rh   r   returnz+Union[TFXLNetModelOutput, Tuple[tf.Tensor]]rX   )r   r   r   r,   r   r   XLNET_INPUTS_DOCSTRINGformatr   _CHECKPOINT_FOR_DOCr=  _CONFIG_FOR_DOCr   rU   r   r   s   @r>   rn  rn    s   
H *+A+H+HIf+gh&&$ .28<.2378<8<48377;#',0/3&*"*" 6" ,	"
 1" 6" 6" 2" 1" 5" !" *" -" $" "  
5!" i "H-r?   rn  zt
    XLNet Model with a language modeling head on top (linear layer with weights tied to the input embeddings).
    c                       e Zd Z fdZd Zd Zd	dZe ee	j                  d             eee      	 	 	 	 	 	 	 	 	 	 	 	 	 	 	 d
	 	 	 	 	 	 	 	 	 	 	 	 	 	 	 	 	 	 	 	 	 	 	 	 	 	 	 	 	 	 	 dd                     ZddZ xZS )TFXLNetLMHeadModelc                    t        |   |g|i | t        |d      | _        t	        || j                  j
                  d      | _        d| _        y )NrT  r   lm_lossF)r+   r,   r   rT  r   r   r  supports_xla_generationrp  s       r>   r,   zTFXLNetLMHeadModel.__init__  sN    3&3F3+FG$VT-=-=-L-LS\]',$r?   c                    | j                   S rX   )r  r   s    r>   get_lm_headzTFXLNetLMHeadModel.get_lm_head  s    ||r?   c                    t        j                  dt               | j                  dz   | j                  j                  z   S )NzMThe method get_prefix_bias_name is deprecated. Please use `get_bias` instead./)warningswarnFutureWarningr)   r  r   s    r>   get_prefix_bias_namez'TFXLNetLMHeadModel.get_prefix_bias_name  s/    egtuyy3!2!222r?   c                |   |j                   d   }t        j                  |df|j                        }d|r$t        j                  |d d  d f   |gd      }nt        j                  ||gd      }|j                   d   }t        j                  |||dz
  f      }	t        j
                  ||df      }
t        j                  |	|
gd      }	t        j                  |d|dz
  f      }t        j
                  |ddf      }t        j                  ||gd      }||	||d}|rt        fd|D              |d	<   |S )
Nr   r!   r   rN   re   r   )r>  r@  r   rD  c              3  <   K   | ]  }|d  d d d d f     y wrX   r*   )r%  
layer_pastoffsets     r>   r'  zCTFXLNetLMHeadModel.prepare_inputs_for_generation.<locals>.<genexpr>  s"     "`*:hwh1n#="`s   r   )rC   rS   rJ   rj   r   r   r.  )r;   rq  past_key_valuesrD  r<   effective_batch_sizedummy_tokenr>  sequence_lengthr@  perm_mask_seq_endr   target_mapping_seq_endr  s                @r>   prepare_inputs_for_generationz0TFXLNetLMHeadModel.prepare_inputs_for_generation  sD   %||Ahh 4a8M
 		6!fWX+#6"D1MI		6;"7a@I $//!,HH2O_WXEXYZ	GG%9?A$NOIIy*;<2F	 #7Oa<O"PQ!#*>1)E!FN4J#KRTU #", 	
 ""`P_"``F6Nr?   rr  )ru  rP  c                "   | j                  |||||||||	|
||||      }|d   }| j                  ||      }d}|| j                  ||      }|s|f|dd z   }||f|z   S |S t        |||j                  |j
                  |j                        S )a  
        labels (`tf.Tensor` of shape `(batch_size, sequence_length)`, *optional*):
            Labels for computing the cross entropy classification loss. Indices should be in `[0, ...,
            config.vocab_size - 1]`.

        Return:

        Examples:

        ```python
        >>> import tensorflow as tf
        >>> import numpy as np
        >>> from transformers import AutoTokenizer, TFXLNetLMHeadModel

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

        >>> # We show how to setup inputs to predict a next token using a bi-directional context.
        >>> input_ids = tf.constant(tokenizer.encode("Hello, my dog is very <mask>", add_special_tokens=True))[
        ...     None, :
        ... ]  # We will predict the masked token

        >>> perm_mask = np.zeros((1, input_ids.shape[1], input_ids.shape[1]))
        >>> perm_mask[:, :, -1] = 1.0  # Previous tokens don't see last token

        >>> target_mapping = np.zeros(
        ...     (1, 1, input_ids.shape[1])
        ... )  # 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=tf.constant(perm_mask, dtype=tf.float32),
        ...     target_mapping=tf.constant(target_mapping, dtype=tf.float32),
        ... )

        >>> next_token_logits = outputs[
        ...     0
        ... ]  # Output has shape [target_mapping.size(0), target_mapping.size(1), config.vocab_size]
        ```rw  r   rg   Nr!   r_  r`  r   r   r4  )rT  r  hf_compute_lossr]  r   r   r4  )r;   r>  r?  r   r@  r   rA  rB  rs   rC  rD  r3   r   r   labelsrh   transformer_outputshidden_stater`  r_  r   s                        r>   r   zTFXLNetLMHeadModel.call  s    ~ #..)))!'/!5# / 
  +1-lX>''7DY!4QR!88F)-)9TGf$EvE'$))-;;*55
 	
r?   c                   | j                   ry d| _         t        | dd       Mt        j                  | j                  j
                        5  | j                  j                  d        d d d        t        | dd       Nt        j                  | j                  j
                        5  | j                  j                  d        d d d        y y # 1 sw Y   exY w# 1 sw Y   y xY w)NTrT  r  )rQ   rR   rS   rT   rT  r)   rU   r  r   s     r>   rU   zTFXLNetLMHeadModel.buildh  s    ::
4-9t//445 -  &&t,-4D)5t||001 )""4() ) 6- -) )r   )NNNNNNNNNNNNNNNNF) r>  rO  r?  r   r   r   r@  r   r   r   rA  r   rB  r   rs   r   rC  r   rD  r   r3   r   r   r   r   r   r  r   rh   r   ry  z1Union[TFXLNetLMHeadModelOutput, Tuple[tf.Tensor]]rX   )r   r   r   r,   r  r  r  r   r   rz  r{  r    r]  r}  r   rU   r   r   s   @r>   r  r    s>   -3%N *+A+H+HIf+gh+CRab .28<.2378<8<48377;#',0/3&*04!]
*]
 6]
 ,	]

 1]
 6]
 6]
 2]
 1]
 5]
 !]
 *]
 -]
 $]
 .]
  !]
" 
;#]
 c i ]
~	)r?   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                       e Zd Z fdZe eej                  d             ee	e
e      	 	 	 	 	 	 	 	 	 	 	 	 	 	 	 d	 	 	 	 	 	 	 	 	 	 	 	 	 	 	 	 	 	 	 	 	 	 	 	 	 	 	 	 	 	 	 dd                     ZddZ xZS )	 TFXLNetForSequenceClassificationc                B   t        |   |g|i | |j                  | _        t        |d      | _        t        ||j                  d      | _        t        j                  j                  |j                  t        |j                        d      | _        || _        y )NrT  r   sequence_summaryr   logits_projr   )r+   r,   
num_labelsr   rT  r   r2   r  r   r4   r   r   r  r9   rp  s       r>   r,   z)TFXLNetForSequenceClassification.__init__|  s    3&3F3 +++FG 1f&>&>EW!
 !<<--/&BZBZ2[bo . 
 r?   rr  rs  c                @   | j                  |||||||||	|
||||      }|d   }| j                  |      }| j                  |      }|dn| j                  ||      }|s|f|dd z   }||f|z   S |S t	        |||j
                  |j                  |j                        S )a  
        labels (`tf.Tensor` 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).
        rw  r   Nr!   r  )rT  r  r  r  rc  r   r   r4  r;   r>  r?  r   r@  r   rA  rB  rs   rC  rD  r3   r   r   r  rh   r  r   r`  r_  s                       r>   r   z%TFXLNetForSequenceClassification.call  s    > #..)))!'/!5# / 
  %Q'&&v.!!&)~t4+?+?+OY!4QR!88F)-)9TGf$EvE5$))-;;*55
 	
r?   c                   | j                   ry d| _         t        | dd       Mt        j                  | j                  j
                        5  | j                  j                  d        d d d        t        | dd       Mt        j                  | j                  j
                        5  | j                  j                  d        d d d        t        | dd       et        j                  | j                  j
                        5  | j                  j                  d d | j                  j                  g       d d d        y y # 1 sw Y   xY w# 1 sw Y   xY w# 1 sw Y   y xY wNTrT  r  r  rQ   rR   rS   rT   rT  r)   rU   r  r  r9   r-   r   s     r>   rU   z&TFXLNetForSequenceClassification.build  $   ::
4-9t//445 -  &&t,-4+T2>t4499: 2%%++D124-9t//445 J  &&dDKK4G4G'HIJ J :- -2 2J J$   D<%E?3E<EEEr  ) r>  rO  r?  r   r   r   r@  r   r   r   rA  r   rB  r   rs   r   rC  r   rD  r   r3   r   r   r   r   r   r  r   rh   r   ry  z?Union[TFXLNetForSequenceClassificationOutput, Tuple[tf.Tensor]]rX   )r   r   r   r,   r   r   rz  r{  r   r|  rc  r}  r   rU   r   r   s   @r>   r  r  t  s"    *+A+H+HIf+gh&:$ .28<.2378<8<48377;#',0/3&*04!9
*9
 69
 ,	9

 19
 69
 69
 29
 19
 59
 !9
 *9
 -9
 $9
 .9
  !9
" 
I#9
 i 9
vJr?   r  z
    XLNET Model with a multiple choice classification head on top (a linear layer on top of the pooled output and a
    softmax) e.g. for RocStories/SWAG tasks.
    c                       e Zd Z fdZe eej                  d             ee	e
e      	 	 	 	 	 	 	 	 	 	 	 	 	 	 	 d	 	 	 	 	 	 	 	 	 	 	 	 	 	 	 	 	 	 	 	 	 	 	 	 	 	 	 	 	 	 	 dd                     ZddZ xZS )	TFXLNetForMultipleChoicec                   t        |   |g|i | t        |d      | _        t	        ||j
                  d      | _        t        j                  j                  dt        |j
                        d      | _        || _        y )NrT  r   r  r   r!   r  r   )r+   r,   r   rT  r   r2   r  r   r4   r   r   r  r9   rp  s       r>   r,   z!TFXLNetForMultipleChoice.__init__  s~    3&3F3+FG 1f&>&>EW!
 !<<--/&2J2J"KR_ . 
 r?   z(batch_size, num_choices, sequence_lengthrs  c                   |t        |      d   }t        |      d   }nt        |	      d   }t        |	      d   }|t        j                  |d|f      nd}|t        j                  |d|f      nd}|t        j                  |d|f      nd}|t        j                  |d|f      nd}|	%t        j                  |	d|t        |	      d   f      nd}| j                  ||||||||||
||||      }|d   }| j	                  |      }| j                  |      }t        j                  |d|f      }|dn| j                  ||      }|s|f|dd z   }||f|z   S |S t        |||j                  |j                  |j                        S )	a5  
        labels (`tf.Tensor` 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)
        Nr!   rN   r   r	   )r   rh   r   r  )r   rS   r_   rT  r  r  r  rh  r   r   r4  )r;   r>  rA  rB  r?  r   r@  r   rs   rC  rD  r3   r   r   r  rh   num_choices
seq_lengthflat_input_idsflat_attention_maskflat_token_type_idsflat_input_maskflat_inputs_embedsr  r   r`  reshaped_logitsr_  s                               r>   r   zTFXLNetForMultipleChoice.call  s   >  $Y/2K#I.q1J$]3A6K#M215JDMDYIJ/?@_cN\Nhbjj"j9IJnrN\Nhbjj"j9IJnrFPF\"**Z"j1ABbf ( JJ}r:z-7PQR7S&TU 	
 #.. # / 
  %Q'&&v.!!&)**Vb+->?~t4+?+?+X%'*=ab*AAF)-)9TGf$EvE-"$))-;;*55
 	
r?   c                   | j                   ry d| _         t        | dd       Mt        j                  | j                  j
                        5  | j                  j                  d        d d d        t        | dd       Mt        j                  | j                  j
                        5  | j                  j                  d        d d d        t        | dd       et        j                  | j                  j
                        5  | j                  j                  d d | j                  j                  g       d d d        y y # 1 sw Y   xY w# 1 sw Y   xY w# 1 sw Y   y xY wr  r  r   s     r>   rU   zTFXLNetForMultipleChoice.build?  r  r  r  ) r>  rO  rA  r   rB  r   r?  r   r   r   r@  r   r   r   rs   r   rC  r   rD  r   r3   r   r   r   r   r   r  r   rh   r   ry  z7Union[TFXLNetForMultipleChoiceOutput, Tuple[tf.Tensor]]rX   )r   r   r   r,   r   r   rz  r{  r   r|  rh  r}  r   rU   r   r   s   @r>   r  r    s4   
 *+A+H+HIs+tu&2$ .28<488<.2378<377;#',0/3&*04!H
*H
 6H
 2	H

 6H
 ,H
 1H
 6H
 1H
 5H
 !H
 *H
 -H
 $H
 .H
  !H
" 
A#H
 v H
TJr?   r  z
    XLNet Model with a token classification head on top (a linear layer on top of the hidden-states output) e.g. for
    Named-Entity-Recognition (NER) tasks.
    c                       e Zd Z fdZe eej                  d             ee	e
e      	 	 	 	 	 	 	 	 	 	 	 	 	 	 	 d	 	 	 	 	 	 	 	 	 	 	 	 	 	 	 	 	 	 	 	 	 	 	 	 	 	 	 	 	 	 	 dd                     ZddZ xZS )	TFXLNetForTokenClassificationc                   t        |   |g|i | |j                  | _        t        |d      | _        t
        j                  j                  |j                  t        |j                        d      | _
        || _        y )NrT  r   
classifierr   )r+   r,   r  r   rT  r   r4   r   r   r2   r  r9   rp  s       r>   r,   z&TFXLNetForTokenClassification.__init__V  ss    3&3F3 +++FG,,,,/&BZBZ2[bn - 
 r?   rr  rs  c                   | j                  |||||||||	|
||||      }|d   }| j                  |      }|dn| j                  ||      }|s|f|dd z   }||f|z   S |S t        |||j                  |j
                  |j                        S )z
        labels (`tf.Tensor` of shape `(batch_size, sequence_length)`, *optional*):
            Labels for computing the token classification loss. Indices should be in `[0, ..., config.num_labels - 1]`.
        rw  r   Nr!   r  )rT  r  r  rf  r   r   r4  r  s                       r>   r   z"TFXLNetForTokenClassification.call`  s    < #..)))!'/!5# / 
  %Q'(~t4+?+?+OY!4QR!88F)-)9TGf$EvE2$))-;;*55
 	
r?   c                   | j                   ry d| _         t        | dd       Mt        j                  | j                  j
                        5  | j                  j                  d        d d d        t        | dd       et        j                  | j                  j
                        5  | j                  j                  d d | j                  j                  g       d d d        y y # 1 sw Y   |xY w# 1 sw Y   y xY w)NTrT  r  )
rQ   rR   rS   rT   rT  r)   rU   r  r9   hidden_sizer   s     r>   rU   z#TFXLNetForTokenClassification.build      ::
4-9t//445 -  &&t,-4t,8t334 M%%tT4;;3J3J&KLM M 9- -M M   C"%3C."C+.C7r  ) r>  rO  r?  r   r   r   r@  r   r   r   rA  r   rB  r   rs   r   rC  r   rD  r   r3   r   r   r   r   r   r  r   rh   r   ry  z<Union[TFXLNetForTokenClassificationOutput, Tuple[tf.Tensor]]rX   )r   r   r   r,   r   r   rz  r{  r   r|  rf  r}  r   rU   r   r   s   @r>   r  r  N  s"    *+A+H+HIf+gh&7$ .28<.2378<8<48377;#',0/3&*04!5
*5
 65
 ,	5

 15
 65
 65
 25
 15
 55
 !5
 *5
 -5
 $5
 .5
  !5
" 
F#5
 i 5
n	Mr?   r  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                       e Zd Z fdZe eej                  d             ee	e
e      	 	 	 	 	 	 	 	 	 	 	 	 	 	 	 	 d	 	 	 	 	 	 	 	 	 	 	 	 	 	 	 	 	 	 	 	 	 	 	 	 	 	 	 	 	 	 	 	 	 dd                     ZddZ xZS )	!TFXLNetForQuestionAnsweringSimplec                    t        |   |g|i | t        |d      | _        t        j
                  j                  |j                  t        |j                        d      | _
        || _        y )NrT  r   
qa_outputsr   )r+   r,   r   rT  r   r4   r   r  r   r2   r  r9   rp  s       r>   r,   z*TFXLNetForQuestionAnsweringSimple.__init__  sf    3&3F3+FG,,,,/&BZBZ2[bn - 
 r?   rr  rs  c                   | j                  |||||||||	|
||||      }|d   }| j                  |      }t        j                  |dd      \  }}t        j                  |d      }t        j                  |d      }d}||d|i}||d<   | j                  |||f      }|s||f|d	d z   }||f|z   S |S t        ||||j                  |j                  |j                  
      S )a  
        start_positions (`tf.Tensor` of shape `(batch_size,)`, *optional*):
            Labels for position (index) of the start of the labelled span for computing the token classification loss.
            Positions are clamped to the length of the sequence (`sequence_length`). Position outside of the sequence
            are not taken into account for computing the loss.
        end_positions (`tf.Tensor` of shape `(batch_size,)`, *optional*):
            Labels for position (index) of the end of the labelled span for computing the token classification loss.
            Positions are clamped to the length of the sequence (`sequence_length`). Position outside of the sequence
            are not taken into account for computing the loss.
        rw  r   rN   r   re   Nstart_positionend_positionr!   )r_  rk  rl  r   r   r4  )
rT  r  rS   splitsqueezer  rj  r   r   r4  )r;   r>  r?  r   r@  r   rA  rB  rs   rC  rD  r3   r   r   start_positionsend_positionsrh   r  sequence_outputr`  rk  rl  r_  r  r   s                            r>   r   z&TFXLNetForQuestionAnsweringSimple.call  s3   H #..)))!'/!5# / 
  .a01#%88FAB#? jzz,R8ZZ
4
&=+D&8F%2F>"''z0JKD"J/2Eab2IIF)-)9TGf$EvE6%!$))-;;*55
 	
r?   c                   | j                   ry d| _         t        | dd       Mt        j                  | j                  j
                        5  | j                  j                  d        d d d        t        | dd       et        j                  | j                  j
                        5  | j                  j                  d d | j                  j                  g       d d d        y y # 1 sw Y   |xY w# 1 sw Y   y xY w)NTrT  r  )
rQ   rR   rS   rT   rT  r)   rU   r  r9   r  r   s     r>   rU   z'TFXLNetForQuestionAnsweringSimple.build  r  r  )NNNNNNNNNNNNNNNF)"r>  rO  r?  r   r   r   r@  r   r   r   rA  r   rB  r   rs   r   rC  r   rD  r   r3   r   r   r   r   r   r  r   r  r   rh   r   ry  z@Union[TFXLNetForQuestionAnsweringSimpleOutput, Tuple[tf.Tensor]]rX   )r   r   r   r,   r   r   rz  r{  r   r|  rj  r}  r   rU   r   r   s   @r>   r  r    sB    *+A+H+HIf+gh&;$ .28<.2378<8<48377;#',0/3&*9=7;#E
*E
 6E
 ,	E

 1E
 6E
 6E
 2E
 1E
 5E
 !E
 *E
 -E
 $E
 7E
  5!E
" #E
$ 
J%E
 i E
N	Mr?   r  )GrU  
__future__r   r  dataclassesr   typingr   r   r   r   numpynp
tensorflowrS   activations_tfr
   modeling_tf_utilsr   r   r   r   r   r   r   r   r   r   r   r   r   tf_utilsr   r   r   utilsr   r   r   r   r   r    configuration_xlnetr"   
get_loggerr   loggerr|  r}  r4   Layerr$   r   r   r   r   rS  r=  r]  rc  rf  rh  rj  XLNET_START_DOCSTRINGrz  rn  r  r  r  r  r  r*   r?   r>   <module>r     s    #  ! / /   /    S R  - 
		H	%. Ku||11 K\'F++ 'FT4$5<<%% 4$nELL&& @ j
u||)) j
 j
Z&. & 4 4 4B !4{ !4 !4H 4[ 4 4B 4+ 4 4B  4[  4  4F !4k !4 !4H( TF R e6-) 6-	6-r  	a)/1M a)a)H  \J'=?[ \J\J~  jJ57K jJjJZ  RM$:<U RMRMj  `M(>@W `M`Mr?   