Ë
    ÛÓ^jÔŸ  ã                   ó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     €úy/var/www/ramen.bs-engineer-server.com/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ˆÔÜ#%§<¡<°×0NÑ0NÐPV×PbÑPbÓ#cˆÔ Ü%'§\¡\°&×2SÑ2SÐU[×UgÑUgÓ%hˆÔ"Ü%'§\¡\°&×2SÑ2SÐU[×UgÑUgÓ%hˆÔ"Ü%'§\¡\°&×2SÑ2SÐU[×UgÑUgÓ%hˆÔ"Ü%'§\¡\°&×2SÑ2SÐU[×UgÑUgÓ%hˆÔ"Ü%'§\¡\°&×2HÑ2HÈ&×J\ÑJ\Ó%]ˆÔ"ä*¨6×+=Ñ+=À6×CXÑCXÔYˆŒÜ—z‘z &×"<Ñ"<Ó=ˆŒà×ÑØœEŸL™L¨×)GÑ)GÓH×OÑOÐPWÓXÐejð 	õ 	
ó    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°Ð3ˆKà  ‘^ˆ
à%.Ð%:�×!Ò!À×@TÑ@TˆàÐØ×,Ñ,ªQ°°°¨^Ñ<ˆLàÐ!Ü"Ÿ[™[¨¼E¿J¹JÈvÔVˆNàÐ Ø ×0Ñ0°Ó;ˆMà(ÐØ"×6Ñ6°|ÓDÐð	bØ'+×'AÑ'AÀ$ÂqÊ!ÈQÀwÁ-Ó'PÐ$Ø(,×(BÑ(BÀ4ÊÊ1ÈaÈÁ=Ó(QÐ%Ø(,×(BÑ(BÀ4ÊÊ1ÈaÈÁ=Ó(QÐ%Ø(,×(BÑ(BÀ4ÊÊ1ÈaÈÁ=Ó(QÐ%ð !%× :Ñ :¸4ÂÂ1ÀaÀ¹=È4ÒPQÒSTÐVWÐPWÉ=Ñ;XÓ YÐØ $× :Ñ :¸4ÂÂ1ÀaÀ¹=È4ÒPQÒSTÐVWÐPWÉ=Ñ;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ÑE€LØÐ!Ø# nÑ4ˆä—=‘=×(Ñ(¨¸2ÄUÇ]Á]Ð(ÓS×VÑVÐW\×WbÑWbÓc€LÜ—=‘=×(Ñ(¨¸È6Ï?É?Ð(Ó[€Lä—,‘,˜|¨UÓ3€KØ×'Ñ'¨¨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Ò?ÌÐPVÐXhÔHiÜØ# F×$6Ñ$6Ð#7ð 8Ø ×4Ñ4Ð5°Qð8óð ð
 ˆŒØ#)×#=Ñ#=ˆÔ Ü#& v×'9Ñ'9¸F×<VÑ<VÑ'VÓ#WˆÔ Ø!×5Ñ5¸×8PÑ8PÑPˆÔä—Y‘Y˜v×1Ñ1°4×3EÑ3EÓFˆŒ
Ü—9‘9˜V×/Ñ/°×1CÑ1CÓDˆŒÜ—Y‘Y˜v×1Ñ1°4×3EÑ3EÓFˆŒ
ä—z‘z &×"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˜ÐC bÐC¨$×*BÑ*BÑCˆà—z‘z -Ó0×5Ñ5°lÓC×MÑMÈaÐQRÓSˆØ—X‘X˜mÓ,×1Ñ1°,Ó?×IÑIÈ!ÈQÓOˆ
Ø—z‘z -Ó0×5Ñ5°lÓC×MÑMÈaÐQRÓSˆä(?×(MÑ(MØ�K‰K×,Ñ,Ô.Eó)
Ðñ %8ØØØØØð	%
ð  $Ÿ}š}‘C°$×2HÑ2HØ—L‘Lñ	%
ð ñ	%
Ñ!ˆ�\ð *�k×)Ñ)Ð;¨;Ð;¸Ò;×FÑFÓHˆØ˜LÐ(Ð(rG   ©N)r_   r`   ra   r)   r?   ÚTensorÚFloatTensorr   r   Útupler^   rc   rd   s   @rF   r{   r{   ”   sd   ø„ ô6ð0 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`   ø€ Ü‰ÑÔÜ—Y‘Y˜v×1Ñ1°6×3EÑ3EÓFˆŒ
ÜŸ™ f×&8Ñ&8¸f×>SÑ>SÔTˆŒÜ—z‘z &×"<Ñ"<Ó=ˆ�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§\¡\ð ÀÇÁð ÐRW×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	ˆ 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   € ð !ˆØ$˜4Ÿ9™9Øñ
à)ð
ð ñ
Ñˆ�qð
 Ÿ™ M°8Ó<ˆØÐ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]   ø€ Ü‰ÑÔÜ—Y‘Y˜v×1Ñ1°6×3KÑ3KÓLˆŒ
Ü�f×'Ñ'¬Ô-Ü'-¨f×.?Ñ.?Ñ'@ˆDÕ$à'-×'8Ñ'8ˆDÕ$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§\¡\ð °e·l±l÷ 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`   ø€ Ü‰ÑÔÜ—Y‘Y˜v×7Ñ7¸×9KÑ9KÓLˆŒ
ÜŸ™ f×&8Ñ&8¸f×>SÑ>SÔTˆŒÜ—z‘z &×"<Ñ"<Ó=ˆ�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Ñ%AÀ4×CSÑCSÐUbó
ˆð Ð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ÐØ—{‘{Ð#6Ð8HÓ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È×IaÑIaÓCbÖ#c¸a¤M°&Õ$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   € ð !ŸJ™Jò 	ˆ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   ø€ Ü‰ÑÔÜ—Y‘Y˜v×1Ñ1°6×3EÑ3EÓ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   € ð +ª1¨a¨4Ñ0ÐØŸ
™
Ð#5Ó6ˆØŸ™¨Ó6ˆØÐrG   r¤   rd   s   @rF   rÖ   rÖ   L  s#   ø„ ô$ð
 U§\¡\ð °e·l±l÷ 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{   ø€ Ü‰ÑÔÜ—Y‘Y˜v×1Ñ1°6×3EÑ3EÓFˆŒ
Ü�f×'Ñ'¬Ô-Ü$*¨6×+<Ñ+<Ñ$=ˆDÕ!à$*×$5Ñ$5ˆDÔ!ÜŸ™ f×&8Ñ&8¸f×>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§\¡\ð °e·l±l÷ 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¸Ó@ˆŒô —y‘y ×!3Ñ!3°V×5FÑ5FÈTÔRˆŒÜ—L‘L¤§¡¨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   ø€ Ü‰ÑÔÜ3°FÓ;ˆÕ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Ü�K‰K˜Ÿ™Õ$Ü˜Ô 2Ô3Ü�J‰J�v×*Ñ*¬E¯L©L¸×9LÑ9L×9RÑ9RÐSUÑ9VÓ,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Ñ6°yÀ.ÔQØ#Ÿ.™.Ó*‰KØÐ&Ø'×,Ñ,Ó.¨s°Ð3‰KäÐTÓUÐUà%.Ð%:�×!Ò!À×@TÑ@TˆàÐ!Ü"ŸZ™Z¨¸FÔCˆNØÐ!Ü"Ÿ[™[¨¼E¿J¹JÈvÔVˆNàˆ<Ü—;‘;˜{¨TÑ1¼¿¹ÈFÔSˆDà"0×":Ñ":¸1Ó"=×"GÑ"GÈÓ"JÐà"9×"<Ñ"<À4Ç:Á:Ð"<Ó"NÐØ#&Ð)@Ñ#@ÄEÇKÁKÐPT×PZÑPZÓD[×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Ø(,Ø37Ø26Ø04Ø26ñ[
à×#Ñ# 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   € Ø�x‰x×#Ñ#×+Ñ+Ð+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  �$—-‘-ØØð
ð *Ø)Ø%Ø'ñ
ð ñ
ˆð " !™*ˆØ ŸH™H _Ó5ÐàˆØÐÜ'Ó)ˆHÙ%Ø!×&Ñ& r¨4¯;©;×+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Ø(,Ø37Ø26Ø04Ø26Ø*.ñ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Ó-ˆŒÜ—z‘z &×"<Ñ"<Ó=ˆŒÜŸ)™) F×$6Ñ$6¸×8IÑ8IÓ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Ò'Ø/;�D—K‘KÕ,Ø—_‘_ qÒ(¨f¯l©l¼e¿j¹jÒ.HÈFÏLÉLÔ\a×\eÑ\eÒLeØ/L�D—K‘KÕ,à/K�D—K‘KÔ,à�{‰{×'Ñ'¨<Ò7Ü"›9�Ø—?‘? aÒ'Ù# F§N¡NÓ$4°f·n±nÓ6FÓG‘Dá# F¨FÓ3‘DØ—‘×)Ñ)Ð-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Ø(,Ø37Ø26Ø04Ø26Ø*.ñ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Ù˜FŸK™K¨¨D¯O©OÓ<¸f¿k¹kÈ"»oÓNˆDä$ØØØ!×/Ñ/Ø×)Ñ)ô	
ð 	
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Ø(,Ø37Ø26Ø04Ø26Ø*.ñ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¸×8IÑ8IÓ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Ñ 5°bÓ 9�à(×-Ñ-¨aÓ0ˆMØ-×3Ñ3°A°}ÓEˆOØ)×/Ñ/°°=ÓAˆMä'°]ÔCˆHÙ! ,°Ó@ˆJÙ 
¨MÓ:ˆHØ$ xÑ/°1Ñ4ˆJä+ØØ%Ø!Ø!×/Ñ/Ø×)Ñ)ô
ð 	
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Ø(,Ø37Ø26Ø04Ø26Ø37Ø15ñ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Ó	%€ð —L‘LÐ ôI˜Ÿ™ô Iðh ñ%Ø�I‰Ið%à�<‰<ð%ð 
�‰ð%ð �<‰<ð	%ð
 —L‘L 4Ñ'ð%ð ð%ð ó%ô.3)˜BŸI™Iô 3)ôn˜Ÿ™ô ô˜Ÿ	™	ô ô.˜2Ÿ9™9ô ô �R—Y‘Yô ôÐ.ô ôD
�b—i‘iô 
ô4�R—Y‘Yô ô  b§i¡iô ô$˜rŸy™yô ô"!˜"Ÿ)™)ô !ð ô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   