Ë
    T^(h_í  ã                   ó€  — d Z ddlZddlZddlmZmZmZ ddlZddlm	Z	 ddl
m	c mZ ddlZddlmZmZ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mZmZm Z m!Z! ddl"m#Z#  ejH                  e%«      Z&dZ'dZ(dZ)dZ* G d„ de	jV                  «      Z, G d„ de	jV                  «      Z- G d„ de«      Z. G d„ de	jV                  «      Z/ G d„ de	jV                  «      Z0 G d„ de	jV                  «      Z1 G d„ de	jV                  «      Z2 G d„ d e	jV                  «      Z3 G d!„ d"e	jV                  «      Z4 G d#„ d$e	jV                  «      Z5 ed%e(«       G d&„ d'e.«      «       Z6 G d(„ d)e	jV                  «      Z7 ed*e(«       G d+„ d,e.«      «       Z8 ed-e(«       G d.„ d/e.«      «       Z9 ed0e(«       G d1„ d2e.«      «       Z:g d3¢Z;y)4zPyTorch LayoutLMv3 model.é    N)ÚOptionalÚTupleÚUnion)ÚBCEWithLogitsLossÚCrossEntropyLossÚMSELossé   )ÚACT2FN)ÚBaseModelOutputÚQuestionAnsweringModelOutputÚSequenceClassifierOutputÚTokenClassifierOutput)ÚPreTrainedModel)Úapply_chunking_to_forward)Úadd_start_docstringsÚ%add_start_docstrings_to_model_forwardÚloggingÚreplace_return_docstringsÚ	torch_inté   )ÚLayoutLMv3Configr   aM  
    This model is a PyTorch [torch.nn.Module](https://pytorch.org/docs/stable/nn.html#torch.nn.Module) sub-class. Use
    it as a regular PyTorch Module and refer to the PyTorch documentation for all matter related to general usage and
    behavior.

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

            Note that `sequence_length = token_sequence_length + patch_sequence_length + 1` where `1` is for [CLS]
            token. See `pixel_values` for `patch_sequence_length`.

            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 `({0}, 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.

            Note that `sequence_length = token_sequence_length + patch_sequence_length + 1` where `1` is for [CLS]
            token. See `pixel_values` for `patch_sequence_length`.

        pixel_values (`torch.FloatTensor` of shape `(batch_size, num_channels, height, width)`):
            Batch of document images. Each image is divided into patches of shape `(num_channels, config.patch_size,
            config.patch_size)` and the total number of patches (=`patch_sequence_length`) equals to `((height /
            config.patch_size) * (width / config.patch_size))`.

        attention_mask (`torch.FloatTensor` of shape `({0})`, *optional*):
            Mask to avoid performing attention on padding token indices. Mask values selected in `[0, 1]`:

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

            Note that `sequence_length = token_sequence_length + patch_sequence_length + 1` where `1` is for [CLS]
            token. See `pixel_values` for `patch_sequence_length`.

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

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

            Note that `sequence_length = token_sequence_length + patch_sequence_length + 1` where `1` is for [CLS]
            token. See `pixel_values` for `patch_sequence_length`.

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

            Note that `sequence_length = token_sequence_length + patch_sequence_length + 1` where `1` is for [CLS]
            token. See `pixel_values` for `patch_sequence_length`.

            [What are position IDs?](../glossary#position-ids)
        head_mask (`torch.FloatTensor` of shape `(num_heads,)` or `(num_layers, num_heads)`, *optional*):
            Mask to nullify selected heads of the self-attention modules. Mask values selected in `[0, 1]`:

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

        inputs_embeds (`torch.FloatTensor` of shape `({0}, hidden_size)`, *optional*):
            Optionally, instead of passing `input_ids` you can choose to directly pass an embedded representation. This
            is useful if you want more control over how to convert *input_ids* indices into associated vectors than the
            model's internal embedding lookup matrix.
        output_attentions (`bool`, *optional*):
            Whether or not to return the attentions tensors of all attention layers. See `attentions` under returned
            tensors for more detail.
        output_hidden_states (`bool`, *optional*):
            Whether or not to return the hidden states of all layers. See `hidden_states` under returned tensors for
            more detail.
        return_dict (`bool`, *optional*):
            Whether or not to return a [`~utils.ModelOutput`] instead of a plain tuple.
aˆ  
    Args:
        input_ids (`torch.LongTensor` of shape `({0})`):
            Indices of input sequence tokens in the vocabulary.

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

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

        bbox (`torch.LongTensor` of shape `({0}, 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.

        pixel_values (`torch.FloatTensor` of shape `(batch_size, num_channels, height, width)`):
            Batch of document images. Each image is divided into patches of shape `(num_channels, config.patch_size,
            config.patch_size)` and the total number of patches (=`patch_sequence_length`) equals to `((height /
            config.patch_size) * (width / config.patch_size))`.

        attention_mask (`torch.FloatTensor` of shape `({0})`, *optional*):
            Mask to avoid performing attention on padding token indices. Mask values selected in `[0, 1]`:

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

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

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

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

            [What are position IDs?](../glossary#position-ids)
        head_mask (`torch.FloatTensor` of shape `(num_heads,)` or `(num_layers, num_heads)`, *optional*):
            Mask to nullify selected heads of the self-attention modules. Mask values selected in `[0, 1]`:

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

        inputs_embeds (`torch.FloatTensor` of shape `({0}, hidden_size)`, *optional*):
            Optionally, instead of passing `input_ids` you can choose to directly pass an embedded representation. This
            is useful if you want more control over how to convert *input_ids* indices into associated vectors than the
            model's internal embedding lookup matrix.
        output_attentions (`bool`, *optional*):
            Whether or not to return the attentions tensors of all attention layers. See `attentions` under returned
            tensors for more detail.
        output_hidden_states (`bool`, *optional*):
            Whether or not to return the hidden states of all layers. See `hidden_states` under returned tensors for
            more detail.
        return_dict (`bool`, *optional*):
            Whether or not to return a [`~utils.ModelOutput`] instead of a plain tuple.
c                   ó*   ‡ — e Zd ZdZˆ fd„Zdd„Zˆ xZS )ÚLayoutLMv3PatchEmbeddingsz„LayoutLMv3 image (patch) embeddings. This class also automatically interpolates the position embeddings for varying
    image sizes.c                 ó  •— t         ‰| �  «        t        |j                  t        j
                  j                  «      r|j                  n|j                  |j                  f}t        |j                  t        j
                  j                  «      r|j                  n|j                  |j                  f}|d   |d   z  |d   |d   z  f| _        t        j                  |j                  |j                  ||¬«      | _        y )Nr   r   )Úkernel_sizeÚstride)ÚsuperÚ__init__Ú
isinstanceÚ
input_sizeÚcollectionsÚabcÚIterableÚ
patch_sizeÚpatch_shapeÚnnÚConv2dÚnum_channelsÚhidden_sizeÚproj)ÚselfÚconfigÚ
image_sizer$   Ú	__class__s       €úp/var/www/skyplay_api_hub/venv/lib/python3.12/site-packages/transformers/models/layoutlmv3/modeling_layoutlmv3.pyr   z"LayoutLMv3PatchEmbeddings.__init__Ì   sÜ   ø€ Ü‰ÑÔô ˜&×+Ñ+¬[¯_©_×-EÑ-EÔFð ×Òà×#Ñ# V×%6Ñ%6Ð7ð 	ô ˜&×+Ñ+¬[¯_©_×-EÑ-EÔFð ×Òà×#Ñ# V×%6Ñ%6Ð7ð 	ð
 ' q™M¨Z¸©]Ñ:¸JÀq¹MÈZÐXYÉ]Ñ<ZÐ[ˆÔÜ—I‘I˜f×1Ñ1°6×3EÑ3EÐS]ÐfpÔqˆ�	ó    c                 ól  — | j                  |«      }|�|j                  d| j                  d   | j                  d   d«      }|j                  dddd«      }|j                  d   |j                  d   }}t        j                  |||fd¬«      }||z   }|j                  d«      j                  dd«      }|S )Nr   r   éÿÿÿÿr	   é   Úbicubic)ÚsizeÚmode)	r*   Úviewr%   ÚpermuteÚshapeÚFÚinterpolateÚflattenÚ	transpose)r+   Úpixel_valuesÚposition_embeddingÚ
embeddingsÚpatch_heightÚpatch_widths         r/   Úforwardz!LayoutLMv3PatchEmbeddings.forwardÜ   sÅ   € Ø—Y‘Y˜|Ó,ˆ
àÐ)à!3×!8Ñ!8¸¸D×<LÑ<LÈQÑ<OÐQU×QaÑQaÐbcÑQdÐfhÓ!iÐØ!3×!;Ñ!;¸A¸qÀ!ÀQÓ!GÐØ(2×(8Ñ(8¸Ñ(;¸Z×=MÑ=MÈaÑ=P˜+ˆLÜ!"§¡Ð/AÈÐWbÐHcÐjsÔ!tÐØ#Ð&8Ñ8ˆJà×'Ñ'¨Ó*×4Ñ4°Q¸Ó:ˆ
ØÐr0   ©N©Ú__name__Ú
__module__Ú__qualname__Ú__doc__r   rC   Ú__classcell__©r.   s   @r/   r   r   È   s   ø„ ñôr÷ r0   r   c                   óF   ‡ — e Zd ZdZˆ fd„Zd„ Zd„ Zd„ Z	 	 	 	 	 dd„Zˆ xZ	S )ÚLayoutLMv3TextEmbeddingszm
    LayoutLMv3 text embeddings. Same as `RobertaEmbeddings` but with added spatial (layout) embeddings.
    c                 ó.  •— t         ‰| �  «        t        j                  |j                  |j
                  |j                  ¬«      | _        t        j                  |j                  |j
                  «      | _	        t        j                  |j
                  |j                  ¬«      | _
        t        j                  |j                  «      | _        | j                  dt!        j"                  |j$                  «      j'                  d«      d¬«       |j                  | _        t        j                  |j$                  |j
                  | j(                  ¬«      | _        t        j                  |j,                  |j.                  «      | _        t        j                  |j,                  |j.                  «      | _        t        j                  |j,                  |j4                  «      | _        t        j                  |j,                  |j4                  «      | _        y )N)Úpadding_idx©ÚepsÚposition_ids)r   r2   F)Ú
persistent)r   r   r&   Ú	EmbeddingÚ
vocab_sizer)   Úpad_token_idÚword_embeddingsÚtype_vocab_sizeÚtoken_type_embeddingsÚ	LayerNormÚlayer_norm_epsÚDropoutÚhidden_dropout_probÚdropoutÚregister_bufferÚtorchÚarangeÚmax_position_embeddingsÚexpandrO   Úposition_embeddingsÚmax_2d_position_embeddingsÚcoordinate_sizeÚx_position_embeddingsÚy_position_embeddingsÚ
shape_sizeÚh_position_embeddingsÚw_position_embeddings©r+   r,   r.   s     €r/   r   z!LayoutLMv3TextEmbeddings.__init__ð   s}  ø€ Ü‰ÑÔÜ!Ÿ|™|¨F×,=Ñ,=¸v×?QÑ?QÐ_e×_rÑ_rÔsˆÔÜ%'§\¡\°&×2HÑ2HÈ&×J\ÑJ\Ó%]ˆÔ"äŸ™ f×&8Ñ&8¸f×>SÑ>SÔTˆŒÜ—z‘z &×"<Ñ"<Ó=ˆŒð 	×ÑØœEŸL™L¨×)GÑ)GÓH×OÑOÐPWÓXÐejð 	ô 	
ð "×.Ñ.ˆÔÜ#%§<¡<Ø×*Ñ*¨F×,>Ñ,>ÈD×L\ÑL\ô$
ˆÔ ô &(§\¡\°&×2SÑ2SÐU[×UkÑUkÓ%lˆÔ"Ü%'§\¡\°&×2SÑ2SÐU[×UkÑUkÓ%lˆÔ"Ü%'§\¡\°&×2SÑ2SÐU[×UfÑUfÓ%gˆÔ"Ü%'§\¡\°&×2SÑ2SÐU[×UfÑUfÓ%gˆÕ"r0   c           	      óH  — 	 | 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                  t	        j
                  |d d …d d …df   |d d …d d …df   z
  dd«      «      }| j                  t	        j
                  |d d …d d …df   |d d …d d …df   z
  dd«      «      }t	        j                  ||||||gd¬«      }	|	S # t        $ r}t        d«      |‚d }~ww xY w)	Nr   r   r3   r	   z;The `bbox` coordinate values should be within 0-1000 range.iÿ  r2   ©Údim)rg   rh   Ú
IndexErrorrj   r`   Úcliprk   Úcat)
r+   ÚbboxÚleft_position_embeddingsÚupper_position_embeddingsÚright_position_embeddingsÚlower_position_embeddingsÚerj   rk   Úspatial_position_embeddingss
             r/   Ú%calculate_spatial_position_embeddingsz>LayoutLMv3TextEmbeddings.calculate_spatial_position_embeddings  sN  € ð	cØ'+×'AÑ'AÀ$ÂqÊ!ÈQÀwÁ-Ó'PÐ$Ø(,×(BÑ(BÀ4ÊÊ1ÈaÈÁ=Ó(QÐ%Ø(,×(BÑ(BÀ4ÊÊ1ÈaÈÁ=Ó(QÐ%Ø(,×(BÑ(BÀ4ÊÊ1ÈaÈÁ=Ó(QÐ%ð !%× :Ñ :¼5¿:¹:ÀdÊ1ÊaÐQRÈ7ÁmÐVZÒ[\Ò^_ÐabÐ[bÑVcÑFcÐefÐhlÓ;mÓ nÐØ $× :Ñ :¼5¿:¹:ÀdÊ1ÊaÐQRÈ7ÁmÐVZÒ[\Ò^_ÐabÐ[bÑVcÑFcÐefÐhlÓ;mÓ nÐô ',§i¡ià(Ø)Ø)Ø)Ø%Ø%ðð ô
'
Ð#ð +Ð*øô% ò 	cÜÐZÓ[ÐabÐbûð	cús   ‚A,D Ä	D!ÄDÄD!c                 ó¸   — |j                  |«      j                  «       }t        j                  |d¬«      j	                  |«      |z  }|j                  «       |z   S )zÐ
        Replace non-padding symbols with their position numbers. Position numbers begin at padding_idx+1. Padding
        symbols are ignored. This is modified from fairseq's `utils.make_positions`.
        r   rn   )ÚneÚintr`   ÚcumsumÚtype_asÚlong)r+   Ú	input_idsrO   ÚmaskÚincremental_indicess        r/   Ú"create_position_ids_from_input_idsz;LayoutLMv3TextEmbeddings.create_position_ids_from_input_ids!  sP   € ð �|‰|˜KÓ(×,Ñ,Ó.ˆÜ$Ÿ|™|¨D°aÔ8×@Ñ@ÀÓFÈ$ÑNÐØ"×'Ñ'Ó)¨KÑ7Ð7r0   c                 ó  — |j                  «       dd }|d   }t        j                  | j                  dz   || j                  z   dz   t        j                  |j
                  ¬«      }|j                  d«      j                  |«      S )z�
        We are provided embeddings directly. We cannot infer which are padded so just generate sequential position ids.
        Nr2   r   ©ÚdtypeÚdevicer   )r5   r`   ra   rO   r€   rˆ   Ú	unsqueezerc   )r+   Úinputs_embedsÚinput_shapeÚsequence_lengthrR   s        r/   Ú&create_position_ids_from_inputs_embedsz?LayoutLMv3TextEmbeddings.create_position_ids_from_inputs_embeds+  s€   € ð $×(Ñ(Ó*¨3¨BÐ/ˆØ% a™.ˆä—|‘|Ø×Ñ˜qÑ  /°D×4DÑ4DÑ"DÀqÑ"HÔPU×PZÑPZÐcp×cwÑcwô
ˆð ×%Ñ% aÓ(×/Ñ/°Ó<Ð<r0   c                 óN  — |€I|�6| j                  || j                  «      j                  |j                  «      }n| j	                  |«      }|�|j                  «       }n|j                  «       d d }|€:t        j                  |t        j                  | j                  j                  ¬«      }|€| j                  |«      }| j                  |«      }||z   }| j                  |«      }	||	z  }| j                  |«      }
||
z   }| j                  |«      }| j                  |«      }|S )Nr2   r†   )r„   rO   Útorˆ   r�   r5   r`   Úzerosr€   rR   rW   rY   rd   rz   rZ   r^   )r+   r�   rs   Útoken_type_idsrR   rŠ   r‹   rY   r@   rd   ry   s              r/   rC   z LayoutLMv3TextEmbeddings.forward7  s+  € ð ÐØÐ$à#×FÑFÀyÐRV×RbÑRbÓc×fÑfØ×$Ñ$ó ‘ð  $×JÑJÈ=ÓY�àÐ Ø#Ÿ.™.Ó*‰Kà'×,Ñ,Ó.¨s°Ð3ˆKàÐ!Ü"Ÿ[™[¨¼E¿J¹JÈt×O`ÑO`×OgÑOgÔhˆNàÐ Ø ×0Ñ0°Ó;ˆMØ $× :Ñ :¸>Ó JÐà"Ð%:Ñ:ˆ
Ø"×6Ñ6°|ÓDÐØÐ)Ñ)ˆ
à&*×&PÑ&PÐQUÓ&VÐ#àÐ"=Ñ=ˆ
à—^‘^ JÓ/ˆ
Ø—\‘\ *Ó-ˆ
ØÐr0   )NNNNN)
rF   rG   rH   rI   r   rz   r„   r�   rC   rJ   rK   s   @r/   rM   rM   ë   s3   ø„ ñôhò.+ò48ò
=ð ØØØØ÷'r0   rM   c                   ó   — e Zd ZdZeZdZd„ Zy)ÚLayoutLMv3PreTrainedModelz†
    An abstract class to handle weights initialization and a simple interface for downloading and loading pretrained
    models.
    Ú
layoutlmv3c                 ó  — t        |t        j                  t        j                  f«      rm|j                  j
                  j                  d| j                  j                  ¬«       |j                  �%|j                  j
                  j                  «        yyt        |t        j                  «      rz|j                  j
                  j                  d| j                  j                  ¬«       |j                  �2|j                  j
                  |j                     j                  «        yyt        |t        j                  «      rJ|j                  j
                  j                  «        |j                  j
                  j                  d«       yt        |t        «      r`| j                  j                   rI|j"                  j
                  j                  «        |j$                  j
                  j                  «        yyy)zInitialize the weightsç        )ÚmeanÚstdNg      ð?)r   r&   ÚLinearr'   ÚweightÚdataÚnormal_r,   Úinitializer_rangeÚbiasÚzero_rT   rO   rZ   Úfill_ÚLayoutLMv3ModelÚvisual_embedÚ	cls_tokenÚ	pos_embed)r+   Úmodules     r/   Ú_init_weightsz'LayoutLMv3PreTrainedModel._init_weightsj  s[  € ä�fœrŸy™y¬"¯)©)Ð4Ô5ð �M‰M×Ñ×&Ñ&¨C°T·[±[×5RÑ5RÐ&ÔSØ�{‰{Ð&Ø—‘× Ñ ×&Ñ&Õ(ð 'ä˜¤§¡Ô-Ø�M‰M×Ñ×&Ñ&¨C°T·[±[×5RÑ5RÐ&ÔSØ×!Ñ!Ð-Ø—‘×"Ñ" 6×#5Ñ#5Ñ6×<Ñ<Õ>ð .ä˜¤§¡Ô-Ø�K‰K×Ñ×"Ñ"Ô$Ø�M‰M×Ñ×$Ñ$ SÕ)Ü˜¤Ô0Ø�{‰{×'Ò'Ø× Ñ ×%Ñ%×+Ñ+Ô-Ø× Ñ ×%Ñ%×+Ñ+Õ-ð (ð 1r0   N)rF   rG   rH   rI   r   Úconfig_classÚbase_model_prefixr¦   © r0   r/   r“   r“   a  s   „ ñð
 $€LØ$Ðó.r0   r“   c                   ó>   ‡ — e Zd Zˆ fd„Zd„ Zdd„Z	 	 	 	 	 dd„Zˆ xZS )ÚLayoutLMv3SelfAttentionc                 ó  •— 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$                  | _        y )Nr   Úembedding_sizezThe hidden size (z6) is not a multiple of the number of attention heads (ú))r   r   r)   Únum_attention_headsÚhasattrÚ
ValueErrorr}   Úattention_head_sizeÚall_head_sizer&   r™   ÚqueryÚkeyÚvaluer\   Úattention_probs_dropout_probr^   Úhas_relative_attention_biasÚhas_spatial_attention_biasrl   s     €r/   r   z LayoutLMv3SelfAttention.__init__€  s8  ø€ Ü‰ÑÔØ×Ñ × :Ñ :Ñ:¸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ˆŒØ+1×+MÑ+MˆÔ(Ø*0×*KÑ*KˆÕ'r0   c                 ó    — |j                  «       d d | j                  | j                  fz   } |j                  |Ž }|j	                  dddd«      S )Nr2   r   r3   r   r	   )r5   r¯   r²   r7   r8   )r+   ÚxÚnew_x_shapes      r/   Útranspose_for_scoresz,LayoutLMv3SelfAttention.transpose_for_scores”  sN   € Ø—f‘f“h˜s �m t×'?Ñ'?À×AYÑAYÐ&ZÑZˆØˆA�F‰F�KÐ ˆØ�y‰y˜˜A˜q !Ó$Ð$r0   c                 ó–   — ||z  }|j                  d¬«      j                  d«      }||z
  |z  } t        j                  d¬«      |«      S )aÂ  
        https://arxiv.org/abs/2105.13290 Section 2.4 Stabilization of training: Precision Bottleneck Relaxation
        (PB-Relax). A replacement of the original nn.Softmax(dim=-1)(attention_scores). Seems the new attention_probs
        will result in a slower speed and a little bias. Can use torch.allclose(standard_attention_probs,
        cogview_attention_probs, atol=1e-08) for comparison. The smaller atol (e.g., 1e-08), the better.
        r2   rn   )Úamaxr‰   r&   ÚSoftmax)r+   Úattention_scoresÚalphaÚscaled_attention_scoresÚ	max_valueÚnew_attention_scoress         r/   Úcogview_attentionz)LayoutLMv3SelfAttention.cogview_attention™  sT   € ð #3°UÑ":ÐØ+×0Ñ0°bÐ0Ó:×DÑDÀRÓHˆ	Ø 7¸)Ñ CÀuÑLÐØ!Œr�z‰z˜bÔ!Ð"6Ó7Ð7r0   c                 ó€  — | j                  |«      }| j                  | j                  |«      «      }| j                  | j                  |«      «      }	| j                  |«      }
t	        j
                  |
t        j                  | j                  «      z  |j                  dd«      «      }| j                  r5| j                  r)|||z   t        j                  | j                  «      z  z  }n1| j                  r%||t        j                  | j                  «      z  z  }|�||z   }| j                  |«      }| j                  |«      }|�||z  }t	        j
                  ||	«      }|j                  dddd«      j                  «       }|j!                  «       d d | j"                  fz   } |j$                  |Ž }|r||f}|S |f}|S )Nr2   éþÿÿÿr   r3   r   r	   )r´   r½   rµ   r¶   r`   ÚmatmulÚmathÚsqrtr²   r=   r¸   r¹   rÆ   r^   r8   Ú
contiguousr5   r³   r7   )r+   Úhidden_statesÚattention_maskÚ	head_maskÚoutput_attentionsÚrel_posÚ
rel_2d_posÚmixed_query_layerÚ	key_layerÚvalue_layerÚquery_layerrÁ   Úattention_probsÚcontext_layerÚnew_context_layer_shapeÚoutputss                   r/   rC   zLayoutLMv3SelfAttention.forward¥  s¸  € ð !ŸJ™J }Ó5Ðà×-Ñ-¨d¯h©h°}Ó.EÓFˆ	Ø×/Ñ/°·
±
¸=Ó0IÓJˆØ×/Ñ/Ð0AÓBˆô
 !Ÿ<™<¨´d·i±iÀ×@XÑ@XÓ6YÑ(YÐ[d×[nÑ[nÐoqÐsuÓ[vÓwÐà×+Ò+°×0OÒ0OØ ¨:Ñ!5¼¿¹À4×C[ÑC[Ó9\Ñ \Ñ\ÑØ×-Ò-Ø ¬$¯)©)°D×4LÑ4LÓ*MÑ MÑMÐàÐ%à/°.Ñ@Ðð ×0Ñ0Ð1AÓBˆð Ÿ,™, Ó7ˆð Ð Ø-°	Ñ9ˆOäŸ™ _°kÓBˆà%×-Ñ-¨a°°A°qÓ9×DÑDÓFˆØ"/×"4Ñ"4Ó"6°s¸Ð";¸t×?QÑ?QÐ>SÑ"SÐØ*˜×*Ñ*Ð,CÐDˆá6G�= /Ð2ˆàˆð O\ÐM]ˆàˆr0   )é    ©NNFNN)rF   rG   rH   r   r½   rÆ   rC   rJ   rK   s   @r/   r«   r«     s)   ø„ ôLò(%ó

8ð ØØØØ÷1r0   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 )ÚLayoutLMv3SelfOutputc                 ó(  •— t         ‰| �  «        t        j                  |j                  |j                  «      | _        t        j                  |j                  |j                  ¬«      | _        t        j                  |j                  «      | _
        y ©NrP   )r   r   r&   r™   r)   ÚdenserZ   r[   r\   r]   r^   rl   s     €r/   r   zLayoutLMv3SelfOutput.__init__Û  s`   ø€ Ü‰ÑÔÜ—Y‘Y˜v×1Ñ1°6×3EÑ3EÓFˆŒ
ÜŸ™ f×&8Ñ&8¸f×>SÑ>SÔTˆŒÜ—z‘z &×"<Ñ"<Ó=ˆ�r0   rÍ   Úinput_tensorÚreturnc                 ór   — | j                  |«      }| j                  |«      }| j                  ||z   «      }|S rD   ©rá   r^   rZ   ©r+   rÍ   râ   s      r/   rC   zLayoutLMv3SelfOutput.forwardá  ó7   € ØŸ
™
 =Ó1ˆØŸ™ ]Ó3ˆØŸ™ }°|Ñ'CÓDˆØÐr0   ©rF   rG   rH   r   r`   ÚTensorrC   rJ   rK   s   @r/   rÞ   rÞ   Ú  ó1   ø„ ô>ð U§\¡\ð ÀÇÁð ÐRW×R^ÑR^÷ r0   rÞ   c                   ó0   ‡ — e Zd Zˆ fd„Z	 	 	 	 	 dd„Zˆ xZS )ÚLayoutLMv3Attentionc                 ób   •— t         ‰| �  «        t        |«      | _        t	        |«      | _        y rD   )r   r   r«   r+   rÞ   Úoutputrl   s     €r/   r   zLayoutLMv3Attention.__init__ê  s&   ø€ Ü‰ÑÔÜ+¨FÓ3ˆŒ	Ü*¨6Ó2ˆ�r0   c                 óp   — | j                  ||||||¬«      }| j                  |d   |«      }|f|dd  z   }	|	S )N©rÑ   rÒ   r   r   )r+   rî   )
r+   rÍ   rÎ   rÏ   rÐ   rÑ   rÒ   Úself_outputsÚattention_outputrÚ   s
             r/   rC   zLayoutLMv3Attention.forwardï  sY   € ð —y‘yØØØØØØ!ð !ó 
ˆð  Ÿ;™; |°A¡¸ÓFÐØ#Ð%¨°Q°RÐ(8Ñ8ˆØˆr0   rÜ   )rF   rG   rH   r   rC   rJ   rK   s   @r/   rì   rì   é  s   ø„ ô3ð ØØØØ÷r0   rì   c                   ó6   ‡ — e Zd Zˆ fd„Z	 	 	 	 	 dd„Zd„ Zˆ xZS )ÚLayoutLMv3Layerc                 ó²   •— t         ‰| �  «        |j                  | _        d| _        t	        |«      | _        t        |«      | _        t        |«      | _	        y ©Nr   )
r   r   Úchunk_size_feed_forwardÚseq_len_dimrì   Ú	attentionÚLayoutLMv3IntermediateÚintermediateÚLayoutLMv3Outputrî   rl   s     €r/   r   zLayoutLMv3Layer.__init__  sI   ø€ Ü‰ÑÔØ'-×'EÑ'EˆÔ$ØˆÔÜ,¨VÓ4ˆŒÜ2°6Ó:ˆÔÜ& vÓ.ˆ�r0   c                 ó¬   — | j                  ||||||¬«      }|d   }|dd  }	t        | j                  | j                  | j                  |«      }
|
f|	z   }	|	S )N)rÐ   rÑ   rÒ   r   r   )rù   r   Úfeed_forward_chunkr÷   rø   )r+   rÍ   rÎ   rÏ   rÐ   rÑ   rÒ   Úself_attention_outputsrò   rÚ   Úlayer_outputs              r/   rC   zLayoutLMv3Layer.forward  s|   € ð "&§¡ØØØØ/ØØ!ð "0ó "
Ðð 2°!Ñ4Ðà(¨¨Ð,ˆä0Ø×#Ñ# T×%AÑ%AÀ4×CSÑCSÐUeó
ˆð  �/ GÑ+ˆàˆr0   c                 óL   — | j                  |«      }| j                  ||«      }|S rD   )rû   rî   )r+   rò   Úintermediate_outputr   s       r/   rþ   z"LayoutLMv3Layer.feed_forward_chunk+  s,   € Ø"×/Ñ/Ð0@ÓAÐØ—{‘{Ð#6Ð8HÓIˆØÐr0   rÜ   )rF   rG   rH   r   rC   rþ   rJ   rK   s   @r/   rô   rô     s#   ø„ ô/ð ØØØØóö8r0   rô   c                   óL   ‡ — e Zd Zˆ fd„Zdd„Zd„ Zd„ Z	 	 	 	 	 	 	 	 	 dd„Zˆ xZS )ÚLayoutLMv3Encoderc                 óô  •— t         ‰| �  «        || _        t        j                  t        |j                  «      D �cg c]  }t        |«      ‘Œ c}«      | _        d| _	        |j                  | _
        |j                  | _        | j                  rS|j                  | _        |j                  | _        t        j                  | j                  |j                  d¬«      | _        | j                  r…|j"                  | _        |j$                  | _        t        j                  | j$                  |j                  d¬«      | _        t        j                  | j$                  |j                  d¬«      | _        y y c c}w )NF)rž   )r   r   r,   r&   Ú
ModuleListÚrangeÚnum_hidden_layersrô   ÚlayerÚgradient_checkpointingr¸   r¹   Úrel_pos_binsÚmax_rel_posr™   r¯   Úrel_pos_biasÚmax_rel_2d_posÚrel_2d_pos_binsÚrel_pos_x_biasÚrel_pos_y_bias)r+   r,   Ú_r.   s      €r/   r   zLayoutLMv3Encoder.__init__2  s  ø€ Ü‰ÑÔØˆŒÜ—]‘]ÄUÈ6×KcÑKcÓEdÖ#eÀ¤O°FÕ$;Ò#eÓfˆŒ
Ø&+ˆÔ#à+1×+MÑ+MˆÔ(Ø*0×*KÑ*KˆÔ'à×+Ò+Ø &× 3Ñ 3ˆDÔØ%×1Ñ1ˆDÔÜ "§	¡	¨$×*;Ñ*;¸V×=WÑ=WÐ^cÔ dˆDÔà×*Ò*Ø"(×"7Ñ"7ˆDÔØ#)×#9Ñ#9ˆDÔ Ü"$§)¡)¨D×,@Ñ,@À&×B\ÑB\ÐchÔ"iˆDÔÜ"$§)¡)¨D×,@Ñ,@À&×B\ÑB\ÐchÔ"iˆDÕð	 +ùò $fs   ½E5c                 ó6  — d}|r4|dz  }||dkD  j                  «       |z  z  }t        j                  |«      }n*t        j                  | t        j                  |«      «      }|dz  }||k  }|t        j
                  |j                  «       |z  «      t        j
                  ||z  «      z  ||z
  z  j                  t        j                   «      z   }	t        j                  |	t        j                  |	|dz
  «      «      }	|t        j                  |||	«      z  }|S )Nr   r3   r   )r€   r`   ÚabsÚmaxÚ
zeros_likeÚlogÚfloatrÊ   r�   ÚminÚ	full_likeÚwhere)
r+   Úrelative_positionÚbidirectionalÚnum_bucketsÚmax_distanceÚretÚnÚ	max_exactÚis_smallÚval_if_larges
             r/   Úrelative_position_bucketz*LayoutLMv3Encoder.relative_position_bucketF  s  € ØˆÙØ˜AÑˆKØÐ%¨Ñ)×/Ñ/Ó1°KÑ?Ñ?ˆCÜ—	‘	Ð+Ó,‰Aä—	‘	Ð,Ð,¬e×.>Ñ.>Ð?PÓ.QÓRˆAð   1Ñ$ˆ	Ø�y‘=ˆð !Ü�I‰I�a—g‘g“i )Ñ+Ó,¬t¯x©x¸ÀyÑ8PÓ/QÑQÐU`ÐclÑUlÑmß
‰"ŒU�Z‰Z‹.ñˆô —y‘y ¬u¯©¸|È[Ð[\É_Ó/]Ó^ˆàŒu�{‰{˜8 Q¨Ó5Ñ5ˆØˆ
r0   c                 ó€  — |j                  d«      |j                  d«      z
  }| j                  || j                  | j                  ¬«      }t	        j
                  «       5  | j                  j                  j                  «       |   j                  dddd«      }d d d «       |j                  «       }|S # 1 sw Y   ŒxY w)NrÈ   r2   ©r  r  r   r	   r   r3   )r‰   r%  r  r  r`   Úno_gradr  rš   Útr8   rÌ   )r+   rR   Úrel_pos_matrÑ   s       r/   Ú_cal_1d_pos_embz!LayoutLMv3Encoder._cal_1d_pos_emb]  s³   € Ø"×,Ñ,¨RÓ0°<×3IÑ3IÈ"Ó3MÑMˆà×/Ñ/ØØ×)Ñ)Ø×)Ñ)ð 0ó 
ˆô �]‰]‹_ñ 	PØ×'Ñ'×.Ñ.×0Ñ0Ó2°7Ñ;×CÑCÀAÀqÈ!ÈQÓOˆG÷	Pà×$Ñ$Ó&ˆØˆ÷	Pð 	Pús   Á :B4Â4B=c                 óâ  — |d d …d d …df   }|d d …d d …df   }|j                  d«      |j                  d«      z
  }|j                  d«      |j                  d«      z
  }| j                  || j                  | j                  ¬«      }| j                  || j                  | j                  ¬«      }t	        j
                  «       5  | j                  j                  j                  «       |   j                  dddd«      }| j                  j                  j                  «       |   j                  dddd«      }d d d «       |j                  «       }|j                  «       }||z   }|S # 1 sw Y   Œ0xY w)Nr   r	   rÈ   r2   r'  r   r3   )r‰   r%  r  r  r`   r(  r  rš   r)  r8   r  rÌ   )	r+   rs   Úposition_coord_xÚposition_coord_yÚrel_pos_x_2d_matÚrel_pos_y_2d_matÚ	rel_pos_xÚ	rel_pos_yrÒ   s	            r/   Ú_cal_2d_pos_embz!LayoutLMv3Encoder._cal_2d_pos_embn  st  € Ø¢¢1 a ™=ÐØ¢¢1 a ™=ÐØ+×5Ñ5°bÓ9Ð<L×<VÑ<VÐWYÓ<ZÑZÐØ+×5Ñ5°bÓ9Ð<L×<VÑ<VÐWYÓ<ZÑZÐØ×1Ñ1ØØ×,Ñ,Ø×,Ñ,ð 2ó 
ˆ	ð
 ×1Ñ1ØØ×,Ñ,Ø×,Ñ,ð 2ó 
ˆ	ô �]‰]‹_ñ 	VØ×+Ñ+×2Ñ2×4Ñ4Ó6°yÑA×IÑIÈ!ÈQÐPQÐSTÓUˆIØ×+Ñ+×2Ñ2×4Ñ4Ó6°yÑA×IÑIÈ!ÈQÐPQÐSTÓUˆI÷	Vð ×(Ñ(Ó*ˆ	Ø×(Ñ(Ó*ˆ	Ø Ñ*ˆ
ØÐ÷	Vð 	Vús   ÃA3E%Å%E.c           
      óþ  — |rdnd }|rdnd }| j                   r| j                  |«      nd }| j                  r| j                  |«      nd }t	        | j
                  «      D ]o  \  }}|r||fz   }|�||   nd }| j                  r.| j                  r"| j                  |j                  ||||||«      }n |||||||¬«      }|d   }|sŒg||d   fz   }Œq |r||fz   }|st        d„ |||fD «       «      S t        |||¬«      S )Nr©   rð   r   r   c              3   ó$   K  — | ]  }|�|–— Œ
 y ­wrD   r©   )Ú.0Úvs     r/   ú	<genexpr>z,LayoutLMv3Encoder.forward.<locals>.<genexpr>¾  s   è ø€ ò àð
 �=ô ñùs   ‚©Úlast_hidden_staterÍ   Ú
attentions)r¸   r+  r¹   r3  Ú	enumerater	  r
  ÚtrainingÚ_gradient_checkpointing_funcÚ__call__Útupler   )r+   rÍ   rs   rÎ   rÏ   rÐ   Úoutput_hidden_statesÚreturn_dictrR   rA   rB   Úall_hidden_statesÚall_self_attentionsrÑ   rÒ   ÚiÚlayer_moduleÚlayer_head_maskÚlayer_outputss                      r/   rC   zLayoutLMv3Encoder.forward‰  s\  € ñ #7™B¸DÐÙ$5™b¸4Ðà8<×8XÒ8X�$×&Ñ& |Ô4Ð^bˆØ37×3RÒ3R�T×)Ñ)¨$Ô/ÐX\ˆ
ä(¨¯©Ó4ò 	P‰OˆAˆ|Ù#Ø$5¸Ð8HÑ$HÐ!à.7Ð.C˜i¨šlÈˆOà×*Ò*¨t¯}ª}Ø $× AÑ AØ ×)Ñ)Ø!Ø"Ø#Ø%ØØó!‘ñ !-Ø!Ø"Ø#Ø%Ø#Ø)ô!�ð *¨!Ñ,ˆMÚ Ø&9¸]È1Ñ=MÐ<OÑ&OÑ#ð9	Pñ<  Ø 1°]Ð4DÑ DÐáÜñ ð "Ø%Ø'ðôó ð ô Ø+Ø+Ø*ô
ð 	
r0   )TrÛ   é€   )	NNNFFTNNN)	rF   rG   rH   r   r%  r+  r3  rC   rJ   rK   s   @r/   r  r  1  s;   ø„ ôjó(ò.ò"ð< ØØØØ"ØØØØ÷B
r0   r  c                   óV   ‡ — e Zd Zˆ fd„Zdej
                  dej
                  fd„Zˆ xZS )rú   c                 ó  •— t         ‰| �  «        t        j                  |j                  |j
                  «      | _        t        |j                  t        «      rt        |j                     | _        y |j                  | _        y rD   )r   r   r&   r™   r)   Úintermediate_sizerá   r   Ú
hidden_actÚstrr
   Úintermediate_act_fnrl   s     €r/   r   zLayoutLMv3Intermediate.__init__Ð  s]   ø€ Ü‰ÑÔÜ—Y‘Y˜v×1Ñ1°6×3KÑ3KÓLˆŒ
Ü�f×'Ñ'¬Ô-Ü'-¨f×.?Ñ.?Ñ'@ˆDÕ$à'-×'8Ñ'8ˆDÕ$r0   rÍ   rã   c                 óJ   — | j                  |«      }| j                  |«      }|S rD   )rá   rO  )r+   rÍ   s     r/   rC   zLayoutLMv3Intermediate.forwardØ  s&   € ØŸ
™
 =Ó1ˆØ×0Ñ0°Ó?ˆØÐr0   rè   rK   s   @r/   rú   rú   Ï  s#   ø„ ô9ð U§\¡\ð °e·l±l÷ r0   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 )rü   c                 ó(  •— t         ‰| �  «        t        j                  |j                  |j
                  «      | _        t        j                  |j
                  |j                  ¬«      | _        t        j                  |j                  «      | _        y rà   )r   r   r&   r™   rL  r)   rá   rZ   r[   r\   r]   r^   rl   s     €r/   r   zLayoutLMv3Output.__init__à  s`   ø€ Ü‰ÑÔÜ—Y‘Y˜v×7Ñ7¸×9KÑ9KÓLˆŒ
ÜŸ™ f×&8Ñ&8¸f×>SÑ>SÔTˆŒÜ—z‘z &×"<Ñ"<Ó=ˆ�r0   rÍ   râ   rã   c                 ór   — | j                  |«      }| j                  |«      }| j                  ||z   «      }|S rD   rå   ræ   s      r/   rC   zLayoutLMv3Output.forwardæ  rç   r0   rè   rK   s   @r/   rü   rü   ß  rê   r0   rü   zdThe bare LayoutLMv3 Model transformer outputting raw hidden-states without any specific head on top.c                   óÎ  ‡ — e Zd Zˆ fd„Zd„ Zd„ Zd„ Zdd„Zd„ Zd„ Z	 e
ej                  d«      «       eee¬	«      	 	 	 	 	 	 	 	 	 	 	 dd
eej$                     deej$                     deej&                     deej$                     deej$                     deej&                     deej&                     deej&                     dee   dee   dee   deeef   fd„«       «       Zˆ xZS )r¡   c                 óÂ  •— t         ‰| �  |«       || _        |j                  rt	        |«      | _        |j                  �rt        |«      | _        t        |j                  |j                  z  «      }t        j                  t        j                  dd|j                   «      «      | _        t        j                  t        j                  d||z  dz   |j                   «      «      | _        t        j&                  d¬«      | _        t        j*                  |j                   |j,                  ¬«      | _        t        j&                  |j.                  «      | _        | j                  j2                  s| j                  j4                  r| j7                  ||f¬«       t        j*                  |j                   d¬«      | _        t;        |«      | _        | j?                  «        y )Nr   r–   )ÚprP   )r-   g�íµ ÷Æ°>) r   r   r,   Ú
text_embedrM   r@   r¢   r   Úpatch_embedr}   r    r$   r&   Ú	Parameterr`   r�   r)   r£   r¤   r\   Úpos_droprZ   r[   r]   r^   r¸   r¹   Úinit_visual_bboxÚnormr  ÚencoderÚinit_weights)r+   r,   r5   r.   s      €r/   r   zLayoutLMv3Model.__init__ò  sO  ø€ Ü‰Ñ˜Ô ØˆŒà×ÒÜ6°vÓ>ˆDŒOà×Óô  9¸Ó@ˆDÔä�v×(Ñ(¨6×+<Ñ+<Ñ<Ó=ˆDÜŸ\™\¬%¯+©+°a¸¸F×<NÑ<NÓ*OÓPˆDŒNÜŸ\™\¬%¯+©+°a¸À¹Àq¹È&×J\ÑJ\Ó*]Ó^ˆDŒNÜŸJ™J¨Ô-ˆDŒMäŸ\™\¨&×*<Ñ*<À&×BWÑBWÔXˆDŒNÜŸ:™: f×&@Ñ&@ÓAˆDŒLà�{‰{×6Ò6¸$¿+¹+×:`Ò:`Ø×%Ñ%°$¸°Ð%Ô>äŸ™ V×%7Ñ%7¸TÔBˆDŒIä(¨Ó0ˆŒà×ÑÕr0   c                 ó.   — | j                   j                  S rD   ©r@   rW   )r+   s    r/   Úget_input_embeddingsz$LayoutLMv3Model.get_input_embeddings  s   € Ø�‰×.Ñ.Ð.r0   c                 ó&   — || j                   _        y rD   r`  )r+   r¶   s     r/   Úset_input_embeddingsz$LayoutLMv3Model.set_input_embeddings  s   € Ø*/ˆ�‰Õ'r0   c                 ó˜   — |j                  «       D ]7  \  }}| j                  j                  |   j                  j	                  |«       Œ9 y)z�
        Prunes heads of the model. heads_to_prune: dict of {layer_num: list of heads to prune in this layer} See base
        class PreTrainedModel
        N)Úitemsr]  r	  rù   Úprune_heads)r+   Úheads_to_pruner	  Úheadss       r/   Ú_prune_headszLayoutLMv3Model._prune_heads  sE   € ð
 +×0Ñ0Ó2ò 	C‰LˆE�5Ø�L‰L×Ñ˜uÑ%×/Ñ/×;Ñ;¸EÕBñ	Cr0   c           	      óª  — t        j                  t        j                  d||d   dz   z  |«      |d   d¬«      }t        j                  t        j                  d||d   dz   z  |«      |d   d¬«      }t        j                  |dd j	                  |d   d«      |dd j	                  |d   d«      j                  dd«      |dd j	                  |d   d«      |dd j	                  |d   d«      j                  dd«      gd¬«      j                  dd«      }t        j                  dd|dz
  |dz
  gg«      }t        j                  ||gd¬«      | _	        y)	zJ
        Create the bounding boxes for the visual (patch) tokens.
        r   r   Útrunc)Úrounding_modeNr2   rn   é   )
r`   Údivra   ÚstackÚrepeatr=   r7   Útensorrr   Úvisual_bbox)r+   r-   Úmax_lenÚvisual_bbox_xÚvisual_bbox_yrr  Úcls_token_boxs          r/   r[  z LayoutLMv3Model.init_visual_bbox  s^  € ô Ÿ	™	Ü�L‰L˜˜G z°!¡}°qÑ'8Ñ9¸7ÓCÀZÐPQÁ]Ðbiô
ˆô Ÿ	™	Ü�L‰L˜˜G z°!¡}°qÑ'8Ñ9¸7ÓCÀZÐPQÁ]Ðbiô
ˆô —k‘kà˜c˜rÐ"×)Ñ)¨*°Q©-¸Ó;Ø˜c˜rÐ"×)Ñ)¨*°Q©-¸Ó;×EÑEÀaÈÓKØ˜a˜bÐ!×(Ñ(¨°A©¸Ó:Ø˜a˜bÐ!×(Ñ(¨°A©¸Ó:×DÑDÀQÈÓJð	ð ô
÷ ‰$ˆr�1‹+ð 	ô Ÿ™ u¨e°W¸q±[À'ÈAÁ+Ð&NÐ%OÓPˆÜ Ÿ9™9 m°[Ð%AÀqÔIˆÕr0   c                 ó€   — | j                   j                  |dd«      }|j                  |«      j                  |«      }|S rö   )rr  rp  r�   Útype)r+   rˆ   r‡   Ú
batch_sizerr  s        r/   Úcalculate_visual_bboxz%LayoutLMv3Model.calculate_visual_bbox4  s;   € Ø×&Ñ&×-Ñ-¨j¸!¸QÓ?ˆØ!—n‘n VÓ,×1Ñ1°%Ó8ˆØÐr0   c                 ó6  — | j                  |«      }|j                  «       \  }}}| j                  j                  |dd«      }t	        j
                  ||fd¬«      }| j                  �|| j                  z   }| j                  |«      }| j                  |«      }|S )Nr2   r   rn   )	rX  r5   r£   rc   r`   rr   r¤   rZ  r\  )r+   r>   r@   ry  Úseq_lenr  Ú
cls_tokenss          r/   Úforward_imagezLayoutLMv3Model.forward_image9  s�   € Ø×%Ñ% lÓ3ˆ
ð ",§¡Ó!2Ñˆ
�G˜QØ—^‘^×*Ñ*¨:°r¸2Ó>ˆ
Ü—Y‘Y 
¨JÐ7¸QÔ?ˆ
ð �>‰>Ð%Ø# d§n¡nÑ4ˆJà—]‘] :Ó.ˆ
Ø—Y‘Y˜zÓ*ˆ
àÐr0   z!batch_size, token_sequence_length©Úoutput_typer§   r�   rs   rÎ   r‘   rR   rÏ   rŠ   r>   rÐ   rA  rB  rã   c                 óX	  — |	�|	n| j                   j                  }	|
�|
n| j                   j                  }
|�|n| j                   j                  }|�"|j	                  «       }|\  }}|j
                  }nL|�%|j	                  «       dd }|\  }}|j
                  }n%|�t        |«      }|j
                  }nt        d«      ‚|€|�—|€t        j                  |f|¬«      }|€&t        j                  t        j                  |¬«      }|€<t        j                  t        t        «      dgz   «      t        j                  |¬«      }| j                  |||||¬«      }dx}}dx}}|��&t        |j                   d   | j                   j"                  z  «      t        |j                   d	   | j                   j"                  z  «      }}| j%                  |«      }t        j                  ||j                   d
   ft        j                  |¬«      }|�t        j&                  ||gd
¬«      }n|}| j                   j(                  s| j                   j*                  rõ| j                   j*                  r@| j-                  |t        j                  |¬«      }|�t        j&                  ||gd
¬«      }n|}t        j.                  d|j                   d
   t        j                  |¬«      j1                  |d
«      }|€|�Ut        j.                  dd
   |¬«      j3                  d«      }|j5                  |«      }t        j&                  ||gd
¬«      }n|}|€|�t        j&                  |gd
¬«      }n|}| j7                  |«      }| j9                  |«      }n�| j                   j(                  s| j                   j*                  rc| j                   j*                  r|}| j                   j(                  r5| j                  j:                  dd…dd
   …f   }|j=                  |«      }|}| j?                  |d|j@                  ¬«      }| jC                  || j                   jD                  «      }| jG                  ||||||	|
|||¬«
      }|d   }|s	|f|d
d z   S tI        ||jJ                  |jL                  ¬«      S )a  
        Returns:

        Examples:

        ```python
        >>> from transformers import AutoProcessor, AutoModel
        >>> from datasets import load_dataset

        >>> processor = AutoProcessor.from_pretrained("microsoft/layoutlmv3-base", apply_ocr=False)
        >>> model = AutoModel.from_pretrained("microsoft/layoutlmv3-base")

        >>> dataset = load_dataset("nielsr/funsd-layoutlmv3", split="train", trust_remote_code=True)
        >>> example = dataset[0]
        >>> image = example["image"]
        >>> words = example["tokens"]
        >>> boxes = example["bboxes"]

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

        >>> outputs = model(**encoding)
        >>> last_hidden_states = outputs.last_hidden_state
        ```Nr2   zEYou have to specify either input_ids or inputs_embeds or pixel_values)rˆ   r†   rm  )r�   rs   rR   r‘   rŠ   r3   r	   r   rn   )r‡   ry  r   )r‡   )	rs   rR   rÎ   rÏ   rÐ   rA  rB  rA   rB   r9  )'r,   rÐ   rA  Úuse_return_dictr5   rˆ   Úlenr±   r`   Úonesr�   r€   r@  Úlistr@   r   r9   r$   r~  rr   r¸   r¹   rz  ra   rp  r‰   rc   rZ   r^   rR   Ú	expand_asÚget_extended_attention_maskr‡   Úget_head_maskr  r]  r   rÍ   r;  )r+   r�   rs   rÎ   r‘   rR   rÏ   rŠ   r>   rÐ   rA  rB  r‹   ry  Ú
seq_lengthrˆ   Úembedding_outputÚ
final_bboxÚfinal_position_idsrA   rB   Úvisual_embeddingsÚvisual_attention_maskrr  Úvisual_position_idsÚextended_attention_maskÚencoder_outputsÚsequence_outputs                               r/   rC   zLayoutLMv3Model.forwardJ  s›  € ðR 2CÐ1NÑ-ÐTX×T_ÑT_×TqÑTqÐà$8Ð$DÑ È$Ï+É+×JjÑJjð 	ð &1Ð%<‘kÀ$Ç+Á+×B]ÑB]ˆàÐ Ø#Ÿ.™.Ó*ˆKØ%0Ñ"ˆJ˜
Ø×%Ñ%‰FØÐ&Ø'×,Ñ,Ó.¨s°Ð3ˆKØ%0Ñ"ˆJ˜
Ø"×)Ñ)‰FØÐ%Ü˜\Ó*ˆJØ!×(Ñ(‰FäÐdÓeÐeàÐ  MÐ$=ØÐ%Ü!&§¡¨j¸*Ð-EÈvÔ!V�ØÐ%Ü!&§¡¨[ÄÇ
Á
ÐSYÔ!Z�Øˆ|Ü—{‘{¤5¬¨kÓ):¸a¸SÑ)@Ó#AÌÏÉÐ\bÔc�à#Ÿ™Ø#ØØ)Ø-Ø+ð  /ó  Ðð +/Ð.ˆ
Ð'Ø%)Ð)ˆ�{ØÑ#ä˜,×,Ñ,¨QÑ/°$·+±+×2HÑ2HÑHÓIÜ˜,×,Ñ,¨QÑ/°$·+±+×2HÑ2HÑHÓIð &ˆLð !%× 2Ñ 2°<Ó @ÐÜ$)§J¡JØÐ.×4Ñ4°QÑ7Ð8ÄÇ
Á
ÐSYô%Ð!ð Ð)Ü!&§¡¨NÐ<QÐ+RÐXYÔ!Z‘à!6�à�{‰{×6Ò6¸$¿+¹+×:`Ò:`Ø—;‘;×9Ò9Ø"&×"<Ñ"<¸VÌ5Ï:É:ÐblÐ"<Ó"m�KØÐ'Ü%*§Y¡Y°°kÐ/BÈÔ%J™
à%0˜
ä&+§l¡lØÐ(×.Ñ.¨qÑ1¼¿¹ÈFô'ç‘&˜ QÓ'ð $ð Ð(¨MÐ,EÜ#(§<¡<°°;¸q±>È&Ô#Q×#[Ñ#[Ð\]Ó#^�LØ#/×#6Ñ#6°{Ó#C�LÜ).¯©°LÐBUÐ3VÐ\]Ô)^Ñ&à)<Ð&àÐ$¨Ð(AÜ#(§9¡9Ð.>Ð@QÐ-RÐXYÔ#ZÑ à#4Ð à#Ÿ~™~Ð.>Ó?ÐØ#Ÿ|™|Ð,<Ó=ÑØ�[‰[×4Ò4¸¿¹×8^Ò8^Ø�{‰{×5Ò5Ø!�
Ø�{‰{×6Ò6Ø#Ÿ™×;Ñ;ºAÐ?OÀÈQÁÐ?OÐ<OÑP�Ø+×5Ñ5°iÓ@�Ø%1Ð"à04×0PÑ0PØ˜D &Ð0@×0FÑ0Fð 1Qó 1
Ðð ×&Ñ& y°$·+±+×2OÑ2OÓPˆ	àŸ,™,ØØØ+Ø2ØØ/Ø!5Ø#Ø%Ø#ð 'ó 
ˆð *¨!Ñ,ˆáØ#Ð%¨¸¸Ð(;Ñ;Ð;äØ-Ø)×7Ñ7Ø&×1Ñ1ô
ð 	
r0   ))é   r“  iè  )NNNNNNNNNNN)rF   rG   rH   r   ra  rc  ri  r[  rz  r~  r   Ú!LAYOUTLMV3_MODEL_INPUTS_DOCSTRINGÚformatr   r   Ú_CONFIG_FOR_DOCr   r`   Ú
LongTensorÚFloatTensorÚboolr   r   rC   rJ   rK   s   @r/   r¡   r¡   í  sw  ø„ ô
ò:/ò0òCóJò.ò
ñ" +Ø)×0Ñ0Ð1TÓUóñ ¨?ÈÔYð 15Ø+/Ø6:Ø59Ø37Ø15Ø59Ø48Ø,0Ø/3Ø&*ñ[
à˜E×,Ñ,Ñ-ð[
ð �u×'Ñ'Ñ(ð[
ð ! ×!2Ñ!2Ñ3ð	[
ð
 ! ×!1Ñ!1Ñ2ð[
ð ˜u×/Ñ/Ñ0ð[
ð ˜E×-Ñ-Ñ.ð[
ð   × 1Ñ 1Ñ2ð[
ð ˜u×0Ñ0Ñ1ð[
ð $ D™>ð[
ð ' t™nð[
ð ˜d‘^ð[
ð 
ˆu�oÐ%Ñ	&ò[
ó Zóô[
r0   r¡   c                   ó*   ‡ — e Zd ZdZdˆ fd„	Zd„ Zˆ xZS )ÚLayoutLMv3ClassificationHeadz\
    Head for sentence-level classification tasks. Reference: RobertaClassificationHead
    c                 óÒ  •— t         ‰| �  «        || _        |r3t        j                  |j
                  dz  |j
                  «      | _        n/t        j                  |j
                  |j
                  «      | _        |j                  �|j                  n|j                  }t        j                  |«      | _
        t        j                  |j
                  |j                  «      | _        y )Nr	   )r   r   Úpool_featurer&   r™   r)   rá   Úclassifier_dropoutr]   r\   r^   Ú
num_labelsÚout_proj)r+   r,   r�  rž  r.   s       €r/   r   z%LayoutLMv3ClassificationHead.__init__ñ  s­   ø€ Ü‰ÑÔØ(ˆÔÙÜŸ™ 6×#5Ñ#5¸Ñ#9¸6×;MÑ;MÓNˆD�JäŸ™ 6×#5Ñ#5°v×7IÑ7IÓJˆDŒJà)/×)BÑ)BÐ)NˆF×%Ò%ÐTZ×TnÑTnð 	ô —z‘zÐ"4Ó5ˆŒÜŸ	™	 &×"4Ñ"4°f×6GÑ6GÓHˆ�r0   c                 ó¸   — | j                  |«      }| j                  |«      }t        j                  |«      }| j                  |«      }| j	                  |«      }|S rD   )r^   rá   r`   Útanhr   )r+   r»   s     r/   rC   z$LayoutLMv3ClassificationHead.forwardþ  sI   € Ø�L‰L˜‹OˆØ�J‰J�q‹MˆÜ�J‰J�q‹MˆØ�L‰L˜‹OˆØ�M‰M˜!ÓˆØˆr0   )FrE   rK   s   @r/   r›  r›  ì  s   ø„ ñõIör0   r›  a„  
    LayoutLMv3 Model with a token classification head on top (a linear layer on top of the final 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                   óÈ  ‡ — e Zd Zˆ fd„Z eej                  d«      «       eee	¬«      	 	 	 	 	 	 	 	 	 	 	 	 dde
ej                     de
ej                     de
ej                     de
ej                     de
ej                     d	e
ej                     d
e
ej                     de
ej                     de
e   de
e   de
e   de
ej                     deeef   fd„«       «       Zˆ xZS )Ú LayoutLMv3ForTokenClassificationc                 óp  •— t         ‰| �  |«       |j                  | _        t        |«      | _        t        j                  |j                  «      | _        |j                  dk  r0t        j                  |j                  |j                  «      | _        nt        |d¬«      | _        | j                  «        y )Né
   F©r�  )r   r   rŸ  r¡   r”   r&   r\   r]   r^   r™   r)   Ú
classifierr›  r^  rl   s     €r/   r   z)LayoutLMv3ForTokenClassification.__init__  s†   ø€ Ü‰Ñ˜Ô Ø ×+Ñ+ˆŒä)¨&Ó1ˆŒÜ—z‘z &×"<Ñ"<Ó=ˆŒØ×Ñ˜rÒ!Ü Ÿi™i¨×(:Ñ(:¸F×<MÑ<MÓNˆD�Oä:¸6ÐPUÔVˆDŒOà×ÑÕr0   úbatch_size, sequence_lengthr  r�   rs   rÎ   r‘   rR   rÏ   rŠ   ÚlabelsrÐ   rA  rB  r>   rã   c                 ó  — |�|n| j                   j                  }| j                  ||||||||	|
||¬«      }|�|j                  «       }n|j                  «       dd }|d   }|d   dd…d|…f   }| j	                  |«      }| j                  |«      }d}|�<t        «       } ||j                  d| j                  «      |j                  d«      «      }|s|f|dd z   }|�|f|z   S |S t        |||j                  |j                  ¬«      S )aj  
        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]`.

        Returns:

        Examples:

        ```python
        >>> from transformers import AutoProcessor, AutoModelForTokenClassification
        >>> from datasets import load_dataset

        >>> processor = AutoProcessor.from_pretrained("microsoft/layoutlmv3-base", apply_ocr=False)
        >>> model = AutoModelForTokenClassification.from_pretrained("microsoft/layoutlmv3-base", num_labels=7)

        >>> dataset = load_dataset("nielsr/funsd-layoutlmv3", split="train", trust_remote_code=True)
        >>> example = dataset[0]
        >>> image = example["image"]
        >>> words = example["tokens"]
        >>> boxes = example["bboxes"]
        >>> word_labels = example["ner_tags"]

        >>> encoding = processor(image, words, boxes=boxes, word_labels=word_labels, return_tensors="pt")

        >>> outputs = model(**encoding)
        >>> loss = outputs.loss
        >>> logits = outputs.logits
        ```N)
rs   rÎ   r‘   rR   rÏ   rŠ   rÐ   rA  rB  r>   r2   r   r   ©ÚlossÚlogitsrÍ   r;  )r,   r‚  r”   r5   r^   r¨  r   r7   rŸ  r   rÍ   r;  )r+   r�   rs   rÎ   r‘   rR   rÏ   rŠ   rª  rÐ   rA  rB  r>   rÚ   r‹   r‰  r’  r®  r­  Úloss_fctrî   s                        r/   rC   z(LayoutLMv3ForTokenClassification.forward  s:  € ð^ &1Ð%<‘kÀ$Ç+Á+×B]ÑB]ˆà—/‘/ØØØ)Ø)Ø%ØØ'Ø/Ø!5Ø#Ø%ð "ó 
ˆð Ð Ø#Ÿ.™.Ó*‰Kà'×,Ñ,Ó.¨s°Ð3ˆKà  ‘^ˆ
à! !™*¢Q¨¨¨ ^Ñ4ˆØŸ,™, Ó7ˆØ—‘ Ó1ˆàˆØÐÜ'Ó)ˆHÙ˜FŸK™K¨¨D¯O©OÓ<¸f¿k¹kÈ"»oÓNˆDáØ�Y ¨¨ Ñ,ˆFØ)-Ð)9�T�G˜fÑ$ÐE¸vÐEä$ØØØ!×/Ñ/Ø×)Ñ)ô	
ð 	
r0   ©NNNNNNNNNNNN)rF   rG   rH   r   r   Ú&LAYOUTLMV3_DOWNSTREAM_INPUTS_DOCSTRINGr•  r   r   r–  r   r`   r—  r˜  r™  r   r   rC   rJ   rK   s   @r/   r¤  r¤    sr  ø„ ôñ +Ø.×5Ñ5Ð6SÓTóñ Ð+@ÈÔ_ð 15Ø+/Ø6:Ø59Ø37Ø15Ø59Ø-1Ø,0Ø/3Ø&*Ø37ñS
à˜E×,Ñ,Ñ-ðS
ð �u×'Ñ'Ñ(ðS
ð ! ×!2Ñ!2Ñ3ð	S
ð
 ! ×!1Ñ!1Ñ2ðS
ð ˜u×/Ñ/Ñ0ðS
ð ˜E×-Ñ-Ñ.ðS
ð   × 1Ñ 1Ñ2ðS
ð ˜×)Ñ)Ñ*ðS
ð $ D™>ðS
ð ' t™nðS
ð ˜d‘^ðS
ð ˜u×/Ñ/Ñ0ðS
ð 
ˆuÐ+Ð+Ñ	,òS
ó `óôS
r0   r¤  a  
    LayoutLMv3 Model with a span classification head on top for extractive question-answering tasks such as
    [DocVQA](https://rrc.cvc.uab.es/?ch=17) (a linear layer on top of the text part of the hidden-states output to
    compute `span start logits` and `span end logits`).
    c            !       óè  ‡ — e Zd Zˆ fd„Z eej                  d«      «       eee	¬«      	 	 	 	 	 	 	 	 	 	 	 	 	 dde
ej                     de
ej                     de
ej                     de
ej                     de
ej                     d	e
ej                     d
e
ej                     de
ej                     de
e   de
e   de
e   de
ej                     de
ej                     deeef   fd„«       «       Zˆ xZS )ÚLayoutLMv3ForQuestionAnsweringc                 óª   •— t         ‰| �  |«       |j                  | _        t        |«      | _        t        |d¬«      | _        | j                  «        y ©NFr§  )r   r   rŸ  r¡   r”   r›  Ú
qa_outputsr^  rl   s     €r/   r   z'LayoutLMv3ForQuestionAnswering.__init__�  sC   ø€ Ü‰Ñ˜Ô Ø ×+Ñ+ˆŒä)¨&Ó1ˆŒÜ6°vÈEÔRˆŒà×ÑÕr0   r©  r  r�   rÎ   r‘   rR   rÏ   rŠ   Ústart_positionsÚend_positionsrÐ   rA  rB  rs   r>   rã   c                 ó,  — |�|n| j                   j                  }| j                  |||||||	|
|||¬«      }|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  }|s||f|dd z   }|�|f|z   S |S t        ||||j                  |j                  ¬	«      S )
aZ  
        start_positions (`torch.LongTensor` of shape `(batch_size,)`, *optional*):
            Labels for position (index) of the start of the labelled span for computing the token classification loss.
            Positions are clamped to the length of the sequence (`sequence_length`). Position outside of the sequence
            are not taken into account for computing the loss.
        end_positions (`torch.LongTensor` of shape `(batch_size,)`, *optional*):
            Labels for position (index) of the end of the labelled span for computing the token classification loss.
            Positions are clamped to the length of the sequence (`sequence_length`). Position outside of the sequence
            are not taken into account for computing the loss.

        Returns:

        Examples:

        ```python
        >>> from transformers import AutoProcessor, AutoModelForQuestionAnswering
        >>> from datasets import load_dataset
        >>> import torch

        >>> processor = AutoProcessor.from_pretrained("microsoft/layoutlmv3-base", apply_ocr=False)
        >>> model = AutoModelForQuestionAnswering.from_pretrained("microsoft/layoutlmv3-base")

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

        >>> encoding = processor(image, question, words, boxes=boxes, return_tensors="pt")
        >>> start_positions = torch.tensor([1])
        >>> end_positions = torch.tensor([3])

        >>> outputs = model(**encoding, start_positions=start_positions, end_positions=end_positions)
        >>> loss = outputs.loss
        >>> start_scores = outputs.start_logits
        >>> end_scores = outputs.end_logits
        ```N©
rÎ   r‘   rR   rÏ   rŠ   rÐ   rA  rB  rs   r>   r   r   r2   rn   )Úignore_indexr3   )r­  Ústart_logitsÚ
end_logitsrÍ   r;  )r,   r‚  r”   r¶  ÚsplitÚsqueezerÌ   rƒ  r5   Úclampr   r   rÍ   r;  )r+   r�   rÎ   r‘   rR   rÏ   rŠ   r·  r¸  rÐ   rA  rB  rs   r>   rÚ   r’  r®  r¼  r½  Ú
total_lossÚignored_indexr¯  Ú
start_lossÚend_lossrî   s                            r/   rC   z&LayoutLMv3ForQuestionAnswering.forwardŠ  sÉ  € ðv &1Ð%<‘kÀ$Ç+Á+×B]ÑB]ˆà—/‘/ØØ)Ø)Ø%ØØ'Ø/Ø!5Ø#ØØ%ð "ó 
ˆð " !™*ˆà—‘ Ó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áØ" JÐ/°'¸!¸"°+Ñ=ˆFØ/9Ð/E�Z�M FÑ*ÐQÈ6ÐQä+ØØ%Ø!Ø!×/Ñ/Ø×)Ñ)ô
ð 	
r0   )NNNNNNNNNNNNN)rF   rG   rH   r   r   r±  r•  r   r   r–  r   r`   r—  r˜  r™  r   r   rC   rJ   rK   s   @r/   r³  r³  x  sŒ  ø„ ôñ +Ø.×5Ñ5Ð6SÓTóñ Ð+GÐVeÔfð 15Ø6:Ø59Ø37Ø15Ø59Ø6:Ø48Ø,0Ø/3Ø&*Ø+/Ø37ñi
à˜E×,Ñ,Ñ-ði
ð ! ×!2Ñ!2Ñ3ði
ð ! ×!1Ñ!1Ñ2ð	i
ð
 ˜u×/Ñ/Ñ0ði
ð ˜E×-Ñ-Ñ.ði
ð   × 1Ñ 1Ñ2ði
ð " %×"2Ñ"2Ñ3ði
ð   × 0Ñ 0Ñ1ði
ð $ D™>ði
ð ' t™nði
ð ˜d‘^ði
ð �u×'Ñ'Ñ(ði
ð ˜u×/Ñ/Ñ0ði
ð 
ˆuÐ2Ð2Ñ	3òi
ó góôi
r0   r³  a
  
    LayoutLMv3 Model with a sequence classification head on top (a linear layer on top of the final hidden state of the
    [CLS] token) e.g. for document image classification tasks such as the
    [RVL-CDIP](https://www.cs.cmu.edu/~aharley/rvl-cdip/) dataset.
    c                   óÈ  ‡ — e Zd Zˆ fd„Z eej                  d«      «       eee	¬«      	 	 	 	 	 	 	 	 	 	 	 	 dde
ej                     de
ej                     de
ej                     de
ej                     de
ej                     d	e
ej                     d
e
ej                     de
e   de
e   de
e   de
ej                     de
ej                     deeef   fd„«       «       Zˆ xZS )Ú#LayoutLMv3ForSequenceClassificationc                 ó¸   •— t         ‰| �  |«       |j                  | _        || _        t	        |«      | _        t        |d¬«      | _        | j                  «        y rµ  )	r   r   rŸ  r,   r¡   r”   r›  r¨  r^  rl   s     €r/   r   z,LayoutLMv3ForSequenceClassification.__init__  sJ   ø€ Ü‰Ñ˜Ô Ø ×+Ñ+ˆŒØˆŒÜ)¨&Ó1ˆŒÜ6°vÈEÔRˆŒà×ÑÕr0   r©  r  r�   rÎ   r‘   rR   rÏ   rŠ   rª  rÐ   rA  rB  rs   r>   rã   c                 ó6  — |
�|
n| j                   j                  }
| j                  ||||||||	|
||¬«      }|d   dd…ddd…f   }| 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        «       } |||«      }|
s|f|dd z   }|�|f|z   S |S t        |||j                   |j"                  ¬	«      S )
a§  
        Returns:

        Examples:

        ```python
        >>> from transformers import AutoProcessor, AutoModelForSequenceClassification
        >>> from datasets import load_dataset
        >>> import torch

        >>> processor = AutoProcessor.from_pretrained("microsoft/layoutlmv3-base", apply_ocr=False)
        >>> model = AutoModelForSequenceClassification.from_pretrained("microsoft/layoutlmv3-base")

        >>> dataset = load_dataset("nielsr/funsd-layoutlmv3", split="train", trust_remote_code=True)
        >>> example = dataset[0]
        >>> image = example["image"]
        >>> words = example["tokens"]
        >>> boxes = example["bboxes"]

        >>> encoding = processor(image, words, boxes=boxes, return_tensors="pt")
        >>> sequence_label = torch.tensor([1])

        >>> outputs = model(**encoding, labels=sequence_label)
        >>> loss = outputs.loss
        >>> logits = outputs.logits
        ```Nrº  r   r   Ú
regressionÚsingle_label_classificationÚmulti_label_classificationr2   r¬  )r,   r‚  r”   r¨  Úproblem_typerŸ  r‡   r`   r€   r}   r   r¿  r   r7   r   r   rÍ   r;  )r+   r�   rÎ   r‘   rR   rÏ   rŠ   rª  rÐ   rA  rB  rs   r>   rÚ   r’  r®  r­  r¯  rî   s                      r/   rC   z+LayoutLMv3ForSequenceClassification.forward  sì  € ðZ &1Ð%<‘kÀ$Ç+Á+×B]ÑB]ˆà—/‘/ØØ)Ø)Ø%ØØ'Ø/Ø!5Ø#ØØ%ð "ó 
ˆð " !™*¢Q¨ª1 WÑ-ˆØ—‘ Ó1ˆàˆØÑØ�{‰{×'Ñ'Ð/Ø—?‘? 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Ü,Ó.�Ù ¨Ó/�áØ�Y ¨¨ Ñ,ˆFØ)-Ð)9�T�G˜fÑ$ÐE¸vÐEä'ØØØ!×/Ñ/Ø×)Ñ)ô	
ð 	
r0   r°  )rF   rG   rH   r   r   r±  r•  r   r   r–  r   r`   r—  r˜  r™  r   r   rC   rJ   rK   s   @r/   rÆ  rÆ  ú  ss  ø„ ôñ +Ø.×5Ñ5Ð6SÓTóñ Ð+CÐRaÔbð 15Ø6:Ø59Ø37Ø15Ø59Ø-1Ø,0Ø/3Ø&*Ø+/Ø37ñ\
à˜E×,Ñ,Ñ-ð\
ð ! ×!2Ñ!2Ñ3ð\
ð ! ×!1Ñ!1Ñ2ð	\
ð
 ˜u×/Ñ/Ñ0ð\
ð ˜E×-Ñ-Ñ.ð\
ð   × 1Ñ 1Ñ2ð\
ð ˜×)Ñ)Ñ*ð\
ð $ D™>ð\
ð ' t™nð\
ð ˜d‘^ð\
ð �u×'Ñ'Ñ(ð\
ð ˜u×/Ñ/Ñ0ð\
ð 
ˆuÐ.Ð.Ñ	/ò\
ó cóô\
r0   rÆ  )r³  rÆ  r¤  r¡   r“   )<rI   r!   rÊ   Útypingr   r   r   r`   Útorch.nnr&   Útorch.nn.functionalÚ
functionalr:   Útorch.utils.checkpointr   r   r   Úactivationsr
   Úmodeling_outputsr   r   r   r   Úmodeling_utilsr   Úpytorch_utilsr   Úutilsr   r   r   r   r   Úconfiguration_layoutlmv3r   Ú
get_loggerrF   Úloggerr–  ÚLAYOUTLMV3_START_DOCSTRINGr”  r±  ÚModuler   rM   r“   r«   rÞ   rì   rô   r  rú   rü   r¡   r›  r¤  r³  rÆ  Ú__all__r©   r0   r/   ú<module>rÝ     sù  ðñ  ã Û ß )Ñ )ã Ý ß Ð Û ß AÑ Aå !÷ó õ .Ý 6÷õ õ 7ð 
ˆ×	Ñ	˜HÓ	%€à$€ð	Ð ðJ%Ð !ðX;*Ð &ô|  §	¡	ô  ôFs˜rŸy™yô sôl. ô .ô<W˜bŸi™iô Wôv˜2Ÿ9™9ô ô˜"Ÿ)™)ô ô:(�b—i‘iô (ôVZ
˜Ÿ	™	ô Z
ô|˜RŸY™Yô ô �r—y‘yô ñ ØjØóôx
Ð/ó x
ó	ðx
ôv 2§9¡9ô ñ6 ðð óôe
Ð'@ó e
óðe
ñP ðð
 óôw
Ð%>ó w
óðw
ñt ðð
 óôj
Ð*Có j
óðj
òZ�r0   