
    iԟ                     z   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 ddl	m
Z ddlm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 ddlmZ ddlmZ ddlmZm Z m!Z!m"Z" ddl#m$Z$ ddl%m&Z& ddl'm(Z(  e"jR                  e*      Z+ejX                  Z- G d dej\                        Z/	 dCdej\                  dej`                  dej`                  dej`                  dej`                  dz  de1de1fdZ2 G d dej\                        Z3 G d d ej\                        Z4 G d! d"ej\                        Z5 G d# d$ej\                        Z6 G d% d&ej\                        Z7 G d' d(e      Z8 G d) d*ej\                        Z9 G d+ d,ej\                        Z: G d- d.ej\                        Z; G d/ d0ej\                        Z< G d1 d2ej\                        Z=e  G d3 d4e             Z>e  G d5 d6e>             Z?e  G d7 d8e>             Z@ e d9:       G d; d<e>             ZA e d=:       G d> d?e>             ZBe  G d@ dAe>             ZCg dBZDy)DzPyTorch LayoutLM model.    )CallableN)nn)BCEWithLogitsLossCrossEntropyLossMSELoss   )initialization)ACT2FN)GradientCheckpointingLayer)BaseModelOutputBaseModelOutputWithPoolingMaskedLMOutputQuestionAnsweringModelOutputSequenceClassifierOutputTokenClassifierOutput)ALL_ATTENTION_FUNCTIONSPreTrainedModel)Unpack)apply_chunking_to_forward)TransformersKwargsauto_docstringcan_return_tuplelogging)merge_with_config_defaults)capture_outputs   )LayoutLMConfigc                   4     e Zd ZdZ fdZ	 	 	 	 	 ddZ xZS )LayoutLMEmbeddingszGConstruct the embeddings from word, position and token_type embeddings.c                    t         |           t        j                  |j                  |j
                  |j                        | _        t        j                  |j                  |j
                        | _	        t        j                  |j                  |j
                        | _        t        j                  |j                  |j
                        | _        t        j                  |j                  |j
                        | _        t        j                  |j                  |j
                        | _        t        j                  |j                  |j
                        | _        t#        |j
                  |j$                        | _        t        j(                  |j*                        | _        | j/                  dt1        j2                  |j                        j5                  d      d       y )N)padding_idxepsposition_idsr   F)
persistent)super__init__r   	Embedding
vocab_sizehidden_sizepad_token_idword_embeddingsmax_position_embeddingsposition_embeddingsmax_2d_position_embeddingsx_position_embeddingsy_position_embeddingsh_position_embeddingsw_position_embeddingstype_vocab_sizetoken_type_embeddingsLayoutLMLayerNormlayer_norm_eps	LayerNormDropouthidden_dropout_probdropoutregister_buffertorcharangeexpandselfconfig	__class__s     /var/www/vps2.regionflexible.com/Desarrollo/venv/lib/python3.12/site-packages/transformers/models/layoutlm/modeling_layoutlm.pyr)   zLayoutLMEmbeddings.__init__3   s[   !||F,=,=v?Q?Q_e_r_rs#%<<0N0NPVPbPb#c %'\\&2S2SU[UgUg%h"%'\\&2S2SU[UgUg%h"%'\\&2S2SU[UgUg%h"%'\\&2S2SU[UgUg%h"%'\\&2H2H&J\J\%]"*6+=+=6CXCXYzz&"<"<=ELL)G)GHOOPWXej 	 	
    c                    ||j                         }n|j                         d d }|d   }||j                  n|j                  }|| j                  d d d |f   }|&t        j                  |t        j
                  |      }|| j                  |      }|}	| j                  |      }
	 | j                  |d d d d df         }| j                  |d d d d df         }| j                  |d d d d df         }| j                  |d d d d df         }| j                  |d d d d df   |d d d d df   z
        }| j                  |d d d d df   |d d d d df   z
        }| j                  |      }|	|
z   |z   |z   |z   |z   |z   |z   |z   }| j                  |      }| j                  |      }|S # t        $ r}t        d      |d }~ww xY w)Nr&   r   dtypedevicer      r   z:The `bbox`coordinate values should be within 0-1000 range.)sizerK   r$   r?   zeroslongr.   r0   r2   r3   
IndexErrorr4   r5   r7   r:   r=   )rC   	input_idsbboxtoken_type_idsr$   inputs_embedsinput_shape
seq_lengthrK   words_embeddingsr0   left_position_embeddingsupper_position_embeddingsright_position_embeddingslower_position_embeddingser4   r5   r7   
embeddingss                       rF   forwardzLayoutLMEmbeddings.forwardD   s1     #..*K',,.s3K ^
%.%:!!@T@T,,Q^<L!"[[EJJvVN  00;M("66|D	b'+'A'A$q!Qw-'P$(,(B(B41a=(Q%(,(B(B41a=(Q%(,(B(B41a=(Q% !% : :41a=4PQSTVWPW=;X Y $ : :41a=4PQSTVWPW=;X Y $ : :> J !"&' (( (	(
 (( $$ $$ $$ 	 ^^J/
\\*-
)  	bYZ`aa	bs   ,A,F7 7	G GG)NNNNN)__name__
__module____qualname____doc__r)   r^   __classcell__rE   s   @rF   r   r   0   s!    Q
& 5rG   r   modulequerykeyvalueattention_maskscalingr=   c                    t        j                  ||j                  dd            |z  }|||z   }t        j                  j                  |dt         j                        j                  |j                        }t        j                  j                  ||| j                        }t        j                  ||      }	|	j                  dd      j                         }	|	|fS )NrL   r   r&   )dimrJ   )ptrainingr   )r?   matmul	transposer   
functionalsoftmaxfloat32torJ   r=   rn   
contiguous)
re   rf   rg   rh   ri   rj   r=   kwargsattn_weightsattn_outputs
             rF   eager_attention_forwardry   }   s     <<s}}Q':;gEL!#n4==((2U]](SVVW\WbWbcL==((6??([L,,|U3K''1-88:K$$rG   c                        e Zd Z fdZ	 ddej
                  dej                  dz  dee   de	ej
                  ej
                  dz  f   fdZ
 xZS )	LayoutLMSelfAttentionc                 $   t         |           |j                  |j                  z  dk7  r2t	        |d      s&t        d|j                   d|j                   d      || _        |j                  | _        t        |j                  |j                  z        | _        | j                  | j                  z  | _	        t        j                  |j                  | j                        | _        t        j                  |j                  | j                        | _        t        j                  |j                  | j                        | _        t        j                  |j                         | _        |j                   | _        | j                  dz  | _        y )Nr   embedding_sizezThe hidden size (z6) is not a multiple of the number of attention heads ()g      )r(   r)   r,   num_attention_headshasattr
ValueErrorrD   intattention_head_sizeall_head_sizer   Linearrf   rg   rh   r;   attention_probs_dropout_probr=   attention_dropoutrj   rB   s     rF   r)   zLayoutLMSelfAttention.__init__   sC    : ::a?PVXhHi#F$6$6#7 8 445Q8 
 #)#=#= #&v'9'9F<V<V'V#W !558P8PPYYv1143E3EF
99V//1C1CDYYv1143E3EF
zz&"E"EF!'!D!D//5rG   Nhidden_statesri   rv   returnc                 x   |j                   d d }g |d| j                  }| j                  |      j                  |      j	                  dd      }| j                  |      j                  |      j	                  dd      }| j                  |      j                  |      j	                  dd      }t        j                  | j                  j                  t              }	 |	| ||||f| j                  sdn| j                  | j                  d|\  }
} |
j                  g |d j!                         }
|
|fS )Nr&   r   rL           )r=   rj   )shaper   rf   viewrp   rg   rh   r   get_interfacerD   _attn_implementationry   rn   r   rj   reshaperu   )rC   r   ri   rv   rU   hidden_shapequery_states
key_statesvalue_statesattention_interfacerx   rw   s               rF   r^   zLayoutLMSelfAttention.forward   s>    $))#2.CCbC$*B*BCzz-055lCMMaQRSXXm,11,?II!QO
zz-055lCMMaQRS(?(M(MKK,,.E)
 %8	%
  $}}C$2H2HLL	%
 	%
!\ *k));;;;FFHL((rG   N)r_   r`   ra   r)   r?   TensorFloatTensorr   r   tupler^   rc   rd   s   @rF   r{   r{      sd    60 48)||) ))D0) +,	)
 
u||U\\D00	1)rG   r{   c                   n     e Zd Z fdZdej
                  dej
                  dej
                  fdZ xZS )LayoutLMSelfOutputc                 (   t         |           t        j                  |j                  |j                        | _        t        j                  |j                  |j                        | _        t        j                  |j                        | _
        y Nr"   )r(   r)   r   r   r,   denser:   r9   r;   r<   r=   rB   s     rF   r)   zLayoutLMSelfOutput.__init__   s`    YYv1163E3EF
f&8&8f>S>STzz&"<"<=rG   r   input_tensorr   c                 r    | j                  |      }| j                  |      }| j                  ||z         }|S r   r   r=   r:   rC   r   r   s      rF   r^   zLayoutLMSelfOutput.forward   7    

=1]3}|'CDrG   r_   r`   ra   r)   r?   r   r^   rc   rd   s   @rF   r   r      1    >U\\  RWR^R^ rG   r   c            	            e Zd Z fdZ	 ddej
                  dej                  dz  dee   dej
                  fdZ	 xZ
S )	LayoutLMAttentionc                 b    t         |           t        |      | _        t	        |      | _        y r   )r(   r)   r{   rC   r   outputrB   s     rF   r)   zLayoutLMAttention.__init__   s&    )&1	(0rG   Nr   ri   rv   r   c                 ^    |} | j                   |fd|i|\  }}| j                  ||      }|S Nri   )rC   r   )rC   r   ri   rv   residual_s         rF   r^   zLayoutLMAttention.forward   sK     !$499
)
 
q
 M8<rG   r   )r_   r`   ra   r)   r?   r   r   r   r   r^   rc   rd   s   @rF   r   r      sQ    1 48|| ))D0 +,	
 
rG   r   c                   V     e Zd Z fdZdej
                  dej
                  fdZ xZS )LayoutLMIntermediatec                    t         |           t        j                  |j                  |j
                        | _        t        |j                  t              rt        |j                     | _        y |j                  | _        y r   )r(   r)   r   r   r,   intermediate_sizer   
isinstance
hidden_actstrr
   intermediate_act_fnrB   s     rF   r)   zLayoutLMIntermediate.__init__   s]    YYv1163K3KL
f''-'-f.?.?'@D$'-'8'8D$rG   r   r   c                 J    | j                  |      }| j                  |      }|S r   )r   r   rC   r   s     rF   r^   zLayoutLMIntermediate.forward   s&    

=100?rG   r   rd   s   @rF   r   r      s#    9U\\ ell rG   r   c                   n     e Zd Z fdZdej
                  dej
                  dej
                  fdZ xZS )LayoutLMOutputc                 (   t         |           t        j                  |j                  |j
                        | _        t        j                  |j
                  |j                        | _        t        j                  |j                        | _        y r   )r(   r)   r   r   r   r,   r   r:   r9   r;   r<   r=   rB   s     rF   r)   zLayoutLMOutput.__init__  s`    YYv779K9KL
f&8&8f>S>STzz&"<"<=rG   r   r   r   c                 r    | j                  |      }| j                  |      }| j                  ||z         }|S r   r   r   s      rF   r^   zLayoutLMOutput.forward  r   rG   r   rd   s   @rF   r   r     r   rG   r   c            	            e Zd Z fdZ	 d	dej
                  dej                  dz  dee   dej
                  fdZ	d Z
 xZS )
LayoutLMLayerc                     t         |           |j                  | _        d| _        t	        |      | _        t        |      | _        t        |      | _	        y )Nr   )
r(   r)   chunk_size_feed_forwardseq_len_dimr   	attentionr   intermediater   r   rB   s     rF   r)   zLayoutLMLayer.__init__  sI    '-'E'E$*6208$V,rG   Nr   ri   rv   r   c                      | j                   |fd|i|}t        | j                  | j                  | j                  |      }|S r   )r   r   feed_forward_chunkr   r   )rC   r   ri   rv   s       rF   r^   zLayoutLMLayer.forward  sY     '
)
 
 2##T%A%A4CSCSUb
 rG   c                 L    | j                  |      }| j                  ||      }|S r   )r   r   )rC   attention_outputintermediate_outputlayer_outputs       rF   r   z LayoutLMLayer.feed_forward_chunk+  s,    "//0@A{{#68HIrG   r   )r_   r`   ra   r)   r?   r   r   r   r   r^   r   rc   rd   s   @rF   r   r     sV    - 48|| ))D0 +,	
 
$rG   r   c            	       n     e Zd Z fdZ	 ddej
                  dej                  dz  dee   de	fdZ
 xZS )	LayoutLMEncoderc                     t         |           || _        t        j                  t        |j                        D cg c]  }t        |       c}      | _        d| _	        y c c}w )NF)
r(   r)   rD   r   
ModuleListrangenum_hidden_layersr   layergradient_checkpointing)rC   rD   irE   s      rF   r)   zLayoutLMEncoder.__init__3  sN    ]]5IaIaCb#caM&$9#cd
&+# $ds   A#Nr   ri   rv   r   c                 P    | j                   D ]  } |||fi |} t        |      S )N)last_hidden_state)r   r   )rC   r   ri   rv   layer_modules        rF   r^   zLayoutLMEncoder.forward9  sC     !JJ 	L( M	 +
 	
rG   r   )r_   r`   ra   r)   r?   r   r   r   r   r   r^   rc   rd   s   @rF   r   r   2  sM    , 48
||
 ))D0
 +,	

 

rG   r   c                   V     e Zd Z fdZdej
                  dej
                  fdZ xZS )LayoutLMPoolerc                     t         |           t        j                  |j                  |j                        | _        t        j                         | _        y r   )r(   r)   r   r   r,   r   Tanh
activationrB   s     rF   r)   zLayoutLMPooler.__init__M  s9    YYv1163E3EF
'')rG   r   r   c                 \    |d d df   }| j                  |      }| j                  |      }|S )Nr   )r   r   )rC   r   first_token_tensorpooled_outputs       rF   r^   zLayoutLMPooler.forwardR  s6     +1a40

#566rG   r   rd   s   @rF   r   r   L  s#    $
U\\ ell rG   r   c                   V     e Zd Z fdZdej
                  dej
                  fdZ xZS )LayoutLMPredictionHeadTransformc                 h   t         |           t        j                  |j                  |j                        | _        t        |j                  t              rt        |j                     | _
        n|j                  | _
        t        j                  |j                  |j                        | _        y r   )r(   r)   r   r   r,   r   r   r   r   r
   transform_act_fnr:   r9   rB   s     rF   r)   z(LayoutLMPredictionHeadTransform.__init__]  s{    YYv1163E3EF
f''-$*6+<+<$=D!$*$5$5D!f&8&8f>S>STrG   r   r   c                 l    | j                  |      }| j                  |      }| j                  |      }|S r   )r   r   r:   r   s     rF   r^   z'LayoutLMPredictionHeadTransform.forwardf  s4    

=1--m<}5rG   r   rd   s   @rF   r   r   \  s$    UU\\ ell rG   r   c                   $     e Zd Z fdZd Z xZS )LayoutLMLMPredictionHeadc                    t         |           t        |      | _        t	        j
                  |j                  |j                  d      | _        t	        j                  t        j                  |j                              | _        y )NT)bias)r(   r)   r   	transformr   r   r,   r+   decoder	Parameterr?   rN   r   rB   s     rF   r)   z!LayoutLMLMPredictionHead.__init__o  s[    8@ yy!3!3V5F5FTRLLV->->!?@	rG   c                 J    | j                  |      }| j                  |      }|S r   )r   r   r   s     rF   r^   z LayoutLMLMPredictionHead.forwardx  s$    }5]3rG   )r_   r`   ra   r)   r^   rc   rd   s   @rF   r   r   n  s    ArG   r   c                   V     e Zd Z fdZdej
                  dej
                  fdZ xZS )LayoutLMOnlyMLMHeadc                 B    t         |           t        |      | _        y r   )r(   r)   r   predictionsrB   s     rF   r)   zLayoutLMOnlyMLMHead.__init__  s    3F;rG   sequence_outputr   c                 (    | j                  |      }|S r   )r   )rC   r   prediction_scoress      rF   r^   zLayoutLMOnlyMLMHead.forward  s     ,,_=  rG   r   rd   s   @rF   r   r     s#    <!u|| ! !rG   r   c                   d     e Zd ZU eed<   dZdZeedZ	 e
j                          fd       Z xZS )LayoutLMPreTrainedModelrD   layoutlmT)r   
attentionsc                 X   t         |   |       t        |t              r t	        j
                  |j                         yt        |t              rZt	        j                  |j                  t        j                  |j                  j                  d         j                  d             yy)zInitialize the weightsr&   r%   N)r(   _init_weightsr   r   initzeros_r   r   copy_r$   r?   r@   r   rA   )rC   re   rE   s     rF   r   z%LayoutLMPreTrainedModel._init_weights  sx     	f%f67KK$ 23JJv**ELL9L9L9R9RSU9V,W,^,^_f,gh 4rG   )r_   r`   ra   r   __annotations__base_model_prefixsupports_gradient_checkpointingr   r{   _can_record_outputsr?   no_gradr   rc   rd   s   @rF   r   r     sA    "&*#&+
 U]]_i irG   r   c                   &    e Zd Z fdZd Zd Zeee	 	 	 	 	 	 dde	j                  dz  de	j                  dz  de	j                  dz  de	j                  dz  d	e	j                  dz  d
e	j                  dz  dee   deez  fd                     Z xZS )LayoutLMModelc                     t         |   |       || _        t        |      | _        t        |      | _        t        |      | _        | j                          y r   )
r(   r)   rD   r   r]   r   encoderr   pooler	post_initrB   s     rF   r)   zLayoutLMModel.__init__  sG     ,V4&v.$V, 	rG   c                 .    | j                   j                  S r   r]   r.   rC   s    rF   get_input_embeddingsz"LayoutLMModel.get_input_embeddings  s    ...rG   c                 &    || j                   _        y r   r  )rC   rh   s     rF   set_input_embeddingsz"LayoutLMModel.set_input_embeddings  s    */'rG   NrQ   rR   ri   rS   r$   rT   rv   r   c                 (   ||t        d      |#| j                  ||       |j                         }n!||j                         dd }nt        d      ||j                  n|j                  }	|t	        j
                  ||	      }|&t	        j                  |t        j                  |	      }|)t	        j                  |dz   t        j                  |	      }|j                  d      j                  d	      }
|
j                  | j                  
      }
d|
z
  t	        j                  | j                        j                  z  }
| j                  |||||      } | j                  ||
fi |}|d   }| j                  |      }t!        ||      S )a  
        bbox (`torch.LongTensor` of shape `(batch_size, sequence_length, 4)`, *optional*):
            Bounding boxes of each input sequence tokens. Selected in the range `[0,
            config.max_2d_position_embeddings-1]`. Each bounding box should be a normalized version in (x0, y0, x1, y1)
            format, where (x0, y0) corresponds to the position of the upper left corner in the bounding box, and (x1,
            y1) represents the position of the lower right corner. See [Overview](#Overview) for normalization.

        Examples:

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

        >>> tokenizer = AutoTokenizer.from_pretrained("microsoft/layoutlm-base-uncased")
        >>> model = LayoutLMModel.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="pt")
        >>> input_ids = encoding["input_ids"]
        >>> attention_mask = encoding["attention_mask"]
        >>> token_type_ids = encoding["token_type_ids"]
        >>> bbox = torch.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
        ```NzDYou cannot specify both input_ids and inputs_embeds at the same timer&   z5You have to specify either input_ids or inputs_embeds)rK   rI   )   r   rL   )rJ   g      ?)rQ   rR   r$   rS   rT   r   )r   pooler_output)r   %warn_if_padding_and_no_attention_maskrM   rK   r?   onesrN   rO   	unsqueezert   rJ   finfominr]   r  r  r   )rC   rQ   rR   ri   rS   r$   rT   rv   rU   rK   extended_attention_maskembedding_outputencoder_outputsr   r   s                  rF   r^   zLayoutLMModel.forward  s   f  ]%>cdd"66y.Q#..*K&',,.s3KTUU%.%:!!@T@T!"ZZFCN!"[[EJJvVN<;;{T1FSD"0":":1"="G"G"J"9"<"<4::"<"N#&)@#@EKKPTPZPZD[D_D_"_??%)' + 
 '$,,#
 

 *!,O4)-'
 	
rG   )NNNNNN)r_   r`   ra   r)   r  r
  r   r   r   r?   
LongTensorr   r   r   r   r   r^   rc   rd   s   @rF   r   r     s    	/0   .2(,37260426[
##d*[
 %[
 ))D0	[

 ((4/[
 &&-[
 ((4/[
 +,[
 
+	+[
    [
rG   r   c                   L    e Zd ZdddZ fdZd Zd Zd Zee		 	 	 	 	 	 	 dd	e
j                  dz  d
e
j                  dz  de
j                  dz  de
j                  dz  de
j                  dz  de
j                  dz  de
j                  dz  dee   deez  fd              Z xZS )LayoutLMForMaskedLMzcls.predictions.biasz*layoutlm.embeddings.word_embeddings.weight)zcls.predictions.decoder.biaszcls.predictions.decoder.weightc                     t         |   |       t        |      | _        t	        |      | _        | j                          y r   )r(   r)   r   r   r   clsr  rB   s     rF   r)   zLayoutLMForMaskedLM.__init__  s4     %f-&v. 	rG   c                 B    | j                   j                  j                  S r   r   r]   r.   r  s    rF   r  z(LayoutLMForMaskedLM.get_input_embeddings!      }}''777rG   c                 B    | j                   j                  j                  S r   )r  r   r   r  s    rF   get_output_embeddingsz)LayoutLMForMaskedLM.get_output_embeddings$  s    xx##+++rG   c                     || j                   j                  _        |j                  | j                   j                  _        y r   )r  r   r   r   )rC   new_embeddingss     rF   set_output_embeddingsz)LayoutLMForMaskedLM.set_output_embeddings'  s,    '5$$2$7$7!rG   NrQ   rR   ri   rS   r$   rT   labelsrv   r   c                 :    | j                   ||f||||d|}	|	d   }
| j                  |
      }d}|Ft               } ||j                  d| j                  j
                        |j                  d            }t        |||	j                  |	j                        S )a2	  
        bbox (`torch.LongTensor` of shape `(batch_size, sequence_length, 4)`, *optional*):
            Bounding boxes of each input sequence tokens. Selected in the range `[0,
            config.max_2d_position_embeddings-1]`. Each bounding box should be a normalized version in (x0, y0, x1, y1)
            format, where (x0, y0) corresponds to the position of the upper left corner in the bounding box, and (x1,
            y1) represents the position of the lower right corner. See [Overview](#Overview) for normalization.
        labels (`torch.LongTensor` of shape `(batch_size, sequence_length)`, *optional*):
            Labels for computing the masked language modeling loss. Indices should be in `[-100, 0, ...,
            config.vocab_size]` (see `input_ids` docstring) Tokens with indices set to `-100` are ignored (masked), the
            loss is only computed for the tokens with labels in `[0, ..., config.vocab_size]`

        Examples:

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

        >>> tokenizer = AutoTokenizer.from_pretrained("microsoft/layoutlm-base-uncased")
        >>> model = LayoutLMForMaskedLM.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="pt")
        >>> input_ids = encoding["input_ids"]
        >>> attention_mask = encoding["attention_mask"]
        >>> token_type_ids = encoding["token_type_ids"]
        >>> bbox = torch.tensor([token_boxes])

        >>> labels = tokenizer("Hello world", return_tensors="pt")["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
        ```)ri   rS   r$   rT   r   Nr&   losslogitsr   r   )	r   r  r   r   rD   r+   r   r   r   )rC   rQ   rR   ri   rS   r$   rT   r#  rv   outputsr   r   masked_lm_lossloss_fcts                 rF   r^   zLayoutLMForMaskedLM.forward+  s    z  $--
 *)%'
 
 "!* HH_5')H%!&&r4;;+A+ABBN
 $!//))	
 	
rG   NNNNNNN)r_   r`   ra   _tied_weights_keysr)   r  r  r"  r   r   r?   r  r   r   r   r   r   r^   rc   rd   s   @rF   r  r    s    )?*V
8,8  .2(,37260426*.U
##d*U
 %U
 ))D0	U

 ((4/U
 &&-U
 ((4/U
   4'U
 +,U
 
	U
  U
rG   r  z
    LayoutLM Model with a sequence classification head on top (a linear layer on top of the pooled output) e.g. for
    document image classification tasks such as the [RVL-CDIP](https://www.cs.cmu.edu/~aharley/rvl-cdip/) dataset.
    )custom_introc                   6    e Zd Z fdZd Zee	 	 	 	 	 	 	 ddej                  dz  dej                  dz  dej                  dz  dej                  dz  dej                  dz  d	ej                  dz  d
ej                  dz  de
e   deez  fd              Z xZS )!LayoutLMForSequenceClassificationc                 ,   t         |   |       |j                  | _        t        |      | _        t        j                  |j                        | _        t        j                  |j                  |j                        | _        | j                          y r   r(   r)   
num_labelsr   r   r   r;   r<   r=   r   r,   
classifierr  rB   s     rF   r)   z*LayoutLMForSequenceClassification.__init__  i      ++%f-zz&"<"<=))F$6$68I8IJ 	rG   c                 B    | j                   j                  j                  S r   r  r  s    rF   r  z6LayoutLMForSequenceClassification.get_input_embeddings  r  rG   NrQ   rR   ri   rS   r$   rT   r#  rv   r   c           
          | j                   d	||||||d|}	|	d   }
| j                  |
      }
| j                  |
      }d}|| j                  j                  | j
                  dk(  rd| j                  _        nl| j
                  dkD  rL|j                  t        j                  k(  s|j                  t        j                  k(  rd| j                  _        nd| j                  _        | j                  j                  dk(  rIt               }| j
                  dk(  r& ||j                         |j                               }n |||      }n| j                  j                  dk(  r=t               } ||j                  d| j
                        |j                  d            }n,| j                  j                  dk(  rt               } |||      }t        |||	j                   |	j"                        S )
aB	  
        bbox (`torch.LongTensor` of shape `(batch_size, sequence_length, 4)`, *optional*):
            Bounding boxes of each input sequence tokens. Selected in the range `[0,
            config.max_2d_position_embeddings-1]`. Each bounding box should be a normalized version in (x0, y0, x1, y1)
            format, where (x0, y0) corresponds to the position of the upper left corner in the bounding box, and (x1,
            y1) represents the position of the lower right corner. See [Overview](#Overview) for normalization.
        labels (`torch.LongTensor` of shape `(batch_size,)`, *optional*):
            Labels for computing the sequence classification/regression loss. Indices should be in `[0, ...,
            config.num_labels - 1]`. If `config.num_labels == 1` a regression loss is computed (Mean-Square loss), If
            `config.num_labels > 1` a classification loss is computed (Cross-Entropy).

        Examples:

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

        >>> tokenizer = AutoTokenizer.from_pretrained("microsoft/layoutlm-base-uncased")
        >>> model = LayoutLMForSequenceClassification.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="pt")
        >>> input_ids = encoding["input_ids"]
        >>> attention_mask = encoding["attention_mask"]
        >>> token_type_ids = encoding["token_type_ids"]
        >>> bbox = torch.tensor([token_boxes])
        >>> sequence_label = torch.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
        ```rQ   rR   ri   rS   r$   rT   r   N
regressionsingle_label_classificationmulti_label_classificationr&   r%   )r   r=   r3  rD   problem_typer2  rJ   r?   rO   r   r   squeezer   r   r   r   r   r   )rC   rQ   rR   ri   rS   r$   rT   r#  rv   r(  r   r'  r&  r*  s                 rF   r^   z)LayoutLMForSequenceClassification.forward  s   z  $-- 
))%'
 
  
]3/{{''/??a'/;DKK,__q(fllejj.HFLL\a\e\eLe/LDKK,/KDKK,{{''<7"9??a'#FNN$4fnn6FGD#FF3D))-JJ+-B @&++b/R))-II,./'!//))	
 	
rG   r+  )r_   r`   ra   r)   r  r   r   r?   r  r   r   r   r   r   r^   rc   rd   s   @rF   r/  r/    s    8  .2(,37260426*.f
##d*f
 %f
 ))D0	f

 ((4/f
 &&-f
 ((4/f
   4'f
 +,f
 
)	)f
  f
rG   r/  a3  
    LayoutLM Model with a token classification head on top (a linear layer on top of the hidden-states output) e.g. for
    sequence labeling (information extraction) tasks such as the [FUNSD](https://guillaumejaume.github.io/FUNSD/)
    dataset and the [SROIE](https://rrc.cvc.uab.es/?ch=13) dataset.
    c                   6    e Zd Z fdZd Zee	 	 	 	 	 	 	 ddej                  dz  dej                  dz  dej                  dz  dej                  dz  dej                  dz  d	ej                  dz  d
ej                  dz  de
e   deez  fd              Z xZS )LayoutLMForTokenClassificationc                 ,   t         |   |       |j                  | _        t        |      | _        t        j                  |j                        | _        t        j                  |j                  |j                        | _        | j                          y r   r1  rB   s     rF   r)   z'LayoutLMForTokenClassification.__init__  r4  rG   c                 B    | j                   j                  j                  S r   r  r  s    rF   r  z3LayoutLMForTokenClassification.get_input_embeddings  r  rG   NrQ   rR   ri   rS   r$   rT   r#  rv   r   c           
      H    | j                   d||||||d|}	|	d   }
| j                  |
      }
| j                  |
      }d}|<t               } ||j	                  d| j
                        |j	                  d            }t        |||	j                  |	j                        S )a  
        bbox (`torch.LongTensor` of shape `(batch_size, sequence_length, 4)`, *optional*):
            Bounding boxes of each input sequence tokens. Selected in the range `[0,
            config.max_2d_position_embeddings-1]`. Each bounding box should be a normalized version in (x0, y0, x1, y1)
            format, where (x0, y0) corresponds to the position of the upper left corner in the bounding box, and (x1,
            y1) represents the position of the lower right corner. See [Overview](#Overview) for normalization.
        labels (`torch.LongTensor` of shape `(batch_size, sequence_length)`, *optional*):
            Labels for computing the token classification loss. Indices should be in `[0, ..., config.num_labels - 1]`.

        Examples:

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

        >>> tokenizer = AutoTokenizer.from_pretrained("microsoft/layoutlm-base-uncased")
        >>> model = LayoutLMForTokenClassification.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="pt")
        >>> input_ids = encoding["input_ids"]
        >>> attention_mask = encoding["attention_mask"]
        >>> token_type_ids = encoding["token_type_ids"]
        >>> bbox = torch.tensor([token_boxes])
        >>> token_labels = torch.tensor([1, 1, 0, 0]).unsqueeze(0)  # batch size of 1

        >>> 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
        ```r7  r   Nr&   r%  r;  )	r   r=   r3  r   r   r2  r   r   r   )rC   rQ   rR   ri   rS   r$   rT   r#  rv   r(  r   r'  r&  r*  s                 rF   r^   z&LayoutLMForTokenClassification.forward  s    v  $-- 
))%'
 
 "!*,,71')HFKKDOO<fkk"oND$!//))	
 	
rG   r+  )r_   r`   ra   r)   r  r   r   r?   r  r   r   r   r   r   r^   rc   rd   s   @rF   r?  r?    s    8  .2(,37260426*.R
##d*R
 %R
 ))D0	R

 ((4/R
 &&-R
 ((4/R
   4'R
 +,R
 
&	&R
  R
rG   r?  c                   X    e Zd Zd fd	Zd Zee	 	 	 	 	 	 	 	 ddej                  dz  dej                  dz  dej                  dz  dej                  dz  dej                  dz  d	ej                  dz  d
ej                  dz  dej                  dz  de
e   deez  fd              Z xZS )LayoutLMForQuestionAnsweringc                     t         |   |       |j                  | _        t        |      | _        t        j                  |j                  |j                        | _        | j                          y)z
        has_visual_segment_embedding (`bool`, *optional*, defaults to `True`):
            Whether or not to add visual segment embeddings.
        N)
r(   r)   r2  r   r   r   r   r,   
qa_outputsr  )rC   rD   has_visual_segment_embeddingrE   s      rF   r)   z%LayoutLMForQuestionAnswering.__init__r  sU    
 	  ++%f-))F$6$68I8IJ 	rG   c                 B    | j                   j                  j                  S r   r  r  s    rF   r  z1LayoutLMForQuestionAnswering.get_input_embeddings  r  rG   NrQ   rR   ri   rS   r$   rT   start_positionsend_positionsrv   r   c	           
          | j                   d
||||||d|	}
|
d   }| j                  |      }|j                  dd      \  }}|j                  d      j	                         }|j                  d      j	                         }d}||t        |j                               dkD  r|j                  d      }t        |j                               dkD  r|j                  d      }|j                  d      }|j                  d|      }|j                  d|      }t        |      } |||      } |||      }||z   dz  }t        ||||
j                  |
j                  	      S )a4	  
        bbox (`torch.LongTensor` of shape `(batch_size, sequence_length, 4)`, *optional*):
            Bounding boxes of each input sequence tokens. Selected in the range `[0,
            config.max_2d_position_embeddings-1]`. Each bounding box should be a normalized version in (x0, y0, x1, y1)
            format, where (x0, y0) corresponds to the position of the upper left corner in the bounding box, and (x1,
            y1) represents the position of the lower right corner. See [Overview](#Overview) for normalization.

        Example:

        In the example below, we prepare a question + context pair for the LayoutLM model. It will give us a prediction
        of what it thinks the answer is (the span of the answer within the texts parsed from the image).

        ```python
        >>> from transformers import AutoTokenizer, LayoutLMForQuestionAnswering
        >>> from datasets import load_dataset
        >>> import torch

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

        >>> dataset = load_dataset("nielsr/funsd", split="train")
        >>> 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="pt"
        ... )
        >>> 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"] = torch.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[start_scores.argmax(-1)], word_ids[end_scores.argmax(-1)]
        >>> print(" ".join(words[start : end + 1]))
        M. Hamann P. Harper, P. Martinez
        ```r7  r   r   r&   )rl   N)ignore_indexrL   )r&  start_logits
end_logitsr   r   r;  )r   rF  splitr=  ru   lenrM   clampr   r   r   r   )rC   rQ   rR   ri   rS   r$   rT   rI  rJ  rv   r(  r   r'  rM  rN  
total_lossignored_indexr*  
start_lossend_losss                       rF   r^   z$LayoutLMForQuestionAnswering.forward  s   ~  $-- 
))%'
 
 "!*1#)<<r<#: j#++B/::<''+668

&=+D?'')*Q."1"9"9""==%%'(1, - 5 5b 9(--a0M-33A}EO)//=AM']CH!,@J
M:H$x/14J+%!!//))
 	
rG   )T)NNNNNNNN)r_   r`   ra   r)   r  r   r   r?   r  r   r   r   r   r   r^   rc   rd   s   @rF   rD  rD  p  s   8  .2(,372604263715e
##d*e
 %e
 ))D0	e

 ((4/e
 &&-e
 ((4/e
 ))D0e
 ''$.e
 +,e
 
-	-e
  e
rG   rD  )r  r/  r?  rD  r   r   )r   )Erb   collections.abcr   r?   r   torch.nnr   r   r    r	   r   activationsr
   modeling_layersr   modeling_outputsr   r   r   r   r   r   modeling_utilsr   r   processing_utilsr   pytorch_utilsr   utilsr   r   r   r   utils.genericr   utils.output_capturingr   configuration_layoutlmr   
get_loggerr_   loggerr:   r8   Moduler   r   floatry   r{   r   r   r   r   r   r   r   r   r   r   r   r   r  r/  r?  rD  __all__r;  rG   rF   <module>rh     sg    $   A A & ! 9  G & 6 R R 7 5 2 
		H	% LL I Ih %II%<<% 
% <<	%
 LL4'% % %.3)BII 3)n 		 .299  RYY . D
bii 
4RYY  bii $ryy "!")) ! io i i& p
+ p
 p
f p
1 p
 p
f v
(? v
v
r b
%< b
b
J y
#: y
 y
xrG   