o
    Zh                     @   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 ddl m!Z! e"e#Z$G dd de	j%Z&G dd de	j%Z'eG dd deZ(G dd de	j%Z)G dd de	j%Z*G dd de	j%Z+G dd de	j%Z,G dd de	j%Z-G dd de	j%Z.G dd  d e	j%Z/eG d!d" d"e(Z0G d#d$ d$e	j%Z1ed%d&G d'd( d(e(Z2eG d)d* d*e(Z3ed+d&G d,d- d-e(Z4g d.Z5dS )/zPyTorch LayoutLMv3 model.    N)OptionalTupleUnion)BCEWithLogitsLossCrossEntropyLossMSELoss   )ACT2FN)BaseModelOutputQuestionAnsweringModelOutputSequenceClassifierOutputTokenClassifierOutput)PreTrainedModel)apply_chunking_to_forward)auto_docstringlogging	torch_int   )LayoutLMv3Configc                       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r!|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__ a/var/www/auris/lib/python3.10/site-packages/transformers/models/layoutlmv3/modeling_layoutlmv3.pyr   3   s   


"z"LayoutLMv3PatchEmbeddings.__init__Nc                 C   s   |  |}|d ur8|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)   forwardC   s   
z!LayoutLMv3PatchEmbeddings.forwardN__name__
__module____qualname____doc__r   r8   __classcell__r(   r(   r&   r)   r   /   s    r   c                       sL   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   W   s    
z!LayoutLMv3TextEmbeddings.__init__c           
   
   C   s.  z:|  |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yK } ztd|d }~ww | 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_embeddingsn   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 u r|d ur|  || j|j}n| |}|d ur"| }n| d d }|d u r9tj|tj| j	jd}|d u rB| 
|}| |}|| }| |}	||	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   r5   rP   r\   r(   r(   r)   r8      s,   







z LayoutLMv3TextEmbeddings.forward)NNNNN)
r;   r<   r=   r>   r   r]   rc   rj   r8   r?   r(   r(   r&   r)   r@   R   s    
r@   c                   @   s   e Zd ZeZdZdd ZdS )LayoutLMv3PreTrainedModel
layoutlmv3c                 C   s   t |tjtjfr#|jjjd| jjd |j	dur!|j	j
  dS dS t |tjrF|jjjd| jjd |jdurD|jj|j 
  dS dS t |tjr[|j	j
  |jjd dS t |trr| jjrt|jj
  |jj
  dS dS dS )zInitialize the weights        )meanZstdNg      ?)r   r   Linearr    weightdataZnormal_r$   Zinitializer_rangebiasZzero_rE   rA   rH   Zfill_LayoutLMv3Modelvisual_embed	cls_token	pos_embed)r#   moduler(   r(   r)   _init_weights   s&   


z'LayoutLMv3PreTrainedModel._init_weightsN)r;   r<   r=   r   Zconfig_classZbase_model_prefixr{   r(   r(   r(   r)   rn      s    rn   c                       sB   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   rr   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,   r~   r   r.   r/   )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
r=| jr=||| t| j 7 }n| j
rJ||t| j 7 }|d urR|| }| |}| |}|d urd|| }t||	}|dddd }| d d | jf }|j| }|r||f}|S |f}|S )Nr*   r   r+   r   r   )r   r   r   r   rM   matmulmathsqrtr   r3   r   r   r   rL   r/   
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)   r8     s.   
	
 


zLayoutLMv3SelfAttention.forward)r   NNFNN)r;   r<   r=   r   r   r   r8   r?   r(   r(   r&   r)   r|      s    
r|   c                       8   e Zd Z fddZdejdejdejfddZ  ZS )LayoutLMv3SelfOutputc                    sB   t    t|j|j| _tj|j|jd| _t|j	| _
d S NrB   )r   r   r   rr   r!   denserH   rI   rJ   rK   rL   rU   r&   r(   r)   r   >     
zLayoutLMv3SelfOutput.__init__r   input_tensorreturnc                 C   &   |  |}| |}| || }|S r9   r   rL   rH   r#   r   r   r(   r(   r)   r8   D     

zLayoutLMv3SelfOutput.forwardr;   r<   r=   r   rM   ZTensorr8   r?   r(   r(   r&   r)   r   =      $r   c                       s0   e Zd Z fddZ					dddZ  ZS )LayoutLMv3Attentionc                    s"   t    t|| _t|| _d S r9   )r   r   r|   r#   r   outputrU   r&   r(   r)   r   M  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)   r8   R  s   	zLayoutLMv3Attention.forwardr   )r;   r<   r=   r   r8   r?   r(   r(   r&   r)   r   L  s    r   c                       s8   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   j  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)   r8   r  s   	
zLayoutLMv3Layer.forwardc                 C   s   |  |}| ||}|S r9   )r   r   )r#   r   Zintermediate_outputr   r(   r(   r)   r     s   
z"LayoutLMv3Layer.feed_forward_chunkr   )r;   r<   r=   r   r8   r   r?   r(   r(   r&   r)   r   i  s    
r   c                       sR   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	r9 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 d S )Nc                    s   g | ]}t  qS r(   )r   ).0_r$   r(   r)   
<listcomp>  s    z.LayoutLMv3Encoder.__init__.<locals>.<listcomp>F)ru   )r   r   r$   r   Z
ModuleListrangenum_hidden_layerslayergradient_checkpointingr   r   rel_pos_binsmax_rel_posrr   r~   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}|r|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_bucket  s   &z*LayoutLMv3Encoder.relative_position_bucketc                 C   sx   | d| d }| j|| j| jd}t  | jj | 	dddd}W d    n1 s1w   Y  |
 }|S )Nr   r*   r   r   r   r   r   r+   )rg   r   r   r   rM   no_gradr   rs   tr/   r   )r#   rC   Zrel_pos_matr   r(   r(   r)   _cal_1d_pos_emb  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}t $ | jj | 	dddd}| j
j | 	dddd}W d    n1 siw   Y  | }| }|| }|S )Nr   r   r   r*   r   r   r+   )rg   r   r   r   rM   r   r   rs   r   r/   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_emb  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 ]?\}}|r0||f }|d ur8|| nd }| jrM| jrM| |j	||||||}n
|||||||d}|d }|rd||d f }q%|rl||f }|szt
dd |||fD S t|||dS )Nr(   r   r   r   c                 s   s    | ]	}|d ur|V  qd S r9   r(   )r   vr(   r(   r)   	<genexpr>!  s    z,LayoutLMv3Encoder.forward.<locals>.<genexpr>Zlast_hidden_stater   
attentions)r   r   r   r   	enumerater   r   ZtrainingZ_gradient_checkpointing_func__call__tupler
   )r#   r   rZ   r   r   r   output_hidden_statesreturn_dictrC   r6   r7   Zall_hidden_statesZall_self_attentionsr   r   iZlayer_moduleZlayer_head_maskZlayer_outputsr(   r(   r)   r8     sX   

	
	zLayoutLMv3Encoder.forward)Tr   r   )	NNNFFTNNN)	r;   r<   r=   r   r   r   r   r8   r?   r(   r(   r&   r)   r     s    
r   c                       s2   e Zd Z fddZdejdejfddZ  ZS )r   c                    sD   t    t|j|j| _t|jt	rt
|j | _d S |j| _d S r9   )r   r   r   rr   r!   intermediate_sizer   r   Z
hidden_actstrr	   intermediate_act_fnrU   r&   r(   r)   r   3  s
   
zLayoutLMv3Intermediate.__init__r   r   c                 C   s   |  |}| |}|S r9   )r   r   )r#   r   r(   r(   r)   r8   ;  s   

zLayoutLMv3Intermediate.forwardr   r(   r(   r&   r)   r   2  s    r   c                       r   )r   c                    sB   t    t|j|j| _tj|j|jd| _t	|j
| _d S r   )r   r   r   rr   r   r!   r   rH   rI   rJ   rK   rL   rU   r&   r(   r)   r   C  r   zLayoutLMv3Output.__init__r   r   r   c                 C   r   r9   r   r   r(   r(   r)   r8   I  r   zLayoutLMv3Output.forwardr   r(   r(   r&   r)   r   B  r   r   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
											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dZ  ZS )"rv   c                    s   t  | || _|jrt|| _|jrnt|| _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re| j||fd tj|jdd| _t|| _|   d S )Nr   rp   )prB   )r%   gư>) r   r   r$   Z
text_embedr@   r5   rw   r   patch_embedr_   r   r   r   	ParameterrM   rl   r!   rx   ry   rJ   pos_droprH   rI   rK   rL   r   r   init_visual_bboxnormr   encoderinit_weights)r#   r$   r,   r&   r(   r)   r   R  s"   

 
zLayoutLMv3Model.__init__c                 C   s   | j jS r9   r5   rF   )r#   r(   r(   r)   get_input_embeddingso  s   z$LayoutLMv3Model.get_input_embeddingsc                 C   s   || j _d S r9   r   )r#   r   r(   r(   r)   set_input_embeddingsr  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_headsu  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repeatr3   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_bbox  s   z%LayoutLMv3Model.calculate_visual_bboxc                 C   sf   |  |}| \}}}| j|dd}tj||fdd}| jd ur'|| j }| |}| |}|S )Nr*   r   rV   )	r   r,   rx   rO   rM   rY   ry   r   r   )r#   r4   r5   r   Zseq_lenr   Z
cls_tokensr(   r(   r)   forward_image  s   




zLayoutLMv3Model.forward_imageNra   rZ   r   rm   rC   r   rh   r4   r   r   r   r   c                 C   s|  |	dur|	n| j j}	|
dur|
n| j j}
|dur|n| j j}|dur.| }|\}}|j}n$|durB| dd }|\}}|j}n|durNt|}|j}ntd|dusZ|dur|du rgtj	||f|d}|du rttj
|tj|d}|du rtj
tt|dg tj|d}| j|||||d}d }}d }}|durYt|jd | j j t|jd	 | j j }}| |}tj	||jd
 ftj|d}|durtj||gd
d}n|}| j js| j jr8| j jr| j|tj|d}|durtj||gd
d}n|}tjd|jd
 tj|d|d
}|dus|dur6tjd|d
 |dd}||}tj||gd
d}n|}|dusB|durLtj||gd
d}n|}| |}| |}n+| j jsc| j jr| j jrj|}| j jr| jjddd|d
 f }||}|}| j|d||j d}| !|| j j"}| j#||||||	|
|||d
}|d }|s|f|d
d  S t$||j%|j&dS )a  
        input_ids (`torch.LongTensor` of shape `(batch_size, token_sequence_length)`):
            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 `(batch_size, token_sequence_length, 4)`, *optional*):
            Bounding boxes of each input sequence tokens. Selected in the range `[0,
            config.max_2d_position_embeddings-1]`. Each bounding box should be a normalized version in (x0, y0, x1, y1)
            format, where (x0, y0) corresponds to the position of the upper left corner in the bounding box, and (x1,
            y1) represents the position of the lower right corner.

            Note that `sequence_length = token_sequence_length + patch_sequence_length + 1` where `1` is for [CLS]
            token. See `pixel_values` for `patch_sequence_length`.
        token_type_ids (`torch.LongTensor` of shape `(batch_size, token_sequence_length)`, *optional*):
            Segment token indices to indicate first and second portions of the inputs. Indices are selected in `[0,
            1]`:

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

            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 `(batch_size, token_sequence_length)`, *optional*):
            Indices of positions of each input sequence tokens in the position embeddings. Selected in the range `[0,
            config.max_position_embeddings - 1]`.

            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)
        inputs_embeds (`torch.FloatTensor` of shape `(batch_size, token_sequence_length, 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.

        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
        ```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   r6   r7   r   )'r$   r   r   use_return_dictr,   rf   lenr   rM   Zonesrl   r`   r   listr5   r   r0   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   r4   r   r   r   ri   r   
seq_lengthrf   Zembedding_outputZ
final_bboxZfinal_position_idsr6   r7   Zvisual_embeddingsZvisual_attention_maskr   Zvisual_position_idsZextended_attention_maskZencoder_outputssequence_outputr(   r(   r)   r8     s   N 







	zLayoutLMv3Model.forward)r   r   )NNNNNNNNNNN)r;   r<   r=   r   r   r   r   r   r   r   r   r   rM   
LongTensorFloatTensorboolr   r   r
   r8   r?   r(   r(   r&   r)   rv   P  sZ    
	

rv   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 ur'|jn|j}t	|| _
t|j|j| _d S )Nr   )r   r   pool_featurer   rr   r!   r   classifier_dropoutrK   rJ   rL   
num_labelsout_proj)r#   r$   r	  r
  r&   r(   r)   r   v  s   
z%LayoutLMv3ClassificationHead.__init__c                 C   s6   |  |}| |}t|}|  |}| |}|S r9   )rL   r   rM   tanhr  )r#   r   r(   r(   r)   r8     s   




z$LayoutLMv3ClassificationHead.forward)Fr:   r(   r(   r&   r)   r  q  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).
    )Zcustom_introc                       s   e Zd Z fddZ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dZ  ZS ) LayoutLMv3ForTokenClassificationc                    sd   t  | |j| _t|| _t|j| _|jdk r%t	|j
|j| _nt|dd| _|   d S )N
   Fr	  )r   r   r  rv   ro   r   rJ   rK   rL   rr   r!   
classifierr  r   rU   r&   r(   r)   r     s   

z)LayoutLMv3ForTokenClassification.__init__Nra   rZ   r   rm   rC   r   rh   labelsr   r   r   r4   r   c                 C   s   |dur|n| j j}| j||||||||	|
||d}|dur#| }n| dd }|d }|d ddd|f }| |}| |}d}|dur[t }||d| j|d}|sq|f|dd  }|duro|f| S |S t	|||j
|jdS )a9  
        bbox (`torch.LongTensor` of shape `(batch_size, sequence_length, 4)`, *optional*):
            Bounding boxes of each input sequence tokens. Selected in the range `[0,
            config.max_2d_position_embeddings-1]`. Each bounding box should be a normalized version in (x0, y0, x1, y1)
            format, where (x0, y0) corresponds to the position of the upper left corner in the bounding box, and (x1,
            y1) represents the position of the lower right corner.
        labels (`torch.LongTensor` of shape `(batch_size, sequence_length)`, *optional*):
            Labels for computing the token classification loss. Indices should be in `[0, ..., config.num_labels - 1]`.

        Examples:

        ```python
        >>> from transformers import 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)
rZ   r   rm   rC   r   rh   r   r   r   r4   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   r4   r   ri   r  r  r  r  loss_fctr   r(   r(   r)   r8     sD   /


z(LayoutLMv3ForTokenClassification.forwardNNNNNNNNNNNN)r;   r<   r=   r   r   r   rM   r  r  r  r   r   r   r8   r?   r(   r(   r&   r)   r    sT    		

r  c                        s   e Zd Z fddZ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dZ  ZS )LayoutLMv3ForQuestionAnsweringc                    s8   t  | |j| _t|| _t|dd| _|   d S NFr  )r   r   r  rv   ro   r  
qa_outputsr   rU   r&   r(   r)   r     s
   
z'LayoutLMv3ForQuestionAnswering.__init__Nra   r   rm   rC   r   rh   start_positionsend_positionsr   r   r   rZ   r4   r   c                 C   sL  |dur|n| j j}| j|||||||	|
|||d}|d }| |}|jddd\}}|d }|d }d}|dur|durt| dkrQ|d}t| dkr^|d}|d}|	d|}|	d|}t
|d}|||}|||}|| d }|s||f|dd  }|dur|f| S |S t||||j|jd	S )
a/  
        bbox (`torch.LongTensor` of shape `(batch_size, sequence_length, 4)`, *optional*):
            Bounding boxes of each input sequence tokens. Selected in the range `[0,
            config.max_2d_position_embeddings-1]`. Each bounding box should be a normalized version in (x0, y0, x1, y1)
            format, where (x0, y0) corresponds to the position of the upper left corner in the bounding box, and (x1,
            y1) represents the position of the lower right corner.

        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   rm   rC   r   rh   r   r   r   rZ   r4   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   r4   r   r  r  r  r  Z
total_lossZignored_indexr  Z
start_lossZend_lossr   r(   r(   r)   r8     sT   3






z&LayoutLMv3ForQuestionAnswering.forward)NNNNNNNNNNNNN)r;   r<   r=   r   r   r   rM   r  r  r  r   r   r   r8   r?   r(   r(   r&   r)   r    sZ    		

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												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dZ  ZS )#LayoutLMv3ForSequenceClassificationc                    s>   t  | |j| _|| _t|| _t|dd| _|   d S r  )	r   r   r  r$   rv   ro   r  r  r   rU   r&   r(   r)   r   w  s   
z,LayoutLMv3ForSequenceClassification.__init__Nra   r   rm   rC   r   rh   r  r   r   r   rZ   r4   r   c                 C   s~  |
dur|
n| j j}
| j||||||||	|
||d}|d dddddf }| |}d}|dur| j jdu r\| jdkrBd| j _n| jdkrX|jtjksS|jtj	krXd| j _nd| j _| j jdkrzt
 }| jdkrt|| | }n+|||}n%| j jdkrt }||d| j|d}n| j jdkrt }|||}|
s|f|dd  }|dur|f| S |S t|||j|jd	S )
aw  
        bbox (`torch.LongTensor` of shape `(batch_size, sequence_length, 4)`, *optional*):
            Bounding boxes of each input sequence tokens. Selected in the range `[0,
            config.max_2d_position_embeddings-1]`. Each bounding box should be a normalized version in (x0, y0, x1, y1)
            format, where (x0, y0) corresponds to the position of the upper left corner in the bounding box, and (x1,
            y1) represents the position of the lower right corner.

        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   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   r4   r   r  r  r  r  r   r(   r(   r)   r8     sX   .


"


z+LayoutLMv3ForSequenceClassification.forwardr  )r;   r<   r=   r   r   r   rM   r  r  r  r   r   r   r8   r?   r(   r(   r&   r)   r#  o  sT    		

r#  )r  r#  r  rv   rn   )6r>   r   r   typingr   r   r   rM   Ztorch.nnr   Ztorch.nn.functionalZ
functionalr1   Ztorch.utils.checkpointr   r   r   Zactivationsr	   Zmodeling_outputsr
   r   r   r   Zmodeling_utilsr   Zpytorch_utilsr   utilsr   r   r   Zconfiguration_layoutlmv3r   Z
get_loggerr;   loggerModuler   r@   rn   r|   r   r   r   r   r   r   rv   r  r  r  r#  __all__r(   r(   r(   r)   <module>   sX   
#v[+   "hrn