
    sg                   D   d Z ddlmZ ddlZddl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 ddl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* ddl+m,Z,  e)jZ                  e.      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                        Z6 G d dejb                  jd                        Z7 G d dejb                  jd                        Z8 G d dejb                  jd                        Z9 G d dejb                  jd                        Z: G d dejb                  jd                        Z; G d  d!ejb                  jd                        Z< G d" d#ejb                  jd                        Z= G d$ d%ejb                  jd                        Z>e  G d& d'ejb                  jd                               Z? G d( d)e      Z@d*ZAd+ZB e'd,eA       G d- d.e@             ZC e'd/eA       G d0 d1e@e             ZD e'd2eA       G d3 d4e@e             ZE e'd5eA       G d6 d7e@e             ZF e'd8eA       G d9 d:e@e             ZGy);zTF 2.0 LayoutLM model.    )annotationsN)DictOptionalTupleUnion   )get_tf_activation)+TFBaseModelOutputWithPastAndCrossAttentions.TFBaseModelOutputWithPoolingAndCrossAttentionsTFMaskedLMOutputTFQuestionAnsweringModelOutputTFSequenceClassifierOutputTFTokenClassifierOutput)
TFMaskedLanguageModelingLossTFModelInputTypeTFPreTrainedModelTFQuestionAnsweringLossTFSequenceClassificationLossTFTokenClassificationLossget_initializerkeraskeras_serializableunpack_inputs)check_embeddings_within_bounds
shape_liststable_softmax)add_start_docstrings%add_start_docstrings_to_model_forwardloggingreplace_return_docstrings   )LayoutLMConfigr"   c                  \     e Zd ZdZd fdZddZ	 	 	 	 	 	 d	 	 	 	 	 	 	 	 	 	 	 	 	 ddZ xZS )	TFLayoutLMEmbeddingszGConstruct the embeddings from word, position and token_type embeddings.c                x   t        |   di | || _        |j                  | _        |j                  | _        |j
                  | _        |j                  | _        t        j                  j                  |j                  d      | _        t        j                  j                  |j                        | _        y )N	LayerNormepsilonnamerate )super__init__confighidden_sizemax_position_embeddingsmax_2d_position_embeddingsinitializer_ranger   layersLayerNormalizationlayer_norm_epsr&   Dropouthidden_dropout_probdropoutselfr/   kwargs	__class__s      d/var/www/html/venv/lib/python3.12/site-packages/transformers/models/layoutlm/modeling_tf_layoutlm.pyr.   zTFLayoutLMEmbeddings.__init__<   s    "6"!--'-'E'E$*0*K*K'!'!9!988AVAV]h8i||++1K1K+L    c                D   t        j                  d      5  | j                  d| j                  j                  | j
                  gt        | j                              | _        d d d        t        j                  d      5  | j                  d| j                  j                  | j
                  gt        | j                              | _
        d d d        t        j                  d      5  | j                  d| j                  | j
                  gt        | j                              | _        d d d        t        j                  d      5  | j                  d| j                  | j
                  gt        | j                              | _        d d d        t        j                  d      5  | j                  d| j                  | j
                  gt        | j                              | _        d d d        t        j                  d	      5  | j                  d| j                  | j
                  gt        | j                              | _        d d d        t        j                  d
      5  | j                  d| j                  | j
                  gt        | j                              | _        d 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   xY w# 1 sw Y   ~xY w# 1 sw Y   +xY w# 1 sw Y   xY w# 1 sw Y   xY w# 1 sw Y   2xY w# 1 sw Y   xY w# 1 sw Y   y xY w)Nword_embeddingsweight)r)   shapeinitializertoken_type_embeddings
embeddingsposition_embeddingsx_position_embeddingsy_position_embeddingsh_position_embeddingsw_position_embeddingsTr&   )tf
name_scope
add_weightr/   
vocab_sizer0   r   r3   rB   type_vocab_sizerE   r1   rG   r2   rH   rI   rJ   rK   builtgetattrr&   r)   buildr;   input_shapes     r>   rS   zTFLayoutLMEmbeddings.buildG   s    ]],- 	//{{--t/?/?@+D,B,BC * DK	 ]]23 	)-!{{22D4D4DE+D,B,BC *9 *D&	 ]]01 	'+!33T5E5EF+D,B,BC (7 (D$	 ]]23 	)-!668H8HI+D,B,BC *9 *D&	 ]]23 	)-!668H8HI+D,B,BC *9 *D&	 ]]23 	)-!668H8HI+D,B,BC *9 *D&	 ]]23 	)-!668H8HI+D,B,BC *9 *D&	 ::
4d+7t~~223 L$$dD$++2I2I%JKL L 8i	 		 		 		 		 		 		 	L Lsf   AL< AM	*AM
AM#*AM0
AM=*AN
?3N<M	MM #M-0M:=N
NNc                R   ||J |At        || j                  j                         t        j                  | j
                  |      }t        |      dd }|t        j                  |d      }|/t        j                  t        j                  d|d         d      }|/t        j                  t        j                  d|d         d      }|t        j                  |dgz   d	      x}}	 t        j                  | j                  |dddddf         }t        j                  | j                  |ddddd
f         }	t        j                  | j                  |dddddf         }
t        j                  | j                  |dddddf         }t        j                  | j                  |dddddf   |ddddd
f   z
        }t        j                  | j                  |dddddf   |dddddf   z
        }t        j                  | j                  |      }t        j                  | j                   |      }||z   |z   |z   |	z   |
z   |z   |z   |z   }| j#                  |      }| j%                  ||      }|S # t        $ r}t        d      |d}~ww xY w)z
        Applies embedding based on inputs tensor.

        Returns:
            final_embeddings (`tf.Tensor`): output embedding tensor.
        N)paramsindicesr   dimsvalue)startlimitaxis   )r\   r!      r   z:The `bbox`coordinate values should be within 0-1000 range.inputsrd   training)r   r/   rO   rL   gatherrB   r   fillexpand_dimsrangerH   rI   
IndexErrorrJ   rK   rG   rE   r&   r9   )r;   	input_idsbboxposition_idstoken_type_idsinputs_embedsrf   rU   left_position_embeddingsupper_position_embeddingsright_position_embeddingslower_position_embeddingserJ   rK   position_embedstoken_type_embedsfinal_embeddingss                     r>   callzTFLayoutLMEmbeddings.call   s    %-*?@@ *9dkk6L6LMIIT[[)LM /4!WW+Q?N>>"((+b/*RYZ[L>>"((+b/*RYZ[L<''+"31==D4	b')yy1K1KTRSUVXYRY]'[$(*		$2L2LdSTVWYZSZm(\%(*		$2L2LdSTVWYZSZm(\%(*		$2L2LdSTVWYZSZm(\% !#		$*D*Dd1aQR7mVZ[\^_ab[bVcFc d "		$*D*Dd1aQR7mVZ[\^_ab[bVcFc d))4+C+C\ZIIT-G-GQ_`  '' (	(
 (( (( $$ $$ 	  >>1A>B<</?(<S+  	bYZ`aa	bs   3B(J 	J&J!!J&r/   r"   N)NNNNNF)rl   	tf.Tensorrm   r|   rn   r|   ro   r|   rp   r|   rf   boolreturnr|   )__name__
__module____qualname____doc__r.   rS   ry   __classcell__r=   s   @r>   r$   r$   9   sp    Q	M7Lv  $"&$(#'< <  <   	< 
 "<  !<  <  
< r?   r$   c                  ^     e Zd Zd fdZddZ	 d	 	 	 	 	 	 	 	 	 	 	 	 	 	 	 	 	 ddZd	dZ xZS )
TFLayoutLMSelfAttentionc                   t        |   d
i | |j                  |j                  z  dk7  r&t	        d|j                   d|j                   d      |j                  | _        t        |j                  |j                  z        | _        | j                  | j                  z  | _        t        j                  | j                        | _
        t        j                  j                  | j                  t        |j                        d      | _        t        j                  j                  | j                  t        |j                        d      | _        t        j                  j                  | j                  t        |j                        d      | _        t        j                  j'                  |j(                  	      | _        |j,                  | _        || _        y )Nr   zThe hidden size (z6) is not a multiple of the number of attention heads ()queryunitskernel_initializerr)   keyr\   r*   r,   )r-   r.   r0   num_attention_heads
ValueErrorintattention_head_sizeall_head_sizemathsqrtsqrt_att_head_sizer   r4   Denser   r3   r   r   r\   r7   attention_probs_dropout_probr9   
is_decoderr/   r:   s      r>   r.   z TFLayoutLMSelfAttention.__init__   s   "6" : ::a?#F$6$6#7 8''-'A'A&B!E 
 $*#=#= #&v'9'9F<V<V'V#W !558P8PP"&))D,D,D"E\\''$$IaIa9bip ( 

 <<%%$$IaIa9bin & 
 \\''$$IaIa9bip ( 

 ||++1T1T+U ++r?   c                    t        j                  ||d| j                  | j                  f      }t        j                  |g d      S )NrY   tensorrC   r   rb   r!   r   perm)rL   reshaper   r   	transpose)r;   r   
batch_sizes      r>   transpose_for_scoresz,TFLayoutLMSelfAttention.transpose_for_scores   s;    6*b$BZBZ\`\t\t1uv ||F66r?   c	                   t        |      d   }	| j                  |      }
|d u}|r||d   }|d   }|}n|rG| j                  | j                  |      |	      }| j                  | j	                  |      |	      }|}n|}| j                  | j                  |      |	      }| j                  | j	                  |      |	      }t        j                  |d   |gd      }t        j                  |d   |gd      }nD| j                  | j                  |      |	      }| j                  | j	                  |      |	      }| j                  |
|	      }| j                  r||f}t        j                  ||d      }t        j                  | j                  |j                        }t        j                  ||      }|t        j                  ||      }t        |d	
      }| j                  ||      }|t        j                   ||      }t        j                  ||      }t        j"                  |g d      }t        j$                  ||	d	| j&                  f      }|r||fn|f}| j                  r||fz   }|S )Nr   rc   r!   rb   r_   T)transpose_bdtyperY   )logitsr`   re   r   r   r   )r   r   r   r   r\   rL   concatr   matmulcastr   r   divideaddr   r9   multiplyr   r   r   )r;   hidden_statesattention_mask	head_maskencoder_hidden_statesencoder_attention_maskpast_key_valueoutput_attentionsrf   r   mixed_query_layeris_cross_attention	key_layervalue_layerquery_layerattention_scoresdkattention_probsattention_outputoutputss                       r>   ry   zTFLayoutLMSelfAttention.call   sy     .q1
 JJmJ<
 3$>."<&q)I(+K3N11$((BW(2XZdeI33DJJF[J4\^hiK3N'11$((-(2PR\]I33DJJmJ4TV`aK		>!#4i"@qII))^A%6$D1MK11$((-(2PR\]I33DJJmJ4TV`aK//0A:N?? (5N 99[)NWWT,,4D4J4JK99%5r:%!vv&6G )0@rJ ,,o,Q   kk/9EO99_kB<<(8|L ::-=jRTVZVhVhEij9J#_5QaPc?? 11G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   rL   rM   r   r)   rS   r/   r0   r   r\   rT   s     r>   rS   zTFLayoutLMSelfAttention.build5  s9   ::
4$'3tzz/ H

  $dkk.E.E!FGH4%1txx}}- FdDKK,C,CDEF4$'3tzz/ H

  $dkk.E.E!FGH H 4H HF FH Hs$   3E*<3E6-3F*E36E?Frz   )r   r|   r   r   r~   r|   F)r   r|   r   r|   r   r|   r   r|   r   r|   r   Tuple[tf.Tensor]r   r}   rf   r}   r~   r   r{   )r   r   r   r.   r   ry   rS   r   r   s   @r>   r   r      s    87  O O "O 	O
  )O !*O )O  O O 
ObHr?   r   c                  2     e Zd Zd fdZdddZddZ xZS )TFLayoutLMSelfOutputc                x   t        |   di | t        j                  j	                  |j
                  t        |j                        d      | _        t        j                  j                  |j                  d      | _        t        j                  j                  |j                        | _        || _        y Ndenser   r&   r'   r*   r,   r-   r.   r   r4   r   r0   r   r3   r   r5   r6   r&   r7   r8   r9   r/   r:   s      r>   r.   zTFLayoutLMSelfOutput.__init__F      "6"\\''$$IaIa9bip ( 

 88AVAV]h8i||++1K1K+Lr?   c                z    | j                  |      }| j                  ||      }| j                  ||z         }|S Nrc   re   r   r9   r&   r;   r   input_tensorrf   s       r>   ry   zTFLayoutLMSelfOutput.callP  ?    

-
8MHMml.JK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       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NTr   r&   
rQ   rR   rL   rM   r   r)   rS   r/   r0   r&   rT   s     r>   rS   zTFLayoutLMSelfOutput.buildW      ::
4$'3tzz/ H

  $dkk.E.E!FGH4d+7t~~223 L$$dD$++2I2I%JKL L 8H HL L   3C9<3D9DDrz   r   r   r|   r   r|   rf   r}   r~   r|   r{   r   r   r   r.   ry   rS   r   r   s   @r>   r   r   E      	Lr?   r   c                  \     e Zd Zd fdZd Z	 d	 	 	 	 	 	 	 	 	 	 	 	 	 	 	 	 	 ddZddZ xZS )	TFLayoutLMAttentionc                l    t        |   di | t        |d      | _        t	        |d      | _        y )Nr;   r)   outputr,   )r-   r.   r   self_attentionr   dense_outputr:   s      r>   r.   zTFLayoutLMAttention.__init__e  s1    "6"5f6J0hGr?   c                    t         r{   NotImplementedError)r;   headss     r>   prune_headszTFLayoutLMAttention.prune_headsk  s    !!r?   c	           
     x    | j                  ||||||||      }	| j                  |	d   ||      }
|
f|	dd  z   }|S )Nr   r   r   r   r   r   r   rf   r   r   r   rf   r!   )r   r   )r;   r   r   r   r   r   r   r   rf   self_outputsr   r   s               r>   ry   zTFLayoutLMAttention.calln  so     **&)"7#9)/ + 	
  ,,&q/x - 
 $%QR(88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   rL   rM   r   r)   rS   r   rT   s     r>   rS   zTFLayoutLMAttention.build  s    ::
4)40<t22778 0##))$/04.:t00556 .!!''-. . ;0 0. .   C%CCC rz   r   )r   r|   r   r|   r   r|   r   r|   r   r|   r   r   r   r}   rf   r}   r~   r   r{   )r   r   r   r.   r   ry   rS   r   r   s   @r>   r   r   d  su    H"  " 	
  ) !* )    
:	.r?   r   c                  0     e Zd Zd fdZddZddZ xZS )TFLayoutLMIntermediatec                T   t        |   di | t        j                  j	                  |j
                  t        |j                        d      | _        t        |j                  t              r"t        |j                        | _        || _        y |j                  | _        || _        y )Nr   r   r,   )r-   r.   r   r4   r   intermediate_sizer   r3   r   
isinstance
hidden_actstrr	   intermediate_act_fnr/   r:   s      r>   r.   zTFLayoutLMIntermediate.__init__  s    "6"\\''**vOgOg?hov ( 

 f''-'89J9J'KD$  (.'8'8D$r?   c                L    | j                  |      }| j                  |      }|S Nrc   )r   r   r;   r   s     r>   ry   zTFLayoutLMIntermediate.call  s(    

-
800?r?   c                (   | 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NTr   	rQ   rR   rL   rM   r   r)   rS   r/   r0   rT   s     r>   rS   zTFLayoutLMIntermediate.build  }    ::
4$'3tzz/ H

  $dkk.E.E!FGH H 4H H   3BBrz   r   r|   r~   r|   r{   r   r   s   @r>   r   r     s    Hr?   r   c                  2     e Zd Zd fdZdddZddZ xZS )TFLayoutLMOutputc                x   t        |   di | t        j                  j	                  |j
                  t        |j                        d      | _        t        j                  j                  |j                  d      | _        t        j                  j                  |j                        | _        || _        y r   r   r:   s      r>   r.   zTFLayoutLMOutput.__init__  r   r?   c                z    | j                  |      }| j                  ||      }| j                  ||z         }|S r   r   r   s       r>   ry   zTFLayoutLMOutput.call  r   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       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r   )rQ   rR   rL   rM   r   r)   rS   r/   r   r&   r0   rT   s     r>   rS   zTFLayoutLMOutput.build  s    ::
4$'3tzz/ N

  $dkk.K.K!LMN4d+7t~~223 L$$dD$++2I2I%JKL L 8N NL Lr   rz   r   r   r{   r   r   s   @r>   r   r     r   r?   r   c                  V     e Zd Zd fdZ	 d	 	 	 	 	 	 	 	 	 	 	 	 	 	 	 	 	 ddZddZ xZS )TFLayoutLMLayerc                D   t        |   di | t        |d      | _        |j                  | _        |j
                  | _        | j
                  r,| j                  st        |  d      t        |d      | _        t        |d      | _	        t        |d      | _        y )N	attentionr   z> should be used as a decoder model if cross attention is addedcrossattentionintermediater   r,   )r-   r.   r   r  r   add_cross_attentionr   r  r   r  r   bert_outputr:   s      r>   r.   zTFLayoutLMLayer.__init__  s    "6",V+F ++#)#=#= ##?? D6)g!hii"5fCS"TD26O+FBr?   c	           
        ||d d nd }	| j                  |||d d |	||      }
|
d   }| j                  r|
dd }|
d   }n|
dd  }d }| j                  rV|Tt        | d      st        d|  d      ||d	d  nd }| j	                  ||||||||      }|d   }||dd z   }|d   }|z   }| j                  |
      }| j                  |||      }|f|z   }| j                  r|fz   }|S )Nrb   )r   r   r   r   r   r   r   rf   r   r!   rY   r  z'If `encoder_hidden_states` are passed, z` has to be instantiated with cross-attention layers by setting `config.add_cross_attention=True`r   r   )r  r   hasattrr   r  r  r  )r;   r   r   r   r   r   r   r   rf   self_attn_past_key_valueself_attention_outputsr   r   present_key_valuecross_attn_present_key_valuecross_attn_past_key_valuecross_attention_outputsintermediate_outputlayer_outputs                      r>   ry   zTFLayoutLMLayer.call  s    :H9S>"1#5Y] !%&)"&#'3/ "0 	"
 2!4 ??,Qr2G 6r :,QR0G'+$??4@4!12 =dV DD D  @N?Yrs(;_c%&*&9&9--#&;'=8"3! ': 	'#  7q9 7" ==G ,C2+F( 14P P"//>N/O''-<LW_ ( 
  /G+ ??!2 44G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       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   xY w# 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  r  )
rQ   rR   rL   rM   r  r)   rS   r  r  r  rT   s     r>   rS   zTFLayoutLMLayer.build*  sZ   ::
4d+7t~~223 +$$T*+4.:t00556 .!!''-.4-9t//445 -  &&t,-4)40<t22778 0##))$/0 0 =+ +. .- -0 0s0   E?%F?FF$?F	FF!$F-rz   r   )r   r|   r   r|   r   r|   r   tf.Tensor | Noner   r  r   zTuple[tf.Tensor] | Noner   r}   rf   r}   r~   r   r{   r   r   s   @r>   r   r     s{    C, E E "E 	E
  0E !1E 0E  E E 
EN0r?   r   c                  b     e Zd Zd fdZ	 d	 	 	 	 	 	 	 	 	 	 	 	 	 	 	 	 	 	 	 	 	 	 	 ddZddZ xZS )TFLayoutLMEncoderc                    t        |   di | || _        t        |j                        D cg c]  }t        |d|        c}| _        y c c}w )Nzlayer_._r   r,   )r-   r.   r/   rj   num_hidden_layersr   layer)r;   r/   r<   ir=   s       r>   r.   zTFLayoutLMEncoder.__init__>  sH    "6"LQRXRjRjLklqofXaS>Bl
ls   Ac                   |	rdnd }|rdnd }|r| j                   j                  rdnd }|rdnd }t        | j                        D ]h  \  }}|	r||fz   }|||   nd } |||||   |||||      }|d   }|r	||d   fz  }|s=||d   fz   }| j                   j                  s]|`||d   fz   }j |	r||fz   }|
st	        d ||||fD              S t        |||||      S )	Nr,   r   r   rY   r!   rb   c              3  &   K   | ]	  }||  y wr{   r,   ).0vs     r>   	<genexpr>z)TFLayoutLMEncoder.call.<locals>.<genexpr>u  s      ghgts   )last_hidden_statepast_key_valuesr   
attentionscross_attentions)r/   r  	enumerater  tupler
   )r;   r   r   r   r   r   r!  	use_cacher   output_hidden_statesreturn_dictrf   all_hidden_statesall_attentionsall_cross_attentionsnext_decoder_cacher  layer_moduler   layer_outputss                       r>   ry   zTFLayoutLMEncoder.callC  sV    #7BD0d%64;;;Z;Zr`d#,R$(4 	VOA|#$58H$H!3B3N_Q/TXN(+-#A,&;'=-"3!	M *!,M"}R'8&::" !/=3C2E!E;;227L7X+?=QRCSBU+U(1	V6   1]4D D )+<nNbc   ;+.+%1
 	
r?   c                    | j                   ry d| _         t        | dd       K| j                  D ];  }t        j                  |j
                        5  |j                  d        d d d        = y y # 1 sw Y   IxY w)NTr  )rQ   rR   r  rL   rM   r)   rS   )r;   rU   r  s      r>   rS   zTFLayoutLMEncoder.build  sp    ::
4$'3 &]]5::. &KK%& && 4& &s   A..A7	rz   r   )r   r|   r   r|   r   r|   r   r  r   r  r!  zTuple[Tuple[tf.Tensor]] | Noner&  Optional[bool]r   r}   r'  r}   r(  r}   rf   r}   r~   zDUnion[TFBaseModelOutputWithPastAndCrossAttentions, Tuple[tf.Tensor]]r{   r   r   s   @r>   r  r  =  s    m" <
 <
 "<
 	<

  0<
 !1<
 8<
 "<
  <
 #<
 <
 <
 
N<
|&r?   r  c                  0     e Zd Zd fdZddZddZ xZS )TFLayoutLMPoolerc                    t        |   di | t        j                  j	                  |j
                  t        |j                        dd      | _        || _	        y )Ntanhr   )r   r   
activationr)   r,   )
r-   r.   r   r4   r   r0   r   r3   r   r/   r:   s      r>   r.   zTFLayoutLMPooler.__init__  sT    "6"\\''$$.v/G/GH	 ( 

 r?   c                <    |d d df   }| j                  |      }|S )Nr   rc   )r   )r;   r   first_token_tensorpooled_outputs       r>   ry   zTFLayoutLMPooler.call  s*     +1a40

*<
=r?   c                (   | 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r   r   rT   s     r>   rS   zTFLayoutLMPooler.build  r   r   rz   r   r{   r   r   s   @r>   r2  r2    s    	Hr?   r2  c                  0     e Zd Zd fdZddZddZ xZS )!TFLayoutLMPredictionHeadTransformc                   t        |   di | t        j                  j	                  |j
                  t        |j                        d      | _        t        |j                  t              rt        |j                        | _        n|j                  | _        t        j                  j                  |j                  d      | _        || _        y )Nr   r   r&   r'   r,   )r-   r.   r   r4   r   r0   r   r3   r   r   r   r   r	   transform_act_fnr5   r6   r&   r/   r:   s      r>   r.   z*TFLayoutLMPredictionHeadTransform.__init__  s    "6"\\''$$.v/G/GH ( 

 f''-$5f6G6G$HD!$*$5$5D!88AVAV]h8ir?   c                p    | j                  |      }| j                  |      }| j                  |      }|S r   )r   r=  r&   r   s     r>   ry   z&TFLayoutLMPredictionHeadTransform.call  s8    

-
8--m<m<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       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r   r   rT   s     r>   rS   z'TFLayoutLMPredictionHeadTransform.build  r   r   rz   r   r{   r   r   s   @r>   r;  r;    s    "	Lr?   r;  c                  P     e Zd Zd fdZd	dZd
dZddZddZddZddZ	 xZ
S )TFLayoutLMLMPredictionHeadc                    t        |   di | || _        |j                  | _        t	        |d      | _        || _        y )N	transformr   r,   )r-   r.   r/   r0   r;  rC  input_embeddingsr;   r/   rD  r<   r=   s       r>   r.   z#TFLayoutLMLMPredictionHead.__init__  s@    "6"!--:6T !1r?   c                X   | j                  | j                  j                  fddd      | _        | 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)NzerosTbias)rC   rD   	trainabler)   rC  )rN   r/   rO   rH  rQ   rR   rL   rM   rC  r)   rS   rT   s     r>   rS   z TFLayoutLMLMPredictionHead.build  s    OO4;;+A+A*CQXdhouOv	::
4d+7t~~223 +$$T*+ + 8+ +s   :B  B)c                    | j                   S r{   )rD  r;   s    r>   get_output_embeddingsz0TFLayoutLMLMPredictionHead.get_output_embeddings  s    $$$r?   c                `    || j                   _        t        |      d   | j                   _        y Nr   )rD  rB   r   rO   r;   r\   s     r>   set_output_embeddingsz0TFLayoutLMLMPredictionHead.set_output_embeddings  s(    ',$+5e+<Q+?(r?   c                    d| j                   iS )NrH  )rH  rK  s    r>   get_biasz#TFLayoutLMLMPredictionHead.get_bias  s    		""r?   c                X    |d   | _         t        |d         d   | j                  _        y )NrH  r   )rH  r   r/   rO   rO  s     r>   set_biasz#TFLayoutLMLMPredictionHead.set_bias  s'    &M	!+E&M!:1!=r?   c                   | j                  |      }t        |      d   }t        j                  |d| j                  g      }t        j
                  || j                  j                  d      }t        j                  |d|| j                  j                  g      }t        j                  j                  || j                        }|S )Nr	  r!   rY   r   T)abr   )r\   rH  )rC  r   rL   r   r0   r   rD  rB   r/   rO   nnbias_addrH  )r;   r   
seq_lengths      r>   ry   zTFLayoutLMLMPredictionHead.call  s    ]C.q1


-DDTDT?UV		MT5J5J5Q5Q_cd

-JPTP[P[PfPf?gh]Kr?   r/   r"   rD  keras.layers.Layerr{   r~   r\  r\   ztf.Variable)r~   zDict[str, tf.Variable]r   )r   r   r   r.   rS   rL  rP  rR  rT  ry   r   r   s   @r>   rA  rA    s'    
1+%@#>r?   rA  c                  0     e Zd Zd fdZddZddZ xZS )TFLayoutLMMLMHeadc                J    t        |   di | t        ||d      | _        y )Npredictionsr   r,   )r-   r.   rA  rb  rE  s       r>   r.   zTFLayoutLMMLMHead.__init__  s&    "6"5f>NUbcr?   c                *    | j                  |      }|S )Nr	  )rb  )r;   sequence_outputprediction_scoress      r>   ry   zTFLayoutLMMLMHead.call  s     ,,?,K  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)NTrb  )rQ   rR   rL   rM   rb  r)   rS   rT   s     r>   rS   zTFLayoutLMMLMHead.build  sm    ::
4-9t//445 -  &&t,- - :- -   A11A:r[  )rd  r|   r~   r|   r{   r   r   s   @r>   r`  r`    s    d
!
-r?   r`  c                       e Zd ZeZdd fdZd	dZd
dZd Ze		 	 	 	 	 	 	 	 	 	 	 	 	 d	 	 	 	 	 	 	 	 	 	 	 	 	 	 	 	 	 	 	 	 	 	 	 	 	 	 	 dd       Z
ddZ xZS )TFLayoutLMMainLayerc                    t        |   di | || _        t        |d      | _        t        |d      | _        |rt        |d      | _        y d | _        y )NrF   r   encoderpoolerr,   )	r-   r.   r/   r$   rF   r  rk  r2  rl  )r;   r/   add_pooling_layerr<   r=   s       r>   r.   zTFLayoutLMMainLayer.__init__  sN    "6".vLI(i@AR&vH=X\r?   c                    | j                   S r{   )rF   rK  s    r>   get_input_embeddingsz(TFLayoutLMMainLayer.get_input_embeddings"  s    r?   c                `    || j                   _        t        |      d   | j                   _        y rN  )rF   rB   r   rO   rO  s     r>   set_input_embeddingsz(TFLayoutLMMainLayer.set_input_embeddings%  s$    !&%/%6q%9"r?   c                    t         )z
        Prunes heads of the model. heads_to_prune: dict of {layer_num: list of heads to prune in this layer} See base
        class PreTrainedModel
        r   )r;   heads_to_prunes     r>   _prune_headsz TFLayoutLMMainLayer._prune_heads)  s
    
 "!r?   c                   ||t        d      |t        |      }n|t        |      d d }nt        d      |t        j                  |d      }|t        j                  |d      }|t        j                  |dgz   d      }| j	                  ||||||      }t        j
                  ||d   dd|d   f      }t        j                  ||j                  	      }t        j                  d
|j                  	      }t        j                  d|j                  	      }t        j                  t        j                  ||      |      }|t        d g| j                  j                  z  }| j                  ||||d d d|
|||      }|d   }| j                  | j                  |      nd }|s
||f|dd  z   S t!        |||j"                  |j$                  |j&                        S )NzDYou cannot specify both input_ids and inputs_embeds at the same timerY   z5You have to specify either input_ids or inputs_embedsr!   rZ   r   ra   )rl   rm   rn   ro   rp   rf   r   g      ?g     F)r   r   r   r   r   r!  r&  r   r'  r(  rf   r	  )r   pooler_outputr   r"  r#  )r   r   rL   rh   rF   r   r   r   constantr   subtractr   r/   r  rk  rl  r   r   r"  r#  )r;   rl   rm   r   ro   rn   r   rp   r   r   r   r'  r(  rf   rU   embedding_outputextended_attention_maskone_cstten_thousand_cstencoder_outputsrd  r8  s                         r>   ry   zTFLayoutLMMainLayer.call0  s    "  ]%>cdd"$Y/K&$]3CR8KTUU!WW+Q?N!WW+Q?N<77qc 1;D??%)' + 
 #%**^k!naQRT_`aTb=c"d #%''*AIYI_I_"`++c)9)?)?@;;x7G7M7MN"$++bkk'CZ.[]m"n  %%!>!>>I,,*2"7#' /!5# ' 
 *!,FJkkF]/Bcg  #$ $
 >-')77&11,==
 	
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       Nt        j                  | j                  j
                        5  | j                  j                  d        d d d        y y # 1 sw Y   xY w# 1 sw Y   qxY w# 1 sw Y   y xY w)NTrF   rk  rl  )	rQ   rR   rL   rM   rF   r)   rS   rk  rl  rT   s     r>   rS   zTFLayoutLMMainLayer.build  s   ::
4t,8t334 ,%%d+,4D)5t||001 )""4()44(4t{{//0 (!!$'( ( 5, ,) )( (s$   D%%D1?D=%D.1D:=E)T)r/   r"   rm  r}   r]  r^  NNNNNNNNNNNNF)rl   TFModelInputType | Nonerm   np.ndarray | tf.Tensor | Noner   r  ro   r  rn   r  r   r  rp   r  r   r  r   r  r   r0  r'  r0  r(  r0  rf   r}   r~   GUnion[TFBaseModelOutputWithPoolingAndCrossAttentions, Tuple[tf.Tensor]]r{   )r   r   r   r"   config_classr.   ro  rq  rt  r   ry   rS   r   r   s   @r>   ri  ri    s    !L]:"  .2.28<8<6:377;?C@D,0/3&*c
*c
 ,c
 6	c

 6c
 4c
 1c
 5c
  =c
 !>c
 *c
 -c
 $c
 c
 
Qc
 c
J(r?   ri  c                  4     e Zd ZdZeZdZe fd       Z xZ	S )TFLayoutLMPreTrainedModelz
    An abstract class to handle weights initialization and a simple interface for downloading and loading pretrained
    models.
    layoutlmc                n    t         |   }t        j                  dt        j                  d      |d<   |S )N)NNra   rm   )rC   r   r)   )r-   input_signaturerL   
TensorSpecint32)r;   	signaturer=   s     r>   r  z)TFLayoutLMPreTrainedModel.input_signature  s/    G+	MMrxxV\]	&r?   )
r   r   r   r   r"   r  base_model_prefixpropertyr  r   r   s   @r>   r  r    s'    
 "L" r?   r  az	  

    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>

    Args:
        config ([`LayoutLMConfig`]): 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 [`~TFPreTrainedModel.from_pretrained`] method to load the model weights.
a  
    Args:
        input_ids (`Numpy array` or `tf.Tensor` of shape `({0})`):
            Indices of input sequence tokens in the vocabulary.

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

            [What are input IDs?](../glossary#input-ids)
        bbox (`Numpy array` or `tf.Tensor` of shape `({0}, 4)`, *optional*):
            Bounding Boxes of each input sequence tokens. Selected in the range `[0, config.max_2d_position_embeddings-
            1]`.
        attention_mask (`Numpy array` or `tf.Tensor` of shape `({0})`, *optional*):
            Mask to avoid performing attention on padding token indices. Mask values selected in `[0, 1]`:

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

            [What are attention masks?](../glossary#attention-mask)
        token_type_ids (`Numpy array` or `tf.Tensor` of shape `({0})`, *optional*):
            Segment token indices to indicate first and second portions of the inputs. Indices are selected in `[0,
            1]`:

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

            [What are token type IDs?](../glossary#token-type-ids)
        position_ids (`Numpy array` or `tf.Tensor` of shape `({0})`, *optional*):
            Indices of positions of each input sequence tokens in the position embeddings. Selected in the range `[0,
            config.max_position_embeddings - 1]`.

            [What are position IDs?](../glossary#position-ids)
        head_mask (`Numpy array` or `tf.Tensor` 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 (`tf.Tensor` 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.
        training (`bool`, *optional*, defaults to `False`):
            Whether or not to use the model in training mode (some modules like dropout modules have different
            behaviors between training and evaluation).
zbThe bare LayoutLM Model transformer outputting raw hidden-states without any specific head on top.c                       e Zd Zd fdZe eej                  d             ee	e
      	 	 	 	 	 	 	 	 	 	 	 	 	 d	 	 	 	 	 	 	 	 	 	 	 	 	 	 	 	 	 	 	 	 	 	 	 	 	 	 	 dd                     Zd	dZ xZS )
TFLayoutLMModelc                P    t        |   |g|i | t        |d      | _        y )Nr  r   )r-   r.   ri  r  r;   r/   rd   r<   r=   s       r>   r.   zTFLayoutLMModel.__init__  s(    3&3F3+FDr?   batch_size, sequence_lengthoutput_typer  c                >    | j                  ||||||||
|||      }|S )a   
        Returns:

        Examples:

        ```python
        >>> from transformers import AutoTokenizer, TFLayoutLMModel
        >>> import tensorflow as tf

        >>> tokenizer = AutoTokenizer.from_pretrained("microsoft/layoutlm-base-uncased")
        >>> model = TFLayoutLMModel.from_pretrained("microsoft/layoutlm-base-uncased")

        >>> words = ["Hello", "world"]
        >>> normalized_word_boxes = [637, 773, 693, 782], [698, 773, 733, 782]

        >>> token_boxes = []
        >>> for word, box in zip(words, normalized_word_boxes):
        ...     word_tokens = tokenizer.tokenize(word)
        ...     token_boxes.extend([box] * len(word_tokens))
        >>> # add bounding boxes of cls + sep tokens
        >>> token_boxes = [[0, 0, 0, 0]] + token_boxes + [[1000, 1000, 1000, 1000]]

        >>> encoding = tokenizer(" ".join(words), return_tensors="tf")
        >>> input_ids = encoding["input_ids"]
        >>> attention_mask = encoding["attention_mask"]
        >>> token_type_ids = encoding["token_type_ids"]
        >>> bbox = tf.convert_to_tensor([token_boxes])

        >>> outputs = model(
        ...     input_ids=input_ids, bbox=bbox, attention_mask=attention_mask, token_type_ids=token_type_ids
        ... )

        >>> last_hidden_states = outputs.last_hidden_state
        ```rl   rm   r   ro   rn   r   rp   r   r'  r(  rf   )r  )r;   rl   rm   r   ro   rn   r   rp   r   r   r   r'  r(  rf   r   s                  r>   ry   zTFLayoutLMModel.call!  s@    n --))%'/!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)NTr  )rQ   rR   rL   rM   r  r)   rS   rT   s     r>   rS   zTFLayoutLMModel.buildh  si    ::
4T*6t}}112 *##D)* * 7* *rg  rz   r  )rl   r  rm   r  r   r  ro   r  rn   r  r   r  rp   r  r   r  r   r  r   r0  r'  r0  r(  r0  rf   r0  r~   r  r{   )r   r   r   r.   r   r   LAYOUTLM_INPUTS_DOCSTRINGformatr    r   _CONFIG_FOR_DOCry   rS   r   r   s   @r>   r  r    s   
E
 *+D+K+KLi+jkBQ`
 .2.28<8<6:377;?C@D,0/3&*#(@*@ ,@ 6	@
 6@ 4@ 1@ 5@  =@ !>@ *@ -@ $@ !@ 
Q@ l 
@D*r?   r  z6LayoutLM Model with a `language modeling` head on top.c                       e Zd Zg dZd	 fdZd
dZddZe ee	j                  d             eee      	 	 	 	 	 	 	 	 	 	 	 	 d	 	 	 	 	 	 	 	 	 	 	 	 	 	 	 	 	 	 	 	 	 	 	 	 	 dd                     ZddZ xZS )TFLayoutLMForMaskedLM)rl  cls.seq_relationshipzcls.predictions.decoder.weight	nsp___clsc                    t        |   |g|i | |j                  rt        j	                  d       t        |dd      | _        t        || j                  j                  d      | _	        y )NzqIf you want to use `TFLayoutLMForMaskedLM` make sure `config.is_decoder=False` for bi-directional self-attention.Tr  rm  r)   	mlm___cls)rD  r)   )
r-   r.   r   loggerwarningri  r  r`  rF   mlmr  s       r>   r.   zTFLayoutLMForMaskedLM.__init__{  sb    3&3F3NN1
 ,FdQ[\$Vdmm>V>V]hir?   c                .    | j                   j                  S r{   )r  rb  rK  s    r>   get_lm_headz!TFLayoutLMForMaskedLM.get_lm_head  s    xx###r?   c                    t        j                  dt               | j                  dz   | j                  j                  z   dz   | j                  j
                  j                  z   S )NzMThe method get_prefix_bias_name is deprecated. Please use `get_bias` instead./)warningswarnFutureWarningr)   r  rb  rK  s    r>   get_prefix_bias_namez*TFLayoutLMForMaskedLM.get_prefix_bias_name  sG    egtuyy3.4txx7K7K7P7PPPr?   r  r  c                   | j                  |||||||||	|
|      }|d   }| j                  ||      }|dn| j                  ||      }|
s|f|dd z   }||f|z   S |S t        |||j                  |j
                        S )aV  
        labels (`tf.Tensor` or `np.ndarray` of shape `(batch_size, sequence_length)`, *optional*):
            Labels for computing the masked language modeling loss. Indices should be in `[-100, 0, ...,
            config.vocab_size]` (see `input_ids` docstring) Tokens with indices set to `-100` are ignored (masked), the
            loss is only computed for the tokens with labels in `[0, ..., config.vocab_size]`

        Returns:

        Examples:

        ```python
        >>> from transformers import AutoTokenizer, TFLayoutLMForMaskedLM
        >>> import tensorflow as tf

        >>> tokenizer = AutoTokenizer.from_pretrained("microsoft/layoutlm-base-uncased")
        >>> model = TFLayoutLMForMaskedLM.from_pretrained("microsoft/layoutlm-base-uncased")

        >>> words = ["Hello", "[MASK]"]
        >>> normalized_word_boxes = [637, 773, 693, 782], [698, 773, 733, 782]

        >>> token_boxes = []
        >>> for word, box in zip(words, normalized_word_boxes):
        ...     word_tokens = tokenizer.tokenize(word)
        ...     token_boxes.extend([box] * len(word_tokens))
        >>> # add bounding boxes of cls + sep tokens
        >>> token_boxes = [[0, 0, 0, 0]] + token_boxes + [[1000, 1000, 1000, 1000]]

        >>> encoding = tokenizer(" ".join(words), return_tensors="tf")
        >>> input_ids = encoding["input_ids"]
        >>> attention_mask = encoding["attention_mask"]
        >>> token_type_ids = encoding["token_type_ids"]
        >>> bbox = tf.convert_to_tensor([token_boxes])

        >>> labels = tokenizer("Hello world", return_tensors="tf")["input_ids"]

        >>> outputs = model(
        ...     input_ids=input_ids,
        ...     bbox=bbox,
        ...     attention_mask=attention_mask,
        ...     token_type_ids=token_type_ids,
        ...     labels=labels,
        ... )

        >>> loss = outputs.loss
        ```r  r   )rd  rf   Nlabelsr   rb   lossr   r   r"  )r  r  hf_compute_lossr   r   r"  )r;   rl   rm   r   ro   rn   r   rp   r   r'  r(  r  rf   r   rd  re  r  r   s                     r>   ry   zTFLayoutLMForMaskedLM.call  s    ~ --))%'/!5#   
 "!* HH_xHX~t4+?+?vVg+?+h')GABK7F)-)9TGf$EvE$!//))	
 	
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   rL   rM   r  r)   rS   r  rT   s     r>   rS   zTFLayoutLMForMaskedLM.build  s    ::
4T*6t}}112 *##D)*4%1txx}}- %t$% % 2* *% %r   rz   r]  )r~   r   NNNNNNNNNNNF)rl   r  rm   r  r   r  ro   r  rn   r  r   r  rp   r  r   r0  r'  r0  r(  r0  r  r  rf   r0  r~   z)Union[TFMaskedLMOutput, Tuple[tf.Tensor]]r{   )r   r   r   "_keys_to_ignore_on_load_unexpectedr.   r  r  r   r   r  r  r    r   r  ry   rS   r   r   s   @r>   r  r  q  s   *&
j$Q *+D+K+KLi+jk+;/Z .2.28<8<6:377;,0/3&*04#(V
*V
 ,V
 6	V

 6V
 4V
 1V
 5V
 *V
 -V
 $V
 .V
 !V
 
3V
 [ l V
p	%r?   r  z
    LayoutLM Model transformer with a sequence classification/regression head on top (a linear layer on top of the
    pooled output) e.g. for GLUE tasks.
    c                       e Zd Zg dZdgZd fdZe eej                  d             e
ee      	 	 	 	 	 	 	 	 	 	 	 	 d		 	 	 	 	 	 	 	 	 	 	 	 	 	 	 	 	 	 	 	 	 	 	 	 	 d
d                     ZddZ xZS )#TFLayoutLMForSequenceClassification)r  r  cls.predictionsr  r9   c                f   t        |   |g|i | |j                  | _        t        |d      | _        t
        j                  j                  |j                        | _	        t
        j                  j                  |j                  t        |j                        d      | _        || _        y )Nr  r   r*   
classifierr   r-   r.   
num_labelsri  r  r   r4   r7   r8   r9   r   r   r3   r  r/   r  s       r>   r.   z,TFLayoutLMForSequenceClassification.__init__  s    3&3F3 +++FD||++1K1K+L,,,,##.v/G/GH - 

 r?   r  r  c                ,   | j                  |||||||||	|
|      }|d   }| j                  ||      }| j                  |      }|dn| j                  ||      }|
s|f|dd z   }||f|z   S |S t	        |||j
                  |j                        S )	an  
        labels (`tf.Tensor` or `np.ndarray` 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).

        Returns:

        Examples:

        ```python
        >>> from transformers import AutoTokenizer, TFLayoutLMForSequenceClassification
        >>> import tensorflow as tf

        >>> tokenizer = AutoTokenizer.from_pretrained("microsoft/layoutlm-base-uncased")
        >>> model = TFLayoutLMForSequenceClassification.from_pretrained("microsoft/layoutlm-base-uncased")

        >>> words = ["Hello", "world"]
        >>> normalized_word_boxes = [637, 773, 693, 782], [698, 773, 733, 782]

        >>> token_boxes = []
        >>> for word, box in zip(words, normalized_word_boxes):
        ...     word_tokens = tokenizer.tokenize(word)
        ...     token_boxes.extend([box] * len(word_tokens))
        >>> # add bounding boxes of cls + sep tokens
        >>> token_boxes = [[0, 0, 0, 0]] + token_boxes + [[1000, 1000, 1000, 1000]]

        >>> encoding = tokenizer(" ".join(words), return_tensors="tf")
        >>> input_ids = encoding["input_ids"]
        >>> attention_mask = encoding["attention_mask"]
        >>> token_type_ids = encoding["token_type_ids"]
        >>> bbox = tf.convert_to_tensor([token_boxes])
        >>> sequence_label = tf.convert_to_tensor([1])

        >>> outputs = model(
        ...     input_ids=input_ids,
        ...     bbox=bbox,
        ...     attention_mask=attention_mask,
        ...     token_type_ids=token_type_ids,
        ...     labels=sequence_label,
        ... )

        >>> loss = outputs.loss
        >>> logits = outputs.logits
        ```r  r!   re   rc   Nr  rb   r  )r  r9   r  r  r   r   r"  )r;   rl   rm   r   ro   rn   r   rp   r   r'  r(  r  rf   r   r8  r   r  r   s                     r>   ry   z(TFLayoutLMForSequenceClassification.call  s    ~ --))%'/!5#   
  
MHM6~t4+?+?vV\+?+]Y,F)-)9TGf$EvE)!//))	
 	
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NTr  r  
rQ   rR   rL   rM   r  r)   rS   r  r/   r0   rT   s     r>   rS   z)TFLayoutLMForSequenceClassification.buildk      ::
4T*6t}}112 *##D)*4t,8t334 M%%tT4;;3J3J&KLM M 9* *M M   C"%3C."C+.C7rz   r  )rl   r  rm   r  r   r  ro   r  rn   r  r   r  rp   r  r   r0  r'  r0  r(  r0  r  r  rf   r0  r~   z3Union[TFSequenceClassifierOutput, Tuple[tf.Tensor]]r{   )r   r   r   r  _keys_to_ignore_on_load_missingr.   r   r   r  r  r    r   r  ry   rS   r   r   s   @r>   r  r    s    *s&'1l# *+D+K+KLi+jk+ETcd .2.28<8<6:377;,0/3&*04#(W
*W
 ,W
 6	W

 6W
 4W
 1W
 5W
 *W
 -W
 $W
 .W
 !W
 
=W
 e l W
r	Mr?   r  z
    LayoutLM 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g dZdgZd fdZe eej                  d             e
ee      	 	 	 	 	 	 	 	 	 	 	 	 d		 	 	 	 	 	 	 	 	 	 	 	 	 	 	 	 	 	 	 	 	 	 	 	 	 d
d                     ZddZ xZS ) TFLayoutLMForTokenClassificationrl  r  r  r  r  r9   c                h   t        |   |g|i | |j                  | _        t        |dd      | _        t
        j                  j                  |j                        | _	        t
        j                  j                  |j                  t        |j                        d      | _        || _        y )NTr  r  r*   r  r   r  r  s       r>   r.   z)TFLayoutLMForTokenClassification.__init__  s    3&3F3 +++FdQ[\||++1K1K+L,,,,##.v/G/GH - 

 r?   r  r  c                ,   | j                  |||||||||	|
|      }|d   }| j                  ||      }| j                  |      }|dn| j                  ||      }|
s|f|dd z   }||f|z   S |S t	        |||j
                  |j                        S )	a  
        labels (`tf.Tensor` or `np.ndarray` of shape `(batch_size, sequence_length)`, *optional*):
            Labels for computing the token classification loss. Indices should be in `[0, ..., config.num_labels - 1]`.

        Returns:

        Examples:

        ```python
        >>> import tensorflow as tf
        >>> from transformers import AutoTokenizer, TFLayoutLMForTokenClassification

        >>> tokenizer = AutoTokenizer.from_pretrained("microsoft/layoutlm-base-uncased")
        >>> model = TFLayoutLMForTokenClassification.from_pretrained("microsoft/layoutlm-base-uncased")

        >>> words = ["Hello", "world"]
        >>> normalized_word_boxes = [637, 773, 693, 782], [698, 773, 733, 782]

        >>> token_boxes = []
        >>> for word, box in zip(words, normalized_word_boxes):
        ...     word_tokens = tokenizer.tokenize(word)
        ...     token_boxes.extend([box] * len(word_tokens))
        >>> # add bounding boxes of cls + sep tokens
        >>> token_boxes = [[0, 0, 0, 0]] + token_boxes + [[1000, 1000, 1000, 1000]]

        >>> encoding = tokenizer(" ".join(words), return_tensors="tf")
        >>> input_ids = encoding["input_ids"]
        >>> attention_mask = encoding["attention_mask"]
        >>> token_type_ids = encoding["token_type_ids"]
        >>> bbox = tf.convert_to_tensor([token_boxes])
        >>> token_labels = tf.convert_to_tensor([1, 1, 0, 0])

        >>> outputs = model(
        ...     input_ids=input_ids,
        ...     bbox=bbox,
        ...     attention_mask=attention_mask,
        ...     token_type_ids=token_type_ids,
        ...     labels=token_labels,
        ... )

        >>> loss = outputs.loss
        >>> logits = outputs.logits
        ```r  r   re   rc   Nr  rb   r  )r  r9   r  r  r   r   r"  )r;   rl   rm   r   ro   rn   r   rp   r   r'  r(  r  rf   r   rd  r   r  r   s                     r>   ry   z%TFLayoutLMForTokenClassification.call  s    z --))%'/!5#   
 "!*,,o,Q8~t4+?+?vV\+?+]Y,F)-)9TGf$EvE&!//))	
 	
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r  r  rT   s     r>   rS   z&TFLayoutLMForTokenClassification.build  r  r  rz   r  )rl   r  rm   r  r   r  ro   r  rn   r  r   r  rp   r  r   r0  r'  r0  r(  r0  r  r  rf   r0  r~   z0Union[TFTokenClassifierOutput, Tuple[tf.Tensor]]r{   )r   r   r   r  r  r.   r   r   r  r  r    r   r  ry   rS   r   r   s   @r>   r  r  w  s   *& (2l# *+D+K+KLi+jk+BQ`a .2.28<8<6:377;,0/3&*04#(U
*U
 ,U
 6	U

 6U
 4U
 1U
 5U
 *U
 -U
 $U
 .U
 !U
 
:U
 b l U
n	Mr?   r  a  
    LayoutLM Model with a span classification head on top for extractive question-answering tasks such as
    [DocVQA](https://rrc.cvc.uab.es/?ch=17) (a linear layer on top of the final hidden-states output to compute `span
    start logits` and `span end logits`).
    c                       e Zd Zg dZd fdZe eej                  d             e	e
e      	 	 	 	 	 	 	 	 	 	 	 	 	 d	 	 	 	 	 	 	 	 	 	 	 	 	 	 	 	 	 	 	 	 	 	 	 	 	 	 	 d	d                     Zd
dZ xZS )TFLayoutLMForQuestionAnsweringr  c                
   t        |   |g|i | |j                  | _        t        |dd      | _        t
        j                  j                  |j                  t        |j                        d      | _
        || _        y )NTr  r  
qa_outputsr   )r-   r.   r  ri  r  r   r4   r   r   r3   r  r/   r  s       r>   r.   z'TFLayoutLMForQuestionAnswering.__init__  sv    3&3F3 +++FdQ[\,,,,##.v/G/GH - 

 r?   r  r  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                        S )a	  
        start_positions (`tf.Tensor` or `np.ndarray` 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` or `np.ndarray` 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.

        Returns:

        Examples:

        ```python
        >>> import tensorflow as tf
        >>> from transformers import AutoTokenizer, TFLayoutLMForQuestionAnswering
        >>> from datasets import load_dataset

        >>> tokenizer = AutoTokenizer.from_pretrained("impira/layoutlm-document-qa", add_prefix_space=True)
        >>> model = TFLayoutLMForQuestionAnswering.from_pretrained("impira/layoutlm-document-qa", revision="1e3ebac")

        >>> dataset = load_dataset("nielsr/funsd", split="train", trust_remote_code=True)
        >>> example = dataset[0]
        >>> question = "what's his name?"
        >>> words = example["words"]
        >>> boxes = example["bboxes"]

        >>> encoding = tokenizer(
        ...     question.split(), words, is_split_into_words=True, return_token_type_ids=True, return_tensors="tf"
        ... )
        >>> bbox = []
        >>> for i, s, w in zip(encoding.input_ids[0], encoding.sequence_ids(0), encoding.word_ids(0)):
        ...     if s == 1:
        ...         bbox.append(boxes[w])
        ...     elif i == tokenizer.sep_token_id:
        ...         bbox.append([1000] * 4)
        ...     else:
        ...         bbox.append([0] * 4)
        >>> encoding["bbox"] = tf.convert_to_tensor([bbox])

        >>> word_ids = encoding.word_ids(0)
        >>> outputs = model(**encoding)
        >>> loss = outputs.loss
        >>> start_scores = outputs.start_logits
        >>> end_scores = outputs.end_logits
        >>> start, end = word_ids[tf.math.argmax(start_scores, -1)[0]], word_ids[tf.math.argmax(end_scores, -1)[0]]
        >>> print(" ".join(words[start : end + 1]))
        M. Hamann P. Harper, P. Martinez
        ```r  r   rc   rb   rY   )r\   num_or_size_splitsr`   )inputr`   Nstart_positionend_positionr  )r  start_logits
end_logitsr   r"  )	r  r  rL   splitsqueezer  r   r   r"  )r;   rl   rm   r   ro   rn   r   rp   r   r'  r(  start_positionsend_positionsrf   r   rd  r   r  r  r  r  r   s                         r>   ry   z#TFLayoutLMForQuestionAnswering.call  s!   L --))%'/!5#   
 "!*8#%88&QUW#X jzz2>ZZjr:
&=+D&8F%2F>"''v|Z>X'YD"J/'!"+=F)-)9TGf$EvE-%!!//))
 	
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)NTr  r  )
rQ   rR   rL   rM   r  r)   rS   r  r/   r0   rT   s     r>   rS   z$TFLayoutLMForQuestionAnswering.build  r  r  rz   r  )rl   r  rm   r  r   r  ro   r  rn   r  r   r  rp   r  r   r0  r'  r0  r(  r0  r  r  r  r  rf   r0  r~   z7Union[TFQuestionAnsweringModelOutput, Tuple[tf.Tensor]]r{   )r   r   r   r  r.   r   r   r  r  r    r   r  ry   rS   r   r   s   @r>   r  r    s   *&
 *+D+K+KLi+jk+IXgh .2.28<8<6:377;,0/3&*9=7;#(h
*h
 ,h
 6	h

 6h
 4h
 1h
 5h
 *h
 -h
 $h
 7h
 5h
 !h
 
Ah
 i l h
T	Mr?   r  )Hr   
__future__r   r   r  typingr   r   r   r   numpynp
tensorflowrL   activations_tfr	   modeling_tf_outputsr
   r   r   r   r   r   modeling_tf_utilsr   r   r   r   r   r   r   r   r   r   tf_utilsr   r   r   utilsr   r   r   r    configuration_layoutlmr"   
get_loggerr   r  r  r4   Layerr$   r   r   r   r   r   r   r  r2  r;  rA  r`  ri  r  LAYOUTLM_START_DOCSTRINGr  r  r  r  r  r  r,   r?   r>   <module>r     s    "   / /   /    S R t t 2 
		H	%"C 5<<-- C NAHell00 AHJL5<<-- L>0.%,,,, 0.hHU\\// H<Lu||)) L>d0ell(( d0PK&** K&^Hu||)) H<"L(:(: "LL-!3!3 -b-** -( L(%,,,, L( L(^ 1  ( T5 p hS*/ S*	S*l RTlm@%57S @% n@%F  xM*CEa xMxMv  |M'@B[ |M|M~ 
 LM%>@W LMLMr?   