
    fThS                        S r SSKrSSKJrJrJr  SSKrSSKrSSKJr  SSK	J
r
JrJr  SSKJr  SSKJrJrJrJrJr  SS	KJr  SS
KJr  SSKJrJrJrJr  SSKJr  \" 5       (       aM  SSK r SSK!J"r"  \R                  RF                  RH                  \ RJ                  RL                  RN                  l$        \RP                  " \)5      r* " S S\RF                  5      r+ " S S\RF                  5      r, " S S\RF                  5      r- " S S\RF                  5      r. " S S\RF                  5      r/ " S S\RF                  5      r0 " S S\RF                  5      r1S3S jr2 " S S\RF                  5      r3\ " S  S!\5      5       r4S4S" jr5 " S# S$\RF                  5      r6 " S% S&\RF                  5      r7\ " S' S(\45      5       r8\" S)S*9 " S+ S,\45      5       r9\" S-S*9 " S. S/\45      5       r:\ " S0 S1\45      5       r;/ S2Qr<g)5zPyTorch LayoutLMv2 model.    N)OptionalTupleUnion)nn)BCEWithLogitsLossCrossEntropyLossMSELoss   )ACT2FN)BaseModelOutputBaseModelOutputWithPoolingQuestionAnsweringModelOutputSequenceClassifierOutputTokenClassifierOutput)PreTrainedModel)apply_chunking_to_forward)auto_docstringis_detectron2_availableloggingrequires_backends   )LayoutLMv2Config)META_ARCH_REGISTRYc                   2   ^  \ rS rSrSrU 4S jrS rSrU =r$ )LayoutLMv2Embeddings3   zGConstruct the embeddings from word, position and token_type embeddings.c                   > [         [        U ]  5         [        R                  " UR
                  UR                  UR                  S9U l        [        R                  " UR                  UR                  5      U l
        [        R                  " UR                  UR                  5      U l        [        R                  " UR                  UR                  5      U l        [        R                  " UR                  UR                  5      U l        [        R                  " UR                  UR                  5      U l        [        R                  " UR$                  UR                  5      U l        [        R(                  " UR                  UR*                  S9U l        [        R,                  " UR.                  5      U l        U R3                  S[4        R6                  " UR                  5      R9                  S5      SS9  g )N)padding_idxepsposition_ids)r   F
persistent)superr   __init__r   	Embedding
vocab_sizehidden_sizepad_token_idword_embeddingsmax_position_embeddingsposition_embeddingsmax_2d_position_embeddingscoordinate_sizex_position_embeddingsy_position_embeddings
shape_sizeh_position_embeddingsw_position_embeddingstype_vocab_sizetoken_type_embeddings	LayerNormlayer_norm_epsDropouthidden_dropout_probdropoutregister_buffertorcharangeexpandselfconfig	__class__s     j/var/www/auris/envauris/lib/python3.13/site-packages/transformers/models/layoutlmv2/modeling_layoutlmv2.pyr&   LayoutLMv2Embeddings.__init__6   sb   "D24!||F,=,=v?Q?Q_e_r_rs#%<<0N0NPVPbPb#c %'\\&2S2SU[UkUk%l"%'\\&2S2SU[UkUk%l"%'\\&2S2SU[UfUf%g"%'\\&2S2SU[UfUf%g"%'\\&2H2H&J\J\%]"f&8&8f>S>STzz&"<"<=ELL)G)GHOOPWXej 	 	
    c                     U R                  US S 2S S 2S4   5      nU R                  US S 2S S 2S4   5      nU R                  US S 2S S 2S4   5      nU R                  US S 2S S 2S4   5      nU R                  US S 2S S 2S4   US S 2S S 2S4   -
  5      nU R	                  US S 2S S 2S4   US S 2S S 2S4   -
  5      n[
        R                  " UUUUUU/SS9n	U	$ ! [         a  n[        S5      UeS nAff = f)Nr   r      r
   z;The `bbox` coordinate values should be within 0-1000 range.r"   dim)r0   r1   
IndexErrorr3   r4   r=   cat)
rA   bboxleft_position_embeddingsupper_position_embeddingsright_position_embeddingslower_position_embeddingser3   r4   spatial_position_embeddingss
             rD   !_calc_spatial_position_embeddings6LayoutLMv2Embeddings._calc_spatial_position_embeddingsH   s(   	c'+'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&+ii()))%% 
'
# +*#  	cZ[abb	cs   A,C 
C6%C11C6)	r7   r;   r3   r-   r6   r4   r+   r0   r1   )	__name__
__module____qualname____firstlineno____doc__r&   rT   __static_attributes____classcell__rC   s   @rD   r   r   3   s    Q
$+ +rF   r   c                   H   ^  \ rS rSrU 4S jrS rS r     SS jrSrU =r	$ )LayoutLMv2SelfAttentionb   c                   > [         TU ]  5         UR                  UR                  -  S:w  a7  [	        US5      (       d&  [        SUR                   SUR                   S35      eUR                  U l        UR                  U l        [        UR                  UR                  -  5      U l        U R                  U R                  -  U l	        UR                  U l
        UR                  U l        UR                  (       a  [        R                  " UR                  SU R                  -  SS9U l        [        R                  " [         R"                  " S	S	U R                  5      5      U l        [        R                  " [         R"                  " S	S	U R                  5      5      U l        O[        R                  " UR                  U R                  5      U l        [        R                  " UR                  U R                  5      U l        [        R                  " UR                  U R                  5      U l        [        R.                  " UR0                  5      U l        g )
Nr   embedding_sizezThe hidden size (z6) is not a multiple of the number of attention heads ()r
   Fbiasr   )r%   r&   r)   num_attention_headshasattr
ValueErrorfast_qkvintattention_head_sizeall_head_sizehas_relative_attention_biashas_spatial_attention_biasr   Linear
qkv_linear	Parameterr=   zerosq_biasv_biasquerykeyvaluer9   attention_probs_dropout_probr;   r@   s     rD   r&    LayoutLMv2SelfAttention.__init__c   s    : ::a?PVXhHiHi#F$6$6#7 8 445Q8  #)#=#= #&v'9'9F<V<V'V#W !558P8PP+1+M+M(*0*K*K'?? ii(:(:A@R@R<RY^_DO,,u{{1a9K9K'LMDK,,u{{1a9K9K'LMDK6#5#5t7I7IJDJyy!3!3T5G5GHDH6#5#5t7I7IJDJzz&"E"EFrF   c                     UR                  5       S S U R                  U R                  4-   nUR                  " U6 nUR	                  SSSS5      $ )Nr"   r   rH   r   r
   )sizerf   rk   viewpermute)rA   xnew_x_shapes      rD   transpose_for_scores,LayoutLMv2SelfAttention.transpose_for_scores}   sL    ffhsmt'?'?AYAY&ZZFFK yyAq!$$rF   c                    U R                   (       a  U R                  U5      n[        R                  " USSS9u  p4nUR	                  5       U R
                  R	                  5       :X  a  X0R
                  -   nXPR                  -   nOSUR	                  5       S-
  -  S-   nX0R
                  R                  " U6 -   nXPR                  R                  " U6 -   nO3U R                  U5      nU R                  U5      nU R                  U5      nX4U4$ )Nr
   r"   rI   )r   r   )r"   )ri   rp   r=   chunk
ndimensionrs   rt   r|   ru   rv   rw   )rA   hidden_statesqkvqkv_szs          rD   compute_qkv#LayoutLMv2SelfAttention.compute_qkv   s    ==//-0Ckk#qb1GA!||~!7!7!99OOallnq01E9((#..((#..

=)A'A

=)AQwrF   c                    U R                  U5      u  pxn	U R                  U5      n
U R                  U5      nU R                  U	5      nU
[        R                  " U R                  5      -  n
[
        R                  " XR                  SS5      5      nU R                  (       a  X-  nU R                  (       a  X-  nUR                  5       R                  UR                  [
        R                  5      [
        R                  " UR                  5      R                   5      n["        R$                  R'                  US[
        R(                  S9R+                  U5      nU R-                  U5      nUb  X-  n[
        R                  " X5      nUR/                  SSSS5      R1                  5       nUR3                  5       S S U R4                  4-   nUR6                  " U6 nU(       a  X4nU$ U4nU$ )Nr"   )rJ   dtyper   rH   r   r
   )r   r   mathsqrtrk   r=   matmul	transposerm   rn   floatmasked_fill_toboolfinfor   minr   
functionalsoftmaxfloat32type_asr;   r}   
contiguousr{   rl   r|   )rA   r   attention_mask	head_maskoutput_attentionsrel_pos
rel_2d_posr   r   r   query_layer	key_layervalue_layerattention_scoresattention_probscontext_layernew_context_layer_shapeoutputss                     rD   forwardLayoutLMv2SelfAttention.forward   s    ""=1a //2--a0	//2!DIId.F.F$GG <<5H5HR5PQ++'***+113@@ejj)5;;7G7M7M+N+R+R
 --//0@bPUP]P]/^ffgrs ,,7  -9O_B%--aAq9DDF"/"4"4"6s";t?Q?Q>S"S%**,CD6G=2 O\M]rF   )rl   rk   r;   ri   rm   rn   rv   rf   rs   rp   ru   rt   rw   NNFNN)
rV   rW   rX   rY   r&   r   r   r   r[   r\   r]   s   @rD   r_   r_   b   s.    G4%
( ) )rF   r_   c                   <   ^  \ rS rSrU 4S jr     SS jrSrU =r$ )LayoutLMv2Attention   c                 b   > [         TU ]  5         [        U5      U l        [	        U5      U l        g N)r%   r&   r_   rA   LayoutLMv2SelfOutputoutputr@   s     rD   r&   LayoutLMv2Attention.__init__   s&    +F3	*62rF   c           	      j    U R                  UUUUUUS9nU R                  US   U5      nU4USS  -   n	U	$ )Nr   r   r   r   )rA   r   )
rA   r   r   r   r   r   r   self_outputsattention_outputr   s
             rD   r   LayoutLMv2Attention.forward   sY     yy! ! 
  ;;|AF#%QR(88rF   )r   rA   r   rV   rW   rX   rY   r&   r   r[   r\   r]   s   @rD   r   r      s#    3  rF   r   c                   .   ^  \ rS rSrU 4S jrS rSrU =r$ )r      c                 (  > [         TU ]  5         [        R                  " UR                  UR                  5      U l        [        R                  " UR                  UR                  S9U l        [        R                  " UR                  5      U l
        g Nr   )r%   r&   r   ro   r)   denser7   r8   r9   r:   r;   r@   s     rD   r&   LayoutLMv2SelfOutput.__init__   s`    YYv1163E3EF
f&8&8f>S>STzz&"<"<=rF   c                 p    U R                  U5      nU R                  U5      nU R                  X-   5      nU$ r   r   r;   r7   rA   r   input_tensors      rD   r   LayoutLMv2SelfOutput.forward   5    

=1]3}'CDrF   r7   r   r;   r   r]   s   @rD   r   r      s    > rF   r   c                   b   ^  \ rS rSrU 4S jrS\R                  S\R                  4S jrSrU =r	$ )LayoutLMv2Intermediate   c                   > [         TU ]  5         [        R                  " UR                  UR
                  5      U l        [        UR                  [        5      (       a  [        UR                     U l        g UR                  U l        g r   )r%   r&   r   ro   r)   intermediate_sizer   
isinstance
hidden_actstrr   intermediate_act_fnr@   s     rD   r&   LayoutLMv2Intermediate.__init__   s`    YYv1163K3KL
f''--'-f.?.?'@D$'-'8'8D$rF   r   returnc                 J    U R                  U5      nU R                  U5      nU$ r   r   r   )rA   r   s     rD   r   LayoutLMv2Intermediate.forward   s&    

=100?rF   r   
rV   rW   rX   rY   r&   r=   Tensorr   r[   r\   r]   s   @rD   r   r      s(    9U\\ ell  rF   r   c                   z   ^  \ rS rSrU 4S jrS\R                  S\R                  S\R                  4S jrSrU =r	$ )LayoutLMv2Output   c                 (  > [         TU ]  5         [        R                  " UR                  UR
                  5      U l        [        R                  " UR
                  UR                  S9U l        [        R                  " UR                  5      U l        g r   )r%   r&   r   ro   r   r)   r   r7   r8   r9   r:   r;   r@   s     rD   r&   LayoutLMv2Output.__init__   s`    YYv779K9KL
f&8&8f>S>STzz&"<"<=rF   r   r   r   c                 p    U R                  U5      nU R                  U5      nU R                  X-   5      nU$ r   r   r   s      rD   r   LayoutLMv2Output.forward  r   rF   r   r   r]   s   @rD   r   r      s6    >U\\  RWR^R^  rF   r   c                   B   ^  \ rS rSrU 4S jr     SS jrS rSrU =r$ )LayoutLMv2Layeri  c                    > [         TU ]  5         UR                  U l        SU l        [	        U5      U l        [        U5      U l        [        U5      U l	        g )Nr   )
r%   r&   chunk_size_feed_forwardseq_len_dimr   	attentionr   intermediater   r   r@   s     rD   r&   LayoutLMv2Layer.__init__	  sI    '-'E'E$,V426:&v.rF   c           	          U R                  UUUUUUS9nUS   nUSS  n	[        U R                  U R                  U R                  U5      n
U
4U	-   n	U	$ )N)r   r   r   r   r   )r   r   feed_forward_chunkr   r   )rA   r   r   r   r   r   r   self_attention_outputsr   r   layer_outputs              rD   r   LayoutLMv2Layer.forward  s|     "&/! "0 "
 2!4(,0##T%A%A4CSCSUe
  /G+rF   c                 J    U R                  U5      nU R                  X!5      nU$ r   )r   r   )rA   r   intermediate_outputr   s       rD   r   "LayoutLMv2Layer.feed_forward_chunk-  s)    "//0@A{{#6IrF   )r   r   r   r   r   r   )	rV   rW   rX   rY   r&   r   r   r[   r\   r]   s   @rD   r   r     s(    / 8 rF   r   c                 D   SnU(       a4  US-  nX@S:  R                  5       U-  -  n[        R                  " U 5      nO,[        R                  " U * [        R                  " U 5      5      nUS-  nXV:  nU[        R
                  " UR                  5       U-  5      [        R
                  " X6-  5      -  X&-
  -  R                  [        R                   5      -   n[        R                  " U[        R                  " XS-
  5      5      nU[        R                  " XuU5      -  nU$ )aR  
Adapted from Mesh Tensorflow:
https://github.com/tensorflow/mesh/blob/0cb87fe07da627bf0b7e60475d59f95ed6b5be3d/mesh_tensorflow/transformer/transformer_layers.py#L593
Translate relative position to a bucket number for relative attention. The relative position is defined as
memory_position - query_position, i.e. the distance in tokens from the attending position to the attended-to
position. If bidirectional=False, then positive relative positions are invalid. We use smaller buckets for small
absolute relative_position and larger buckets for larger absolute relative_positions. All relative positions
>=max_distance map to the same bucket. All relative positions <=-max_distance map to the same bucket. This should
allow for more graceful generalization to longer sequences than the model has been trained on.

Args:
    relative_position: an int32 Tensor
    bidirectional: a boolean - whether the attention is bidirectional
    num_buckets: an integer
    max_distance: an integer

Returns:
    a Tensor with the same shape as relative_position, containing int32 values in the range [0, num_buckets)
r   rH   r   )longr=   absmax
zeros_likelogr   r   r   r   	full_likewhere)	relative_positionbidirectionalnum_bucketsmax_distanceretn	max_exactis_smallval_if_larges	            rD   relative_position_bucketr  3  s    * CA%++-;;II'(II((%*:*:;L*MN q I}H 		!'')i'(488L4L+MMQ\QhibnL 99\5??<WX+YZL5;;xL11CJrF   c                   L   ^  \ rS rSrU 4S jrS rS r       SS jrSrU =r	$ )LayoutLMv2Encoderi_  c                    > [         TU ]  5         Xl        [        R                  " [        UR                  5       Vs/ s H  n[        U5      PM     sn5      U l        UR                  U l	        UR                  U l
        U R                  (       aQ  UR                  U l        UR                  U l        [        R                  " U R                  UR                  SS9U l        U R                  (       a  UR                   U l        UR"                  U l        [        R                  " U R"                  UR                  SS9U l        [        R                  " U R"                  UR                  SS9U l        SU l        g s  snf )NFrd   )r%   r&   rB   r   
ModuleListrangenum_hidden_layersr   layerrm   rn   rel_pos_binsmax_rel_posro   rf   rel_pos_biasmax_rel_2d_posrel_2d_pos_binsrel_pos_x_biasrel_pos_y_biasgradient_checkpointing)rA   rB   _rC   s      rD   r&   LayoutLMv2Encoder.__init__`  s   ]]U6KcKcEd#eEdOF$;Ed#ef
+1+M+M(*0*K*K'++ & 3 3D%11D "		$*;*;V=W=W^c dD**"("7"7D#)#9#9D "$))D,@,@&B\B\ch"iD"$))D,@,@&B\B\ch"iD&+#! $fs   E;c                 z   UR                  S5      UR                  S5      -
  n[        UU R                  U R                  S9n[        R
                  " 5          U R                  R                  R                  5       U   R                  SSSS5      nS S S 5        UR                  5       nU$ ! , (       d  f       N = f)Nr   r"   r   r   r   r
   r   rH   )	unsqueezer  r
  r  r=   no_gradr  weighttr}   r   )rA   r!   rel_pos_matr   s       rD   !_calculate_1d_position_embeddings3LayoutLMv2Encoder._calculate_1d_position_embeddingsu  s    ",,R0<3I3I"3MM*))))
 ]]_''..0027;CCAq!QOG $$& _s   :B,,
B:c                    US S 2S S 2S4   nUS S 2S S 2S4   nUR                  S5      UR                  S5      -
  nUR                  S5      UR                  S5      -
  n[        UU R                  U R                  S9n[        UU R                  U R                  S9n[        R
                  " 5          U R                  R                  R                  5       U   R                  SSSS5      nU R                  R                  R                  5       U   R                  SSSS5      nS S S 5        UR                  5       nUR                  5       nXg-   nU$ ! , (       d  f       N4= f)Nr   r
   r   r"   r  r   rH   )r  r  r  r  r=   r  r  r  r  r}   r  r   )	rA   rM   position_coord_xposition_coord_yrel_pos_x_2d_matrel_pos_y_2d_mat	rel_pos_x	rel_pos_yr   s	            rD   !_calculate_2d_position_embeddings3LayoutLMv2Encoder._calculate_2d_position_embeddings  sP   1a=1a=+55b9<L<V<VWY<ZZ+55b9<L<V<VWY<ZZ,,,,,
	
 -,,,,
	 ]]_++22446yAII!QPQSTUI++22446yAII!QPQSTUI  ((*	((*	*
 _s   2A3E
E!c	                 R   U(       a  SOS n	U(       a  SOS n
U R                   (       a  U R                  U5      OS nU R                  (       a  U R                  U5      OS n[	        U R
                  5       H~  u  pU(       a  X4-   n	Ub  X=   OS nU R                  (       a1  U R                  (       a   U R                  UR                  UUUUUUS9nOU" UUUUUUS9nUS   nU(       d  Mu  U
US   4-   n
M     U(       a  X4-   n	U(       d  [        S UU	U
4 5       5      $ [        UU	U
S9$ )N r   r   r   c              3   0   #    U  H  nUc  M  Uv   M     g 7fr   r'  ).0r   s     rD   	<genexpr>,LayoutLMv2Encoder.forward.<locals>.<genexpr>  s"      A
  s   	)last_hidden_stater   
attentions)rm   r  rn   r$  	enumerater	  r  training_gradient_checkpointing_func__call__tupler   )rA   r   r   r   r   output_hidden_statesreturn_dictrM   r!   all_hidden_statesall_self_attentionsr   r   ilayer_modulelayer_head_masklayer_outputss                    rD   r   LayoutLMv2Encoder.forward  sV    #7BD$5b4JNJjJj$88FptEIEdEdT;;DAjn
(4OA#$58H$H!.7.CilO**t}} $ A A ))!"#%#) !B ! !-!"#%#)! *!,M  &9]1=M<O&O#9  5<   14D D  "%'   ++*
 	
rF   )rB   r  rm   rn   r	  r  r  r  r  r
  r  r  )NNFFTNN)
rV   rW   rX   rY   r&   r  r$  r   r[   r\   r]   s   @rD   r  r  _  s5    ,* < "@
 @
rF   r  c                   "    \ rS rSr\rSrS rSrg)LayoutLMv2PreTrainedModeli  
layoutlmv2c                    [        U[        R                  5      (       ak  UR                  R                  R                  SU R                  R                  S9  UR                  b%  UR                  R                  R                  5         gg[        U[        R                  5      (       ax  UR                  R                  R                  SU R                  R                  S9  UR                  b2  UR                  R                  UR                     R                  5         gg[        U[        R                  5      (       aJ  UR                  R                  R                  5         UR                  R                  R                  S5        g[        U[        5      (       ae  U R                  R                  (       aI  UR                   R                  R                  5         UR"                  R                  R                  5         gg[        U[$        5      (       aK  ['        US5      (       a9  UR(                  R                  R                  SU R                  R                  S9  ggg)zInitialize the weightsg        )meanstdN      ?visual_segment_embedding)r   r   ro   r  datanormal_rB   initializer_rangere   zero_r'   r   r7   fill_r_   ri   rs   rt   LayoutLMv2Modelrg   rC  )rA   modules     rD   _init_weights'LayoutLMv2PreTrainedModel._init_weights  s   fbii(( MM&&CT[[5R5R&S{{&  &&( '--MM&&CT[[5R5R&S!!-""6#5#56<<> .--KK""$MM$$S) 788{{##""((*""((* $ 00v9:://44<<#4;;KhKh<i ; 1rF   r'  N)	rV   rW   rX   rY   r   config_classbase_model_prefixrK  r[   r'  rF   rD   r=  r=    s    #L$jrF   r=  c                 r   [        U [        R                  R                  R                  R
                  5      (       a)  [        R                  R                  R                  X5      $ U n[        U [        R                  R                  5      (       a  [        R                  R                  U R                  U R                  SSUS9n[        R                  R                  U R                  5      Ul        [        R                  R                  U R                  5      Ul        U R                   Ul        U R"                  Ul        [        R$                  " S[        R&                  U R                   R(                  S9Ul        U R-                  5        H   u  p4UR/                  U[1        XA5      5        M"     A U$ )NT)num_featuresr    affinetrack_running_statsprocess_groupr   r   device)r   r=   r   modules	batchnorm
_BatchNormSyncBatchNormconvert_sync_batchnorm
detectron2layersFrozenBatchNorm2drP  r    rq   r  re   running_meanrunning_vartensorr   rU  num_batches_trackednamed_children
add_modulemy_convert_sync_batchnorm)rJ  rS  module_outputnamechilds        rD   rd  rd     s>   &%((**44??@@zz''>>vUUM&*++==>>..,,

 $' / 
  %xx11&--@"XX//<%+%8%8"$*$6$6!,1LL%**U[UhUhUoUo,p),,.  '@'VW /rF   c                   4   ^  \ rS rSrU 4S jrS rS rSrU =r$ )LayoutLMv2VisualBackbonei  c           	      j  > [         TU ]  5         UR                  5       U l        U R                  R                  R
                  n[        R                  " U5      " U R                  5      n[        UR                  [        R                  R                  R                  5      (       d   eUR                  U l	        [        U R                  R                  R                  5      [        U R                  R                  R                  5      :X  d   e[        U R                  R                  R                  5      nU R!                  S["        R$                  " U R                  R                  R                  5      R'                  USS5      SS9  U R!                  S["        R$                  " U R                  R                  R                  5      R'                  USS5      SS9  SU l        ["        R*                  " 5       (       a  [,        R/                  S5        SnU R                  R1                  5       U R(                     R2                  n[4        R6                  " [8        R:                  " [8        R:                  " US	   U-  5      UR<                  S	   -  5      [8        R:                  " [8        R:                  " US   U-  5      UR<                  S   -  5      45      U l        O([4        R@                  " UR<                  S S
 5      U l        [        UR<                  5      S
:X  aJ  UR<                  RC                  U R                  R1                  5       U R(                     RD                  5        U R                  R1                  5       U R(                     RD                  UR<                  S
   :X  d   eg )N
pixel_meanr   Fr#   	pixel_stdp2z0using `AvgPool2d` instead of `AdaptiveAvgPool2d`)   rn  r   rH   )#r%   r&   get_detectron2_configcfgMODELMETA_ARCHITECTUREr   getr   backboner[  modelingFPNlen
PIXEL_MEAN	PIXEL_STDr<   r=   r   r|   out_feature_key$are_deterministic_algorithms_enabledloggerwarningoutput_shapestrider   	AvgPool2dr   ceilimage_feature_pool_shapepoolAdaptiveAvgPool2dappendchannels)rA   rB   	meta_archmodelnum_channelsinput_shapebackbone_striderC   s          rD   r&   !LayoutLMv2VisualBackbone.__init__  s   //1HHNN44	"&&y1$((;%..**=*=*F*F*J*JKKKK488>>,,-TXX^^5M5M1NNNN488>>445LL22388q!L 	 	

 	dhhnn&>&>?DD\STVWXej 	 	
  $5577NNMN$K"mm88:4;O;OPWWOIIdiiA(HIFLkLklmLnnoIIdiiA(HIFLkLklmLnnoDI ,,V-L-LRa-PQDIv../14++224==3M3M3OPTPdPd3e3n3no}}))+D,@,@AJJfNmNmnoNpppprF   c                 B   [         R                  " U5      (       a  UOUR                  U R                  -
  U R                  -  nU R                  U5      nX0R                     nU R                  U5      R                  SS9R                  SS5      R                  5       nU$ )NrH   )	start_dimr   )r=   	is_tensorr`  rk  rl  rt  rz  r  flattenr   r   )rA   imagesimages_inputfeaturess       rD   r    LayoutLMv2VisualBackbone.forward<  s    #(??6#:#:QUQ`Q``dhdrdrr==.00199X&...;EEaKVVXrF   c           
         [         R                  R                  5       (       aE  [         R                  R                  5       (       a"  [         R                  R	                  5       S:  d  [        S5      e[         R                  R	                  5       n[         R                  R                  5       n[         R                  R                  5       nX2-  S:X  d  [        S5      e[        X2-  5       Vs/ s H   n[        [        XB-  US-   U-  5      5      PM"     nn[        X2-  5       Vs/ s H"  n[         R                  R                  XT   S9PM$     nnX-  n[        U R                  Xg   S9U l        g s  snf s  snf )Nr"   z/Make sure torch.distributed is set up properly.r   zGMake sure the number of processes can be divided by the number of nodesr   )ranks)rS  )r=   distributedis_availableis_initializedget_rankRuntimeErrorcudadevice_countget_world_sizer  list	new_grouprd  rt  )rA   	self_rank	node_size
world_sizer7  node_global_rankssync_bn_groups	node_ranks           rD   synchronize_batch_norm/LayoutLMv2VisualBackbone.synchronize_batch_normC  s@   **,,!!0022!!**,r1PQQ%%..0	JJ++-	&&557
&!+hiiV[\f\sVtuVtQRT%A7J"KLVtuMRS]SjMk
MkE''.?.B'CMk 	 
 *	1$--~Ohi v
s   0'E3()E8)rt  rp  rz  r  )	rV   rW   rX   rY   r&   r   r  r[   r\   r]   s   @rD   ri  ri    s    !qFj jrF   ri  c                   .   ^  \ rS rSrU 4S jrS rSrU =r$ )LayoutLMv2PooleriZ  c                    > [         TU ]  5         [        R                  " UR                  UR                  5      U l        [        R                  " 5       U l        g r   )r%   r&   r   ro   r)   r   Tanh
activationr@   s     rD   r&   LayoutLMv2Pooler.__init__[  s9    YYv1163E3EF
'')rF   c                 \    US S 2S4   nU R                  U5      nU R                  U5      nU$ )Nr   )r   r  )rA   r   first_token_tensorpooled_outputs       rD   r   LayoutLMv2Pooler.forward`  s6     +1a40

#566rF   )r  r   r   r]   s   @rD   r  r  Z  s    $
 rF   r  c                     ^  \ rS rSrU 4S jrS rS rSS jrS rS r	SS jr
\           SS	\\R                     S
\\R                     S\\R                     S\\R                     S\\R                     S\\R                     S\\R                     S\\R                     S\\   S\\   S\\   S\\\4   4S jj5       rSrU =r$ )rI  ii  c                   > [        U S5        [        TU ]	  U5        Xl        UR                  U l        [        U5      U l        [        U5      U l        [        R                  " UR                  S   UR                  5      U l        U R                  (       aG  [        R                  " [        R                  " SUR                  5      R                   S   5      U l        [        R$                  " UR                  UR&                  S9U l        [        R*                  " UR,                  5      U l        [1        U5      U l        [5        U5      U l        U R9                  5         g )Nr[  r"   r   r   r   )r   r%   r&   rB   has_visual_segment_embeddingr   
embeddingsri  visualr   ro   r  r)   visual_projrq   r'   r  rC  r7   r8   visual_LayerNormr9   r:   visual_dropoutr  encoderr  pooler	post_initr@   s     rD   r&   LayoutLMv2Model.__init__k  s    $- ,2,O,O).v6.v699V%D%DR%H&J\J\],,,.LLaI[I[9\9c9cde9f,gD) "V-?-?VEZEZ [ jj)C)CD(0&v. 	rF   c                 .    U R                   R                  $ r   r  r+   rA   s    rD   get_input_embeddings$LayoutLMv2Model.get_input_embeddings  s    ...rF   c                 $    XR                   l        g r   r  )rA   rw   s     rD   set_input_embeddings$LayoutLMv2Model.set_input_embeddings  s    */'rF   c                    Ub  UR                  5       nOUR                  5       S S nUS   nUcN  [        R                  " U[        R                  UR                  S9nUR                  S5      R                  U5      nUc  [        R                  " U5      nUc  U R                  R                  U5      nU R                  R                  U5      nU R                  R                  U5      n	U R                  R                  U5      n
XX-   U	-   U
-   nU R                  R                  U5      nU R                  R                  U5      nU$ )Nr"   r   rT  r   )r{   r=   r>   r   rU  r  	expand_asr   r  r+   r-   rT   r6   r7   r;   )rA   	input_idsrM   r!   token_type_idsinputs_embedsr  
seq_lengthr-   rS   r6   r  s               rD   _calc_text_embeddings%LayoutLMv2Model._calc_text_embeddings  s!    #..*K',,.s3K ^
 <<
%**YM]M]^L'11!4>>yIL!"--i8N  OO;;IFM"ooAA,O&*oo&W&WX\&]# $ E En U"8;VVYnn
__..z:
__,,Z8
rF   c                 B   U R                  U R                  U5      5      nU R                  R                  U5      nU R                  R	                  U5      nXE-   U-   nU R
                  (       a  XpR                  -  nU R                  U5      nU R                  U5      nU$ r   )	r  r  r  r-   rT   r  rC  r  r  )rA   imagerM   r!   visual_embeddingsr-   rS   r  s           rD   _calc_img_embeddings$LayoutLMv2Model._calc_img_embeddings  s     ,,T[[-?@"ooAA,O&*oo&W&WX\&]#&<?ZZ
,,777J**:6
((4
rF   c           
         [         R                  " [         R                  " SSUS   S-   -  SUUR                  S9U R                  R
                  S   SS9n[         R                  " [         R                  " SSU R                  R
                  S   S-   -  SUUR                  S9U R                  R
                  S   SS9n[         R                  " US S R                  US   S5      US S R                  US   S5      R                  SS5      USS  R                  US   S5      USS  R                  US   S5      R                  SS5      /SS9R                  SUR                  S5      5      nUR                  US   SS5      nU$ )	Nr   i  r   )rU  r   floor)rounding_moder"   rI   )r=   divr>   r   rB   r  stackrepeatr   r|   r{   )rA   r  rM   rU  final_shapevisual_bbox_xvisual_bbox_yvisual_bboxs           rD   _calc_visual_bbox!LayoutLMv2Model._calc_visual_bbox  s   		LL03a78jj KK003!

 		LL<<Q?!CDjj KK003!

 kkcr"))*B1*EqIcr"))*B1*EqISSTUWXYab!(()A!)DaHab!(()A!)DaHRRSTVWX	 
 $r499R=
! 	 "((QA>rF   c                     Ub  Ub  [        S5      eUb  UR                  5       $ Ub  UR                  5       S S $ [        S5      e)NDYou cannot specify both input_ids and inputs_embeds at the same timer"   5You have to specify either input_ids or inputs_embeds)rh   r{   )rA   r  r  s      rD   _get_input_shape LayoutLMv2Model._get_input_shape  sT     ]%>cdd">>##& %%',,TUUrF   r  rM   r  r   r  r!   r   r  r   r3  r4  r   c                 "	   U	b  U	OU R                   R                  n	U
b  U
OU R                   R                  n
Ub  UOU R                   R                  nU R	                  X5      nUb  UR
                  OUR
                  n[        U5      nU R                   R                  S   U R                   R                  S   -  US'   [        R                  " U5      n[        U R	                  X5      5      nUS==   US   -  ss'   [        R                  " U5      nU R                  U R                   R                  X-U5      n[        R                  " UU/SS9nUc  [        R                  " XS9n[        R                  " XS9n[        R                  " UU/SS9nUc$  [        R                  " U[        R                  US9nUc5  US   nU R                  R                   SS2SU24   nUR#                  U5      n[        R$                  " SUS   [        R                  US9R'                  US   S5      n[        R                  " UU/SS9nUc:  [        R                  " [)        [        U5      S/-   5      [        R                  US9nU R+                  UUUUUS9nU R-                  UUUS	9n[        R                  " UU/SS9nUR/                  S5      R/                  S
5      nUR1                  U R2                  S9nSU-
  [        R4                  " U R2                  5      R6                  -  nUb  UR9                  5       S:X  ah  UR/                  S5      R/                  S5      R/                  S5      R/                  S5      nUR#                  U R                   R:                  SSSS5      nOCUR9                  5       S
:X  a/  UR/                  S5      R/                  S5      R/                  S5      nUR1                  [=        U R?                  5       5      R2                  S9nOS/U R                   R:                  -  nU RA                  UUUUUU	U
US9nUS   nU RC                  U5      nU(       d
  UU4USS -   $ [E        UUURF                  URH                  S9$ )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.
image (`torch.FloatTensor` of shape `(batch_size, num_channels, height, width)` or `detectron.structures.ImageList` whose `tensors` is of shape `(batch_size, num_channels, height, width)`):
    Batch of document images.

Examples:

```python
>>> from transformers import AutoProcessor, LayoutLMv2Model, set_seed
>>> from PIL import Image
>>> import torch
>>> from datasets import load_dataset

>>> set_seed(0)

>>> processor = AutoProcessor.from_pretrained("microsoft/layoutlmv2-base-uncased")
>>> model = LayoutLMv2Model.from_pretrained("microsoft/layoutlmv2-base-uncased")


>>> dataset = load_dataset("hf-internal-testing/fixtures_docvqa", trust_remote_code=True)
>>> image_path = dataset["test"][0]["file"]
>>> image = Image.open(image_path).convert("RGB")

>>> encoding = processor(image, return_tensors="pt")

>>> outputs = model(**encoding)
>>> last_hidden_states = outputs.last_hidden_state

>>> last_hidden_states.shape
torch.Size([1, 342, 768])
```
Nr   r   rI   )rU  rT     )r  rM   r  r!   r  r  rM   r!   rH   )r   rB  r"   )rM   r!   r   r   r3  r4  )r,  pooler_outputr   r-  )%rB   r   r3  use_return_dictr  rU  r  r  r=   Sizer  rL   onesrr   r   r  r!   r?   r>   r  r2  r  r  r  r   r   r   r   rJ   r  next
parametersr  r  r   r   r-  )rA   r  rM   r  r   r  r!   r   r  r   r3  r4  r  rU  visual_shaper  r  
final_bboxvisual_attention_maskfinal_attention_maskr  visual_position_idsfinal_position_idstext_layout_emb
visual_emb	final_embextended_attention_maskencoder_outputssequence_outputr  s                                 rD   r   LayoutLMv2Model.forward  sF   f 2C1N-TXT_T_TqTq$8$D $++JjJj 	 &1%<k$++B]B]++IE%.%:!!@T@TK(++>>qADKKDhDhijDkkQzz,/400JKA,q/)jj-,,T[[-Q-QSWalmYYk2:
!"ZZCN %

< G$yy.:O)PVWX!"[[EJJvVN$QJ??77;J;GL'..{;L#ll1l1oUZZX^_ffNA
 #YY6I'JPQR<;;uT+%6!%<=UZZX^_D44)%' 5 
 .., / 


 II
;C	"6"@"@"C"M"Ma"P"9"<"<4::"<"N#&)@#@EKKPTPZPZD[D_D_"_ }}!#%//2<<Q?II"MWWXZ[	%,,T[[-J-JBPRTVXZ[	A%%//2<<R@JJ2N	!40A+B+H+HII!>!>>I,,#+/!5# ' 	
 *!,O4#]3oab6III)-')77&11	
 	
rF   )
rB   r  r  r  r  r  r  r  r  rC  r   )NN)NNNNNNNNNNN)rV   rW   rX   rY   r&   r  r  r  r  r  r  r   r   r=   
LongTensorFloatTensorr   r   r   r   r   r[   r\   r]   s   @rD   rI  rI  i  sR   (/02	#JV  15+/-16:59371559,0/3&*O
E,,-O
 u''(O
 ))*	O

 !!2!23O
 !!1!12O
 u//0O
 E--.O
   1 12O
 $D>O
 'tnO
 d^O
 
u00	1O
 O
rF   rI  ax  
    LayoutLMv2 Model with a sequence classification head on top (a linear layer on top of the concatenation of the
    final hidden state of the [CLS] token, average-pooled initial visual embeddings and average-pooled final visual
    embeddings, e.g. for document image classification tasks such as the
    [RVL-CDIP](https://www.cs.cmu.edu/~aharley/rvl-cdip/) dataset.
    )custom_introc                     ^  \ rS rSrU 4S jrS r\            SS\\R                     S\\R                     S\\R                     S\\R                     S\\R                     S	\\R                     S
\\R                     S\\R                     S\\R                     S\\   S\\   S\\   S\\\4   4S jj5       rSrU =r$ )#LayoutLMv2ForSequenceClassificationik  c                 6  > [         TU ]  U5        UR                  U l        [        U5      U l        [
        R                  " UR                  5      U l        [
        R                  " UR                  S-  UR                  5      U l        U R                  5         g )Nr
   r%   r&   
num_labelsrI  r>  r   r9   r:   r;   ro   r)   
classifierr  r@   s     rD   r&   ,LayoutLMv2ForSequenceClassification.__init__t  sn      ++)&1zz&"<"<=))F$6$6$:F<M<MN 	rF   c                 B    U R                   R                  R                  $ r   r>  r  r+   r  s    rD   r  8LayoutLMv2ForSequenceClassification.get_input_embeddings~      ))999rF   r  rM   r  r   r  r!   r   r  labelsr   r3  r4  r   c                 h   Ub  UOU R                   R                  nUb  Ub  [        S5      eUb"  U R                  X5        UR	                  5       nO"Ub  UR	                  5       SS nO[        S5      eUb  UR
                  OUR
                  n[        U5      nU R                   R                  S   U R                   R                  S   -  US'   [        R                  " U5      n[        U5      nUS==   US   -  ss'   [        R                  " U5      nU R                  R                  U R                   R                  X.U5      n[        R                  " SUS   [        R                  US9R                  US   S5      nU R                  R                  UUUS9nU R                  UUUUUUUUU
UUS	9nUb  UR	                  5       nOUR	                  5       SS nUS   nUS   SS2SU24   US   SS2US24   nnUSS2SSS24   nUR!                  SS
9nUR!                  SS
9n[        R"                  " UUU/SS
9nU R%                  U5      nU R'                  U5      nSnU	Gb  U R                   R(                  c  U R*                  S:X  a  SU R                   l        OoU R*                  S:  aN  U	R,                  [        R                  :X  d  U	R,                  [        R.                  :X  a  SU R                   l        OSU R                   l        U R                   R(                  S:X  aJ  [1        5       nU R*                  S:X  a&  U" UR3                  5       U	R3                  5       5      nOU" UU	5      nOU R                   R(                  S:X  a=  [5        5       nU" UR7                  SU R*                  5      U	R7                  S5      5      nO-U R                   R(                  S:X  a  [9        5       nU" UU	5      nU(       d  U4USS -   nUb  U4U-   $ U$ [;        UUUR<                  UR>                  S9$ )a  
input_ids (`torch.LongTensor` of shape `batch_size, sequence_length`):
    Indices of input sequence tokens in the vocabulary.

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

    [What are input IDs?](../glossary#input-ids)
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.
image (`torch.FloatTensor` of shape `(batch_size, num_channels, height, width)` or `detectron.structures.ImageList` whose `tensors` is of shape `(batch_size, num_channels, height, width)`):
    Batch of document images.
token_type_ids (`torch.LongTensor` of shape `batch_size, sequence_length`, *optional*):
    Segment token indices to indicate first and second portions of the inputs. Indices are selected in `[0,
    1]`:

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

    [What are token type IDs?](../glossary#token-type-ids)
position_ids (`torch.LongTensor` of shape `batch_size, sequence_length`, *optional*):
    Indices of positions of each input sequence tokens in the position embeddings. Selected in the range `[0,
    config.max_position_embeddings - 1]`.

    [What are position IDs?](../glossary#position-ids)
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).

Example:

```python
>>> from transformers import AutoProcessor, LayoutLMv2ForSequenceClassification, set_seed
>>> from PIL import Image
>>> import torch
>>> from datasets import load_dataset

>>> set_seed(0)

>>> dataset = load_dataset("aharley/rvl_cdip", split="train", streaming=True, trust_remote_code=True)
>>> data = next(iter(dataset))
>>> image = data["image"].convert("RGB")

>>> processor = AutoProcessor.from_pretrained("microsoft/layoutlmv2-base-uncased")
>>> model = LayoutLMv2ForSequenceClassification.from_pretrained(
...     "microsoft/layoutlmv2-base-uncased", num_labels=dataset.info.features["label"].num_classes
... )

>>> encoding = processor(image, return_tensors="pt")
>>> sequence_label = torch.tensor([data["label"]])

>>> outputs = model(**encoding, labels=sequence_label)

>>> loss, logits = outputs.loss, outputs.logits
>>> predicted_idx = logits.argmax(dim=-1).item()
>>> predicted_answer = dataset.info.features["label"].names[4]
>>> predicted_idx, predicted_answer  # results are not good without further fine-tuning
(7, 'advertisement')
```
Nr  r"   r  r   r   rT  r  r  rM   r  r   r  r!   r   r  r   r3  r4  rI   
regressionsingle_label_classificationmulti_label_classificationrH   losslogitsr   r-  ) rB   r  rh   %warn_if_padding_and_no_attention_maskr{   rU  r  r  r=   r  r>  r  r>   r   r  r  r@  rL   r;   r  problem_typer  r   rj   r	   squeezer   r|   r   r   r   r-  )rA   r  rM   r  r   r  r!   r   r  r	  r   r3  r4  r  rU  r  r  r  r  initial_image_embeddingsr   r  r  final_image_embeddingscls_final_outputpooled_initial_image_embeddingspooled_final_image_embeddingsr  r  loss_fctr   s                                  rD   r   +LayoutLMv2ForSequenceClassification.forward  s   b &1%<k$++B]B] ]%>cdd"66yQ#..*K&',,.s3KTUU%.%:!!@T@TK(++>>qADKKDhDhijDkkQzz,/;'A,q/)jj-oo77KK00$
 $ll1l1oUZZX^_ffNA
 $(??#G#G, $H $
  //))%'/!5# " 
  #..*K',,.s3K ^
29!*Q^2LgVWjYZ\f\gYgNh/*1a73 +C*G*GA*G*N'(>(C(C(C(J%))>@]^de
 ,,71{{''/??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,./Y,F)-)9TGf$EvE'!//))	
 	
rF   r  r;   r>  r  NNNNNNNNNNNN)rV   rW   rX   rY   r&   r  r   r   r=   r  r  r   r   r   r   r   r[   r\   r]   s   @rD   r  r  k  sP   :  15+/-16:59371559-1,0/3&*s
E,,-s
 u''(s
 ))*	s

 !!2!23s
 !!1!12s
 u//0s
 E--.s
   1 12s
 ))*s
 $D>s
 'tns
 d^s
 
u..	/s
 s
rF   r  a  
    LayoutLMv2 Model with a token classification head on top (a linear layer on top of the text part of the hidden
    states) e.g. for sequence labeling (information extraction) tasks such as
    [FUNSD](https://guillaumejaume.github.io/FUNSD/), [SROIE](https://rrc.cvc.uab.es/?ch=13),
    [CORD](https://github.com/clovaai/cord) and [Kleister-NDA](https://github.com/applicaai/kleister-nda).
    c                     ^  \ rS rSrU 4S jrS r\            SS\\R                     S\\R                     S\\R                     S\\R                     S\\R                     S	\\R                     S
\\R                     S\\R                     S\\R                     S\\   S\\   S\\   S\\\4   4S jj5       rSrU =r$ ) LayoutLMv2ForTokenClassificationi8  c                 0  > [         TU ]  U5        UR                  U l        [        U5      U l        [
        R                  " UR                  5      U l        [
        R                  " UR                  UR                  5      U l        U R                  5         g r   r  r@   s     rD   r&   )LayoutLMv2ForTokenClassification.__init__A  si      ++)&1zz&"<"<=))F$6$68I8IJ 	rF   c                 B    U R                   R                  R                  $ r   r  r  s    rD   r  5LayoutLMv2ForTokenClassification.get_input_embeddingsK  r  rF   r  rM   r  r   r  r!   r   r  r	  r   r3  r4  r   c                    Ub  UOU R                   R                  nU R                  UUUUUUUUU
UUS9nUb  UR                  5       nOUR                  5       SS nUS   nUS   SS2SU24   nU R	                  U5      nU R                  U5      nSnU	b<  [        5       nU" UR                  SU R                  5      U	R                  S5      5      nU(       d  U4USS -   nUb  U4U-   $ U$ [        UUUR                  UR                  S9$ )a  
input_ids (`torch.LongTensor` of shape `batch_size, sequence_length`):
    Indices of input sequence tokens in the vocabulary.

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

    [What are input IDs?](../glossary#input-ids)
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.
image (`torch.FloatTensor` of shape `(batch_size, num_channels, height, width)` or `detectron.structures.ImageList` whose `tensors` is of shape `(batch_size, num_channels, height, width)`):
    Batch of document images.
token_type_ids (`torch.LongTensor` of shape `batch_size, sequence_length`, *optional*):
    Segment token indices to indicate first and second portions of the inputs. Indices are selected in `[0,
    1]`:

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

    [What are token type IDs?](../glossary#token-type-ids)
position_ids (`torch.LongTensor` of shape `batch_size, sequence_length`, *optional*):
    Indices of positions of each input sequence tokens in the position embeddings. Selected in the range `[0,
    config.max_position_embeddings - 1]`.

    [What are position IDs?](../glossary#position-ids)
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]`.

Example:

```python
>>> from transformers import AutoProcessor, LayoutLMv2ForTokenClassification, set_seed
>>> from PIL import Image
>>> from datasets import load_dataset

>>> set_seed(0)

>>> datasets = load_dataset("nielsr/funsd", split="test", trust_remote_code=True)
>>> labels = datasets.features["ner_tags"].feature.names
>>> id2label = {v: k for v, k in enumerate(labels)}

>>> processor = AutoProcessor.from_pretrained("microsoft/layoutlmv2-base-uncased", revision="no_ocr")
>>> model = LayoutLMv2ForTokenClassification.from_pretrained(
...     "microsoft/layoutlmv2-base-uncased", num_labels=len(labels)
... )

>>> data = datasets[0]
>>> image = Image.open(data["image_path"]).convert("RGB")
>>> words = data["words"]
>>> boxes = data["bboxes"]  # make sure to normalize your bounding boxes
>>> word_labels = data["ner_tags"]
>>> encoding = processor(
...     image,
...     words,
...     boxes=boxes,
...     word_labels=word_labels,
...     padding="max_length",
...     truncation=True,
...     return_tensors="pt",
... )

>>> outputs = model(**encoding)
>>> logits, loss = outputs.logits, outputs.loss

>>> predicted_token_class_ids = logits.argmax(-1)
>>> predicted_tokens_classes = [id2label[t.item()] for t in predicted_token_class_ids[0]]
>>> predicted_tokens_classes[:5]  # results are not good without further fine-tuning
['I-HEADER', 'I-HEADER', 'I-QUESTION', 'I-HEADER', 'I-QUESTION']
```
Nr  r"   r   r   rH   r  )rB   r  r>  r{   r;   r  r   r|   r  r   r   r-  )rA   r  rM   r  r   r  r!   r   r  r	  r   r3  r4  r   r  r  r  r  r  r  r   s                        rD   r   (LayoutLMv2ForTokenClassification.forwardN  s:   t &1%<k$++B]B]//))%'/!5# " 
  #..*K',,.s3K ^
!!*Q^4,,71')HFKKDOO<fkk"oNDY,F)-)9TGf$EvE$!//))	
 	
rF   r  r  )rV   rW   rX   rY   r&   r  r   r   r=   r  r  r   r   r   r   r   r[   r\   r]   s   @rD   r  r  8  sP   :  15+/-16:59371559-1,0/3&*A
E,,-A
 u''(A
 ))*	A

 !!2!23A
 !!1!12A
 u//0A
 E--.A
   1 12A
 ))*A
 $D>A
 'tnA
 d^A
 
u++	,A
 A
rF   r  c                      ^  \ rS rSrSU 4S jjrS r\             SS\\R                     S\\R                     S\\R                     S\\R                     S\\R                     S	\\R                     S
\\R                     S\\R                     S\\R                     S\\R                     S\\   S\\   S\\   S\\\4   4S jj5       rSrU =r$ )LayoutLMv2ForQuestionAnsweringi  c                    > [         TU ]  U5        UR                  U l        X!l        [	        U5      U l        [        R                  " UR                  UR                  5      U l	        U R                  5         g)z}
has_visual_segment_embedding (`bool`, *optional*, defaults to `True`):
    Whether or not to add visual segment embeddings.
N)r%   r&   r  r  rI  r>  r   ro   r)   
qa_outputsr  )rA   rB   r  rC   s      rD   r&   'LayoutLMv2ForQuestionAnswering.__init__  s[    
 	  ++.J+)&1))F$6$68I8IJ 	rF   c                 B    U R                   R                  R                  $ r   r  r  s    rD   r  3LayoutLMv2ForQuestionAnswering.get_input_embeddings  r  rF   r  rM   r  r   r  r!   r   r  start_positionsend_positionsr   r3  r4  r   c                    Ub  UOU R                   R                  nU R                  UUUUUUUUUUUS9nUb  UR                  5       nOUR                  5       SS nUS   nUS   SS2SU24   nU R	                  U5      nUR                  SSS9u  nnUR                  S5      R                  5       nUR                  S5      R                  5       nSnU	b  U
b  [        U	R                  5       5      S:  a  U	R                  S5      n	[        U
R                  5       5      S:  a  U
R                  S5      n
UR                  S5      nU	R                  SU5      n	U
R                  SU5      n
[        US9nU" UU	5      nU" UU
5      nUU-   S-  nU(       d  UU4USS -   nUb  U4U-   $ U$ [        UUUUR                  UR                  S	9$ )
u  
input_ids (`torch.LongTensor` of shape `batch_size, sequence_length`):
    Indices of input sequence tokens in the vocabulary.

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

    [What are input IDs?](../glossary#input-ids)
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.
image (`torch.FloatTensor` of shape `(batch_size, num_channels, height, width)` or `detectron.structures.ImageList` whose `tensors` is of shape `(batch_size, num_channels, height, width)`):
    Batch of document images.
token_type_ids (`torch.LongTensor` of shape `batch_size, sequence_length`, *optional*):
    Segment token indices to indicate first and second portions of the inputs. Indices are selected in `[0,
    1]`:

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

    [What are token type IDs?](../glossary#token-type-ids)
position_ids (`torch.LongTensor` of shape `batch_size, sequence_length`, *optional*):
    Indices of positions of each input sequence tokens in the position embeddings. Selected in the range `[0,
    config.max_position_embeddings - 1]`.

    [What are position IDs?](../glossary#position-ids)

Example:

In this example below, we give the LayoutLMv2 model an image (of texts) and ask it a question. 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 AutoProcessor, LayoutLMv2ForQuestionAnswering, set_seed
>>> import torch
>>> from PIL import Image
>>> from datasets import load_dataset

>>> set_seed(0)
>>> processor = AutoProcessor.from_pretrained("microsoft/layoutlmv2-base-uncased")
>>> model = LayoutLMv2ForQuestionAnswering.from_pretrained("microsoft/layoutlmv2-base-uncased")

>>> dataset = load_dataset("hf-internal-testing/fixtures_docvqa", trust_remote_code=True)
>>> image_path = dataset["test"][0]["file"]
>>> image = Image.open(image_path).convert("RGB")
>>> question = "When is coffee break?"
>>> encoding = processor(image, question, return_tensors="pt")

>>> outputs = model(**encoding)
>>> predicted_start_idx = outputs.start_logits.argmax(-1).item()
>>> predicted_end_idx = outputs.end_logits.argmax(-1).item()
>>> predicted_start_idx, predicted_end_idx
(30, 191)

>>> predicted_answer_tokens = encoding.input_ids.squeeze()[predicted_start_idx : predicted_end_idx + 1]
>>> predicted_answer = processor.tokenizer.decode(predicted_answer_tokens)
>>> predicted_answer  # results are not good without further fine-tuning
'44 a. m. to 12 : 25 p. m. 12 : 25 to 12 : 58 p. m. 12 : 58 to 4 : 00 p. m. 2 : 00 to 5 : 00 p. m. coffee break coffee will be served for men and women in the lobby adjacent to exhibit area. please move into exhibit area. ( exhibits open ) trrf general session ( part | ) presiding : lee a. waller trrf vice president “ introductory remarks ” lee a. waller, trrf vice presi - dent individual interviews with trrf public board members and sci - entific advisory council mem - bers conducted by trrf treasurer philip g. kuehn to get answers which the public refrigerated warehousing industry is looking for. plus questions from'
```

```python
>>> target_start_index = torch.tensor([7])
>>> target_end_index = torch.tensor([14])
>>> outputs = model(**encoding, start_positions=target_start_index, end_positions=target_end_index)
>>> predicted_answer_span_start = outputs.start_logits.argmax(-1).item()
>>> predicted_answer_span_end = outputs.end_logits.argmax(-1).item()
>>> predicted_answer_span_start, predicted_answer_span_end
(30, 191)
```
Nr  r"   r   r   rI   )ignore_indexrH   )r  start_logits
end_logitsr   r-  )rB   r  r>  r{   r)  splitr  r   rw  clampr   r   r   r-  )rA   r  rM   r  r   r  r!   r   r  r-  r.  r   r3  r4  r   r  r  r  r  r1  r2  
total_lossignored_indexr  
start_lossend_lossr   s                              rD   r   &LayoutLMv2ForQuestionAnswering.forward  s   t &1%<k$++B]B]//))%'/!5# " 
  #..*K',,.s3K ^
!!*Q^4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"J/'!"+=F/9/EZMF*Q6Q+%!!//))
 	
rF   )r>  r  r)  )T)NNNNNNNNNNNNN)rV   rW   rX   rY   r&   r  r   r   r=   r  r  r   r   r   r   r   r[   r\   r]   s   @rD   r'  r'    si   :  15+/-16:593715596:48,0/3&*R
E,,-R
 u''(R
 ))*	R

 !!2!23R
 !!1!12R
 u//0R
 E--.R
   1 12R
 "%"2"23R
   0 01R
 $D>R
 'tnR
 d^R
 
u22	3R
 R
rF   r'  )r'  r  r  r   rI  r=  )T       r   )=rZ   r   typingr   r   r   r=   torch.utils.checkpointr   torch.nnr   r   r	   activationsr   modeling_outputsr   r   r   r   r   modeling_utilsr   pytorch_utilsr   utilsr   r   r   r   configuration_layoutlmv2r   r[  detectron2.modelingr   Module_load_from_state_dictr\  
batch_normr]  
get_loggerrV   r|  r   r_   r   r   r   r   r   r  r  r=  rd  ri  r  rI  r  r  r'  __all__r'  rF   rD   <module>rK     s      ) )    A A !  . 6 X X 6 6 LQ88??KpKpJ  22H			H	%,+299 ,+^Zbii Zz")) 8299 RYY  ryy (bii (V)XA
		 A
H j j j80?jryy ?jDryy  ~
/ ~
 ~
B B
*C B
B
J P
'@ P
P
f e
%> e
 e
PrF   