U
    9%e                     @   s  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	  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  ddl!m"Z" e#e$Z%dZ&ddgZ'dZ(dZ)dZ*G dd de	j+Z,G dd de	j+Z-G dd deZ.G dd de	j+Z/G dd de	j+Z0G dd de	j+Z1G dd  d e	j+Z2G d!d" d"e	j+Z3G d#d$ d$e	j+Z4G d%d& d&e	j+Z5ed'e(G d(d) d)e.Z6G d*d+ d+e	j+Z7ed,e(G d-d. d.e.Z8ed/e(G d0d1 d1e.Z9ed2e(G d3d4 d4e.Z:dS )5z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   )LayoutLMv3Configr   zmicrosoft/layoutlmv3-basezmicrosoft/layoutlmv3-largeaM  
    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                       s*   e Zd ZdZ fddZdddZ  ZS )LayoutLMv3PatchEmbeddingszLayoutLMv3 image (patch) embeddings. This class also automatically interpolates the position embeddings for varying
    image sizes.c                    s   t    t|jtjjr |jn
|j|jf}t|jtjjrB|jn
|j|jf}|d |d  |d |d  f| _t	j
|j|j||d| _d S )Nr   r   )Zkernel_sizeZstride)super__init__
isinstance
input_sizecollectionsabcIterable
patch_sizepatch_shapennConv2dZnum_channelshidden_sizeproj)selfconfig
image_sizer   	__class__ q/var/www/html/Darija-Ai-API/env/lib/python3.8/site-packages/transformers/models/layoutlmv3/modeling_layoutlmv3.pyr      s    


"z"LayoutLMv3PatchEmbeddings.__init__Nc                 C   s   |  |}|d k	rp|d| jd | jd d}|dddd}|jd |jd  }}tj|||fdd}|| }|ddd}|S )Nr   r   r      Zbicubic)sizemode)	r#   viewr   permuteshapeFZinterpolateflatten	transpose)r$   pixel_valuesZposition_embedding
embeddingspatch_heightpatch_widthr)   r)   r*   forward   s    
z!LayoutLMv3PatchEmbeddings.forward)N__name__
__module____qualname____doc__r   r9   __classcell__r)   r)   r'   r*   r      s   r   c                       sB   e Zd ZdZ fddZdd Zdd Zdd	 ZdddZ  Z	S )LayoutLMv3TextEmbeddingszm
    LayoutLMv3 text embeddings. Same as `RobertaEmbeddings` but with added spatial (layout) embeddings.
    c                    s   t    tj|j|j|jd| _t|j|j| _	tj
|j|jd| _
t|j| _| jdt|jddd |j| _tj|j|j| jd| _t|j|j| _t|j|j| _t|j|j| _t|j|j| _d S )N)padding_idxZepsposition_ids)r   r+   F)
persistent)r   r   r    	EmbeddingZ
vocab_sizer"   Zpad_token_idword_embeddingsZtype_vocab_sizetoken_type_embeddings	LayerNormlayer_norm_epsDropouthidden_dropout_probdropoutZregister_buffertorcharangeZmax_position_embeddingsexpandrA   position_embeddingsZmax_2d_position_embeddingsZcoordinate_sizex_position_embeddingsy_position_embeddingsZ
shape_sizeh_position_embeddingsw_position_embeddingsr$   r%   r'   r)   r*   r      s(    
    z!LayoutLMv3TextEmbeddings.__init__c           
   
   C   s8  zt|  |d d d d df }| |d d d d df }|  |d d d d df }| |d d d d df }W n, tk
r } ztd|W 5 d }~X Y nX | t|d d d d df |d d d d df  dd}| t|d d d d df |d d d d df  dd}tj||||||gdd}	|	S )	Nr   r   r,   r   z;The `bbox` coordinate values should be within 0-1000 range.i  r+   dim)rQ   rR   
IndexErrorrS   rM   ZcliprT   cat)
r$   bboxZleft_position_embeddingsZupper_position_embeddingsZright_position_embeddingsZlower_position_embeddingserS   rT   spatial_position_embeddingsr)   r)   r*   %calculate_spatial_position_embeddings  s(     <<z>LayoutLMv3TextEmbeddings.calculate_spatial_position_embeddingsc                 C   s2   | | }tj|dd|| }| | 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   rV   )neintrM   ZcumsumZtype_aslong)r$   	input_idsrA   maskZincremental_indicesr)   r)   r*   "create_position_ids_from_input_ids   s    z;LayoutLMv3TextEmbeddings.create_position_ids_from_input_idsc                 C   sN   |  dd }|d }tj| jd || j d tj|jd}|d|S )z
        We are provided embeddings directly. We cannot infer which are padded so just generate sequential position ids.
        Nr+   r   dtypedevicer   )r-   rM   rN   rA   r`   rf   	unsqueezerO   )r$   inputs_embedsinput_shapeZsequence_lengthrC   r)   r)   r*   &create_position_ids_from_inputs_embeds*  s       z?LayoutLMv3TextEmbeddings.create_position_ids_from_inputs_embedsNc                 C   s   |d kr2|d k	r(|  || j|j}n
| |}|d k	rD| }n| d d }|d krrtj|tj| j	jd}|d kr| 
|}| |}|| }| |}	||	7 }| |}
||
 }| |}| |}|S )Nr+   rd   )rc   rA   torf   rj   r-   rM   zerosr`   rC   rF   rG   rP   r]   rH   rL   )r$   ra   rZ   token_type_idsrC   rh   ri   rG   r6   rP   r\   r)   r)   r*   r9   6  s,    







z LayoutLMv3TextEmbeddings.forward)NNNNN)
r;   r<   r=   r>   r   r]   rc   rj   r9   r?   r)   r)   r'   r*   r@      s   
     r@   c                   @   s    e Zd ZdZeZdZdd ZdS )LayoutLMv3PreTrainedModelz
    An abstract class to handle weights initialization and a simple interface for downloading and loading pretrained
    models.
    
layoutlmv3c                 C   s   t |tjtjfr@|jjjd| jjd |j	dk	r|j	j
  nft |tjr|jjjd| jjd |jdk	r|jj|j 
  n&t |tjr|j	j
  |jjd dS )zInitialize the weights        )ZmeanZstdNg      ?)r   r    Linearr!   weightdataZnormal_r%   Zinitializer_rangebiasZzero_rE   rA   rH   Zfill_)r$   moduler)   r)   r*   _init_weightsi  s    

z'LayoutLMv3PreTrainedModel._init_weightsN)r;   r<   r=   r>   r   config_classZbase_model_prefixrv   r)   r)   r)   r*   rn   `  s   rn   c                       s8   e Zd Z fddZdd ZdddZdd
dZ  ZS )LayoutLMv3SelfAttentionc                    s   t    |j|j dkr>t|ds>td|j d|j d|j| _t|j|j | _| j| j | _t	
|j| j| _t	
|j| j| _t	
|j| j| _t	|j| _|j| _|j| _d S )Nr   Z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    rq   querykeyvaluerJ   Zattention_probs_dropout_probrL   has_relative_attention_biashas_spatial_attention_biasrU   r'   r)   r*   r   {  s    
z LayoutLMv3SelfAttention.__init__c                 C   s6   |  d d | j| jf }|j| }|ddddS )Nr+   r   r,   r   r   )r-   rz   r}   r/   r0   )r$   xZnew_x_shaper)   r)   r*   transpose_for_scores  s    
z,LayoutLMv3SelfAttention.transpose_for_scores    c                 C   s6   || }|j ddd}|| | }tjd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.
        r+   rV   )Zamaxrg   r    ZSoftmax)r$   attention_scoresalphaZscaled_attention_scoresZ	max_valueZnew_attention_scoresr)   r)   r*   cogview_attention  s    z)LayoutLMv3SelfAttention.cogview_attentionNFc                 C   s"  |  |}| | |}| | |}	| |}
t|
t| j |	dd}| j
rz| jrz||| t| j 7 }n| j
r||t| j 7 }|d k	r|| }| |}| |}|d k	r|| }t||	}|dddd }| d d | jf }|j| }|r||fn|f}|S )Nr+   r   r,   r   r   )r   r   r   r   rM   matmulmathsqrtr}   r4   r   r   r   rL   r0   
contiguousr-   r~   r/   )r$   hidden_statesattention_mask	head_maskoutput_attentionsrel_pos
rel_2d_posZmixed_query_layerZ	key_layerZvalue_layerZquery_layerr   Zattention_probsZcontext_layerZnew_context_layer_shapeoutputsr)   r)   r*   r9     s*    	

 


zLayoutLMv3SelfAttention.forward)r   )NNFNN)r;   r<   r=   r   r   r   r9   r?   r)   r)   r'   r*   rx   z  s   
     rx   c                       s4   e Zd Z fddZejejejdddZ  ZS )LayoutLMv3SelfOutputc                    sB   t    t|j|j| _tj|j|jd| _t|j	| _
d S NrB   )r   r   r    rq   r"   denserH   rI   rJ   rK   rL   rU   r'   r)   r*   r     s    
zLayoutLMv3SelfOutput.__init__r   input_tensorreturnc                 C   s&   |  |}| |}| || }|S Nr   rL   rH   r$   r   r   r)   r)   r*   r9     s    

zLayoutLMv3SelfOutput.forwardr;   r<   r=   r   rM   ZTensorr9   r?   r)   r)   r'   r*   r     s   r   c                       s&   e Zd Z fddZdddZ  ZS )LayoutLMv3Attentionc                    s"   t    t|| _t|| _d S r   )r   r   rx   r$   r   outputrU   r'   r)   r*   r     s    

zLayoutLMv3Attention.__init__NFc           
      C   s<   | j ||||||d}| |d |}|f|dd   }	|	S )Nr   r   r   r   )r$   r   )
r$   r   r   r   r   r   r   Zself_outputsattention_outputr   r)   r)   r*   r9     s    	zLayoutLMv3Attention.forward)NNFNN)r;   r<   r=   r   r9   r?   r)   r)   r'   r*   r     s        r   c                       s.   e Zd Z fddZd	ddZdd Z  ZS )
LayoutLMv3Layerc                    s:   t    |j| _d| _t|| _t|| _t|| _	d S Nr   )
r   r   chunk_size_feed_forwardseq_len_dimr   	attentionLayoutLMv3IntermediateintermediateLayoutLMv3Outputr   rU   r'   r)   r*   r     s    


zLayoutLMv3Layer.__init__NFc                 C   sL   | j ||||||d}|d }|dd  }	t| j| j| j|}
|
f|	 }	|	S )N)r   r   r   r   r   )r   r   feed_forward_chunkr   r   )r$   r   r   r   r   r   r   Zself_attention_outputsr   r   layer_outputr)   r)   r*   r9   
  s$    	   
zLayoutLMv3Layer.forwardc                 C   s   |  |}| ||}|S r   )r   r   )r$   r   Zintermediate_outputr   r)   r)   r*   r   &  s    
z"LayoutLMv3Layer.feed_forward_chunk)NNFNN)r;   r<   r=   r   r9   r   r?   r)   r)   r'   r*   r     s        
r   c                	       s@   e Zd Z fddZdddZdd	 Zd
d ZdddZ  ZS )LayoutLMv3Encoderc                    s   t     | _t fddt jD | _d| _ j	| _	 j
| _
| j	rr j| _ j| _tj| j jdd| _| j
r j| _ j| _tj| j jdd| _tj| j jdd| _d S )Nc                    s   g | ]}t  qS r)   )r   ).0_r%   r)   r*   
<listcomp>0  s     z.LayoutLMv3Encoder.__init__.<locals>.<listcomp>F)rt   )r   r   r%   r    Z
ModuleListrangenum_hidden_layerslayergradient_checkpointingr   r   rel_pos_binsmax_rel_posrq   rz   rel_pos_biasmax_rel_2d_posrel_2d_pos_binsrel_pos_x_biasrel_pos_y_biasrU   r'   r   r*   r   -  s    
 zLayoutLMv3Encoder.__init__Tr      c           
      C   s   d}|r0|d }||dk  | 7 }t|}nt| t|}|d }||k }|t| | t||  ||  tj  }	t	|	t
|	|d }	|t|||	7 }|S )Nr   r,   r   )r`   rM   absmaxZ
zeros_likelogfloatr   rk   minZ	full_likewhere)
r$   Zrelative_positionbidirectionalnum_bucketsmax_distanceretnZ	max_exactZis_smallZval_if_larger)   r)   r*   relative_position_bucketA  s     &z*LayoutLMv3Encoder.relative_position_bucketc                 C   sP   | d| d }| j|| j| jd}| jj | dddd}| }|S )Nr   r+   r   r   r   r   r   r,   )	rg   r   r   r   r   rr   tr0   r   )r$   rC   Zrel_pos_matr   r)   r)   r*   _cal_1d_pos_embX  s    z!LayoutLMv3Encoder._cal_1d_pos_embc           	      C   s   |d d d d df }|d d d d df }| d| d }| d| d }| j|| j| jd}| j|| j| jd}| jj | dddd}| jj | dddd}|	 }|	 }|| }|S )Nr   r   r   r+   r   r   r,   )
rg   r   r   r   r   rr   r   r0   r   r   )	r$   rZ   Zposition_coord_xZposition_coord_yZrel_pos_x_2d_matZrel_pos_y_2d_matZ	rel_pos_xZ	rel_pos_yr   r)   r)   r*   _cal_2d_pos_embd  s(    z!LayoutLMv3Encoder._cal_2d_pos_embNFc              
   C   s  |rdnd }|rdnd }| j r(| |nd }| jr<| |nd }t| jD ]\}}|r`||f }|d k	rp|| nd }| jr| jrdd }tj	j

||||||||}n|||||||d}|d }|rJ||d f }qJ|r||f }|stdd |||fD S t|||d	S )
Nr)   c                    s    fdd}|S )Nc                     s    |  S r   r)   )inputsru   r)   r*   custom_forward  s    zPLayoutLMv3Encoder.forward.<locals>.create_custom_forward.<locals>.custom_forwardr)   )ru   r   r)   r   r*   create_custom_forward  s    z8LayoutLMv3Encoder.forward.<locals>.create_custom_forwardr   r   r   c                 s   s   | ]}|d k	r|V  qd S r   r)   )r   vr)   r)   r*   	<genexpr>  s   z,LayoutLMv3Encoder.forward.<locals>.<genexpr>Zlast_hidden_stater   
attentions)r   r   r   r   	enumerater   r   ZtrainingrM   utils
checkpointtupler
   )r$   r   rZ   r   r   r   output_hidden_statesreturn_dictrC   r7   r8   Zall_hidden_statesZall_self_attentionsr   r   iZlayer_moduleZlayer_head_maskr   Zlayer_outputsr)   r)   r*   r9   z  sX    


	
	zLayoutLMv3Encoder.forward)Tr   r   )	NNNFFTNNN)	r;   r<   r=   r   r   r   r   r9   r?   r)   r)   r'   r*   r   ,  s   
         r   c                       s0   e Zd Z fddZejejdddZ  ZS )r   c                    sB   t    t|j|j| _t|jt	r6t
|j | _n|j| _d S r   )r   r   r    rq   r"   intermediate_sizer   r   Z
hidden_actstrr	   intermediate_act_fnrU   r'   r)   r*   r     s
    
zLayoutLMv3Intermediate.__init__)r   r   c                 C   s   |  |}| |}|S r   )r   r   )r$   r   r)   r)   r*   r9     s    

zLayoutLMv3Intermediate.forwardr   r)   r)   r'   r*   r     s   r   c                       s4   e Zd Z fddZejejejdddZ  ZS )r   c                    sB   t    t|j|j| _tj|j|jd| _t	|j
| _d S r   )r   r   r    rq   r   r"   r   rH   rI   rJ   rK   rL   rU   r'   r)   r*   r     s    
zLayoutLMv3Output.__init__r   c                 C   s&   |  |}| |}| || }|S r   r   r   r)   r)   r*   r9     s    

zLayoutLMv3Output.forwardr   r)   r)   r'   r*   r     s   r   zdThe bare LayoutLMv3 Model transformer outputting raw hidden-states without any specific head on top.c                       s   e Zd Z fddZdd Zdd Zdd ZdddZdd Zdd Z	e
edeeeddeej eej eej eej eej eej eej eej ee ee ee eeef dddZ  ZS )LayoutLMv3Modelc                    s   t  | || _|jr"t|| _|jrt|| _t	|j
|j }ttdd|j| _ttd|| d |j| _tjdd| _tj|j|jd| _t|j| _| jjs| jjr| j||fd tj|jdd| _t|| _|   d S )Nr   rp   )prB   )r&   gư>) r   r   r%   Z
text_embedr@   r6   Zvisual_embedr   patch_embedr_   r   r   r    	ParameterrM   rl   r"   	cls_token	pos_embedrJ   pos_droprH   rI   rK   rL   r   r   init_visual_bboxnormr   encoderinit_weights)r$   r%   r-   r'   r)   r*   r     s"    

 
zLayoutLMv3Model.__init__c                 C   s   | j jS r   r6   rF   )r$   r)   r)   r*   get_input_embeddings  s    z$LayoutLMv3Model.get_input_embeddingsc                 C   s   || j _d S r   r   )r$   r   r)   r)   r*   set_input_embeddings  s    z$LayoutLMv3Model.set_input_embeddingsc                 C   s*   |  D ]\}}| jj| j| qdS )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   Zprune_heads)r$   Zheads_to_pruner   Zheadsr)   r)   r*   _prune_heads  s    zLayoutLMv3Model._prune_heads   r     c                 C   s  t jt d||d d  ||d dd}t jt d||d d  ||d dd}t j|dd |d d|dd |d ddd|dd |d d|dd |d dddgdddd}t dd|d |d gg}t j||gdd| _	dS )	zJ
        Create the bounding boxes for the visual (patch) tokens.
        r   r   trunc)Zrounding_modeNr+   rV      )
rM   divrN   stackrepeatr4   r/   ZtensorrY   visual_bbox)r$   r&   max_lenZvisual_bbox_xZvisual_bbox_yr   Zcls_token_boxr)   r)   r*   r     s.         
z LayoutLMv3Model.init_visual_bboxc                 C   s$   | j |dd}|||}|S r   )r   r   rk   type)r$   rf   re   
batch_sizer   r)   r)   r*   calculate_visual_bbox0  s    z%LayoutLMv3Model.calculate_visual_bboxc                 C   sf   |  |}| \}}}| j|dd}tj||fdd}| jd k	rN|| j }| |}| |}|S )Nr+   r   rV   )	r   r-   r   rO   rM   rY   r   r   r   )r$   r5   r6   r   Zseq_lenr   Z
cls_tokensr)   r)   r*   forward_image5  s    




zLayoutLMv3Model.forward_imagez!batch_size, token_sequence_lengthoutput_typerw   N)ra   rZ   r   rm   rC   r   rh   r5   r   r   r   r   c                 C   s  |	dk	r|	n| j j}	|
dk	r |
n| j j}
|dk	r4|n| j j}|dk	r\| }|\}}|j}nH|dk	r| dd }|\}}|j}n |dk	rt|}|j}ntd|dk	s|dk	r(|dkrtj	||f|d}|dkrtj
|tj|d}|dkrtj
tt|dg tj|d}| j|||||d}d }}d }}|dk	rt|jd | j j t|jd	 | j j  }}| |}tj	||jd
 ftj|d}|dk	rtj||gd
d}n|}| j js| j jr|| j jr
| j|tj|d}|dk	rtj||gd
d}n|}tjd|jd
 tj|d|d
}|dk	s@|dk	rxtjd|d
 |dd}||}tj||gd
d}n|}|dk	s|dk	rtj||gd
d}n|}| |}| |}nV| j js| j jr| j jr|}| j jr| jjddd|d
 f }||}|}| j|d||j d}| !|| j j"}| j#||||||	|
|||d
}|d }|sv|f|d
d  S t$||j%|j&d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")
        >>> 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
        ```Nr+   zEYou have to specify either input_ids or inputs_embeds or pixel_values)rf   rd   r   )ra   rZ   rC   rm   rh   r,   r   r   rV   )re   r   r   )re   )	rZ   rC   r   r   r   r   r   r7   r8   r   )'r%   r   r   use_return_dictr-   rf   lenr|   rM   Zonesrl   r`   r   listr6   r_   r1   r   r   rY   r   r   r   rN   r   rg   rO   rH   rL   rC   Z	expand_asZget_extended_attention_maskre   Zget_head_maskr   r   r
   r   r   )r$   ra   rZ   r   rm   rC   r   rh   r5   r   r   r   ri   r   
seq_lengthrf   Zembedding_outputZ
final_bboxZfinal_position_idsr7   r8   Zvisual_embeddingsZvisual_attention_maskr   Zvisual_position_idsZextended_attention_maskZencoder_outputssequence_outputr)   r)   r*   r9   F  s    )
 

  


    




   	zLayoutLMv3Model.forward)r   r   )NNNNNNNNNNN)r;   r<   r=   r   r   r   r   r   r   r   r   !LAYOUTLMV3_MODEL_INPUTS_DOCSTRINGformatr   r
   _CONFIG_FOR_DOCr   rM   
LongTensorFloatTensorboolr   r   r9   r?   r)   r)   r'   r*   r     sH   

           
r   c                       s*   e Zd ZdZd fdd	Zdd Z  ZS )LayoutLMv3ClassificationHeadz\
    Head for sentence-level classification tasks. Reference: RobertaClassificationHead
    Fc                    sv   t    || _|r,t|jd |j| _nt|j|j| _|jd k	rN|jn|j}t	|| _
t|j|j| _d S )Nr   )r   r   pool_featurer    rq   r"   r   classifier_dropoutrK   rJ   rL   
num_labelsout_proj)r$   r%   r  r  r'   r)   r*   r     s    
z%LayoutLMv3ClassificationHead.__init__c                 C   s6   |  |}| |}t|}|  |}| |}|S r   )rL   r   rM   tanhr  )r$   r   r)   r)   r*   r9     s    




z$LayoutLMv3ClassificationHead.forward)Fr:   r)   r)   r'   r*   r    s   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                       s   e Zd Z fddZeedeee	dd	e
ej e
ej e
ej e
ej e
ej e
ej e
ej e
ej e
e e
e e
e e
ej eeef dddZ  ZS )
 LayoutLMv3ForTokenClassificationc                    sd   t  | |j| _t|| _t|j| _|jdk rJt	|j
|j| _nt|dd| _|   d S )N
   Fr  )r   r   r  r   ro   r    rJ   rK   rL   rq   r"   
classifierr  r   rU   r'   r)   r*   r     s    

z)LayoutLMv3ForTokenClassification.__init__batch_size, sequence_lengthr   N)ra   rZ   r   rm   rC   r   rh   labelsr   r   r   r5   r   c                 C   s   |dk	r|n| j j}| j||||||||	|
||d}|dk	rF| }n| dd }|d }|d ddd|f }| |}| |}d}|dk	rt }||d| j|d}|s|f|dd  }|dk	r|f| S |S t	|||j
|jdS )aR  
        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")
        >>> 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)
rZ   r   rm   rC   r   rh   r   r   r   r5   r+   r   r   losslogitsr   r   )r%   r  ro   r-   rL   r  r   r/   r  r   r   r   )r$   ra   rZ   r   rm   rC   r   rh   r  r   r   r   r5   r   ri   r  r  r  r  loss_fctr   r)   r)   r*   r9     sD    /


z(LayoutLMv3ForTokenClassification.forward)NNNNNNNNNNNN)r;   r<   r=   r   r   &LAYOUTLMV3_DOWNSTREAM_INPUTS_DOCSTRINGr  r   r   r  r   rM   r	  r
  r  r   r   r9   r?   r)   r)   r'   r*   r    s@   

            
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                       s   e Zd Z fddZeedeee	dd	e
ej e
ej e
ej e
ej e
ej e
ej e
ej e
ej e
e e
e e
e e
ej e
ej eeef dddZ  ZS )
LayoutLMv3ForQuestionAnsweringc                    s8   t  | |j| _t|| _t|dd| _|   d S NFr  )r   r   r  r   ro   r  
qa_outputsr   rU   r'   r)   r*   r   |  s
    
z'LayoutLMv3ForQuestionAnswering.__init__r  r   N)ra   r   rm   rC   r   rh   start_positionsend_positionsr   r   r   rZ   r5   r   c                 C   sT  |dk	r|n| j j}| j|||||||	|
|||d}|d }| |}|jddd\}}|d }|d }d}|dk	r|dk	rt| dkr|d}t| dkr|d}|d}|	d|}|	d|}t
|d}|||}|||}|| d }|s>||f|dd  }|dk	r:|f| S |S t||||j|jd	S )
aB  
        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")
        >>> 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   rm   rC   r   rh   r   r   r   rZ   r5   r   r   r+   rV   )Zignore_indexr,   )r  start_logits
end_logitsr   r   )r%   r  ro   r  splitsqueezer   r  r-   clampr   r   r   r   )r$   ra   r   rm   rC   r   rh   r   r!  r   r   r   rZ   r5   r   r  r  r#  r$  Z
total_lossZignored_indexr  Z
start_lossZend_lossr   r)   r)   r*   r9     sT    ;






z&LayoutLMv3ForQuestionAnswering.forward)NNNNNNNNNNNNN)r;   r<   r=   r   r   r  r  r   r   r  r   rM   r	  r
  r  r   r   r9   r?   r)   r)   r'   r*   r  s  sD   		
             
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                       s   e Zd Z fddZeedeee	dd	e
ej e
ej e
ej e
ej e
ej e
ej e
ej e
e e
e e
e e
ej e
ej eeef dddZ  ZS )
#LayoutLMv3ForSequenceClassificationc                    s>   t  | |j| _|| _t|| _t|dd| _|   d S r  )	r   r   r  r%   r   ro   r  r  r   rU   r'   r)   r*   r     s    
z,LayoutLMv3ForSequenceClassification.__init__r  r   N)ra   r   rm   rC   r   rh   r  r   r   r   rZ   r5   r   c                 C   s  |
dk	r|
n| j j}
| j||||||||	|
||d}|d dddddf }| |}d}|dk	rD| j jdkr| jdkrd| j _n4| jdkr|jtjks|jtj	krd| j _nd| j _| j jdkrt
 }| jdkr|| | }n
|||}nN| j jdkr&t }||d| j|d}n| j jdkrDt }|||}|
st|f|dd  }|dk	rp|f| S |S t|||j|jd	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")
        >>> 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   Z
regressionZsingle_label_classificationZmulti_label_classificationr+   r  )r%   r  ro   r  Zproblem_typer  re   rM   r`   r_   r   r&  r   r/   r   r   r   r   )r$   ra   r   rm   rC   r   rh   r  r   r   r   rZ   r5   r   r  r  r  r  r   r)   r)   r*   r9     sX    -



"


z+LayoutLMv3ForSequenceClassification.forward)NNNNNNNNNNNN)r;   r<   r=   r   r   r  r  r   r   r  r   rM   r	  r
  r  r   r   r9   r?   r)   r)   r'   r*   r(    s@   		
            
r(  );r>   r   r   typingr   r   r   rM   Ztorch.nnr    Ztorch.nn.functionalZ
functionalr2   Ztorch.utils.checkpointr   r   r   Zactivationsr	   Zmodeling_outputsr
   r   r   r   Zmodeling_utilsr   Zpytorch_utilsr   r   r   r   r   r   Zconfiguration_layoutlmv3r   Z
get_loggerr;   loggerr  Z(LAYOUTLMV3_PRETRAINED_MODEL_ARCHIVE_LISTZLAYOUTLMV3_START_DOCSTRINGr  r  Moduler   r@   rn   rx   r   r   r   r   r   r   r   r  r  r  r(  r)   r)   r)   r*   <module>   sn   
L>#v[+   {	hz