U
    9%e                     @   s<  d Z ddlZddlmZmZmZ ddlZddlZddlmZ ddl	m
Z
mZmZ ddlmZ ddlmZ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mZ ddl m!Z! e rddl"Z"ddl#m$Z$ e%e&Z'dZ(dZ)ddg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+Z0G dd dej+Z1G dd dej+Z2d=d#d$Z3G d%d& d&ej+Z4G d'd( d(eZ5d>d)d*Z6G d+d, d,ej+Z7d-Z8d.Z9G d/d0 d0ej+Z:ed1e8G d2d3 d3e5Z;ed4e8G d5d6 d6e5Z<ed7e8G d8d9 d9e5Z=ed:e8G d;d< d<e5Z>dS )?z PyTorch LayoutLMv2 model.    N)OptionalTupleUnion)nn)BCEWithLogitsLossCrossEntropyLossMSELoss   )ACT2FN)BaseModelOutputBaseModelOutputWithPoolingQuestionAnsweringModelOutputSequenceClassifierOutputTokenClassifierOutput)PreTrainedModel)apply_chunking_to_forward)add_start_docstrings%add_start_docstrings_to_model_forwardis_detectron2_availableloggingreplace_return_docstringsrequires_backends   )LayoutLMv2Config)META_ARCH_REGISTRYz!microsoft/layoutlmv2-base-uncasedr   z"microsoft/layoutlmv2-large-uncasedc                       s(   e Zd ZdZ fddZdd Z  ZS )LayoutLMv2EmbeddingszGConstruct the embeddings from word, position and token_type embeddings.c                    s   t t|   tj|j|j|jd| _t|j	|j| _
t|j|j| _t|j|j| _t|j|j| _t|j|j| _t|j|j| _tj|j|jd| _t|j| _| jdt|j	ddd d S )N)padding_idxepsposition_ids)r   F
persistent)superr   __init__r   	EmbeddingZ
vocab_sizehidden_sizeZpad_token_idword_embeddingsZmax_position_embeddingsposition_embeddingsZmax_2d_position_embeddingsZcoordinate_sizex_position_embeddingsy_position_embeddingsZ
shape_sizeh_position_embeddingsw_position_embeddingsZtype_vocab_sizetoken_type_embeddings	LayerNormlayer_norm_epsDropouthidden_dropout_probdropoutregister_buffertorcharangeexpandselfconfig	__class__ q/var/www/html/Darija-Ai-API/env/lib/python3.8/site-packages/transformers/models/layoutlmv2/modeling_layoutlmv2.pyr$   B   s      zLayoutLMv2Embeddings.__init__c           
   
   C   s$  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 | |d d d d df |d d d d df  }| |d d d d df |d d d d df  }tj||||||gdd}	|	S )Nr   r      r	   z;The `bbox` coordinate values should be within 0-1000 range.r    dim)r)   r*   
IndexErrorr+   r,   r4   cat)
r8   bboxZleft_position_embeddingsZupper_position_embeddingsZright_position_embeddingsZlower_position_embeddingser+   r,   spatial_position_embeddingsr<   r<   r=   !_calc_spatial_position_embeddingsT   s(     22z6LayoutLMv2Embeddings._calc_spatial_position_embeddings)__name__
__module____qualname____doc__r$   rF   __classcell__r<   r<   r:   r=   r   ?   s   r   c                       s6   e Zd Z fddZdd Zdd Zdd	d
Z  ZS )LayoutLMv2SelfAttentionc                    s  t    |j|j dkr>t|ds>td|j d|j d|j| _|j| _t|j|j | _| j| j | _	|j
| _
|j| _|jrtj|jd| j	 dd| _ttd	d	| j	| _ttd	d	| j	| _n6t|j| j	| _t|j| j	| _t|j| j	| _t|j| _d S )
Nr   Zembedding_sizezThe hidden size (z6) is not a multiple of the number of attention heads ()r	   Fbiasr   )r#   r$   r&   num_attention_headshasattr
ValueErrorfast_qkvintattention_head_sizeall_head_sizehas_relative_attention_biashas_spatial_attention_biasr   Linear
qkv_linear	Parameterr4   zerosq_biasv_biasquerykeyvaluer0   Zattention_probs_dropout_probr2   r7   r:   r<   r=   r$   o   s&    
z LayoutLMv2SelfAttention.__init__c                 C   s6   |  d d | j| jf }|j| }|ddddS )Nr    r   r>   r   r	   )sizerP   rU   viewpermute)r8   xZnew_x_shaper<   r<   r=   transpose_for_scores   s    
z,LayoutLMv2SelfAttention.transpose_for_scoresc                 C   s   | j r| |}tj|ddd\}}}| | j krN|| j }|| j }qd| d  d }|| jj|  }|| jj|  }n| |}| 	|}| 
|}|||fS )Nr	   r    r?   r   r   )r    )rS   rZ   r4   chunkZ
ndimensionr]   r^   rc   r_   r`   ra   )r8   hidden_statesZqkvqkvZ_szr<   r<   r=   compute_qkv   s    




z#LayoutLMv2SelfAttention.compute_qkvNFc                 C   s  |  |\}}}	| |}
| |}| |	}|
t| j }
t|
|dd}| jr`||7 }| j	rn||7 }|
 |tjt|jj}tjj|dtjd|}| |}|d k	r|| }t||}|dddd }| d d | jf }|j| }|r||fn|f}|S )Nr    )r@   dtyper   r>   r   r	   )rm   rf   mathsqrtrU   r4   matmul	transposerW   rX   floatZmasked_fill_toboolfinforo   minr   Z
functionalZsoftmaxZfloat32Ztype_asr2   rd   
contiguousrb   rV   rc   )r8   ri   attention_mask	head_maskoutput_attentionsrel_pos
rel_2d_posrj   rk   rl   Zquery_layerZ	key_layerZvalue_layerZattention_scoresZattention_probsZcontext_layerZnew_context_layer_shapeoutputsr<   r<   r=   forward   s0    	



 

zLayoutLMv2SelfAttention.forward)NNFNN)rG   rH   rI   r$   rf   rm   r   rK   r<   r<   r:   r=   rL   n   s        rL   c                       s&   e Zd Z fddZdddZ  ZS )LayoutLMv2Attentionc                    s"   t    t|| _t|| _d S N)r#   r$   rL   r8   LayoutLMv2SelfOutputoutputr7   r:   r<   r=   r$      s    

zLayoutLMv2Attention.__init__NFc           
      C   s<   | j ||||||d}| |d |}|f|dd   }	|	S )Nr}   r~   r   r   )r8   r   )
r8   ri   rz   r{   r|   r}   r~   Zself_outputsattention_outputr   r<   r<   r=   r      s    	zLayoutLMv2Attention.forward)NNFNNrG   rH   rI   r$   r   rK   r<   r<   r:   r=   r      s        r   c                       s$   e Zd Z fddZdd Z  ZS )r   c                    sB   t    t|j|j| _tj|j|jd| _t|j	| _
d S Nr   )r#   r$   r   rY   r&   denser.   r/   r0   r1   r2   r7   r:   r<   r=   r$      s    
zLayoutLMv2SelfOutput.__init__c                 C   s&   |  |}| |}| || }|S r   r   r2   r.   r8   ri   input_tensorr<   r<   r=   r      s    

zLayoutLMv2SelfOutput.forwardr   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 )LayoutLMv2Intermediatec                    sB   t    t|j|j| _t|jt	r6t
|j | _n|j| _d S r   )r#   r$   r   rY   r&   intermediate_sizer   
isinstanceZ
hidden_actstrr
   intermediate_act_fnr7   r:   r<   r=   r$      s
    
zLayoutLMv2Intermediate.__init__)ri   returnc                 C   s   |  |}| |}|S r   )r   r   )r8   ri   r<   r<   r=   r      s    

zLayoutLMv2Intermediate.forwardrG   rH   rI   r$   r4   Tensorr   rK   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 )LayoutLMv2Outputc                    sB   t    t|j|j| _tj|j|jd| _t	|j
| _d S r   )r#   r$   r   rY   r   r&   r   r.   r/   r0   r1   r2   r7   r:   r<   r=   r$     s    
zLayoutLMv2Output.__init__)ri   r   r   c                 C   s&   |  |}| |}| || }|S r   r   r   r<   r<   r=   r     s    

zLayoutLMv2Output.forwardr   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 )
LayoutLMv2Layerc                    s:   t    |j| _d| _t|| _t|| _t|| _	d S )Nr   )
r#   r$   chunk_size_feed_forwardseq_len_dimr   	attentionr   intermediater   r   r7   r:   r<   r=   r$     s    


zLayoutLMv2Layer.__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   )r8   ri   rz   r{   r|   r}   r~   Zself_attention_outputsr   r   layer_outputr<   r<   r=   r     s$    	   
zLayoutLMv2Layer.forwardc                 C   s   |  |}| ||}|S r   )r   r   )r8   r   Zintermediate_outputr   r<   r<   r=   r   9  s    
z"LayoutLMv2Layer.feed_forward_chunk)NNFNN)rG   rH   rI   r$   r   r   rK   r<   r<   r:   r=   r     s        
r   T       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 )a  
    Adapted from Mesh Tensorflow:
    https://github.com/tensorflow/mesh/blob/0cb87fe07da627bf0b7e60475d59f95ed6b5be3d/mesh_tensorflow/transformer/transformer_layers.py#L593
    Translate relative position to a bucket number for relative attention. The relative position is defined as
    memory_position - query_position, i.e. the distance in tokens from the attending position to the attended-to
    position. If bidirectional=False, then positive relative positions are invalid. We use smaller buckets for small
    absolute relative_position and larger buckets for larger absolute relative_positions. All relative positions
    >=max_distance map to the same bucket. All relative positions <=-max_distance map to the same bucket. This should
    allow for more graceful generalization to longer sequences than the model has been trained on.

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

    Returns:
        a Tensor with the same shape as relative_position, containing int32 values in the range [0, num_buckets)
    r   r>   r   )longr4   absmax
zeros_likelogrt   rp   ru   rx   Z	full_likewhere)	Zrelative_positionbidirectionalnum_bucketsmax_distanceretnZ	max_exactZis_smallZval_if_larger<   r<   r=   relative_position_bucket?  s     &r   c                       s6   e Zd Z fddZdd Zdd Zdd
dZ  ZS )LayoutLMv2Encoderc                    s   t     | _t fddt jD | _ j| _ j	| _	| jrl 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| _d S )Nc                    s   g | ]}t  qS r<   )r   ).0_r9   r<   r=   
<listcomp>o  s     z.LayoutLMv2Encoder.__init__.<locals>.<listcomp>FrN   )r#   r$   r9   r   Z
ModuleListrangenum_hidden_layerslayerrW   rX   rel_pos_binsmax_rel_posrY   rP   rel_pos_biasmax_rel_2d_posrel_2d_pos_binsrel_pos_x_biasrel_pos_y_biasgradient_checkpointingr7   r:   r   r=   r$   l  s    
 zLayoutLMv2Encoder.__init__c                 C   sN   | d| d }t|| j| jd}| jj | dddd}| }|S )Nrn   r    r   r   r   r	   r   r>   )		unsqueezer   r   r   r   weighttrd   ry   )r8   r   Zrel_pos_matr}   r<   r<   r=   !_calculate_1d_position_embeddings  s    z3LayoutLMv2Encoder._calculate_1d_position_embeddingsc           	      C   s   |d d d d df }|d d d d df }| d| d }| d| d }t|| j| jd}t|| j| jd}| jj | dddd}| jj | dddd}|	 }|	 }|| }|S )Nr   r	   rn   r    r   r   r>   )
r   r   r   r   r   r   r   rd   r   ry   )	r8   rC   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=   !_calculate_2d_position_embeddings  s(    z3LayoutLMv2Encoder._calculate_2d_position_embeddingsNFTc	              	      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r fdd}tj	j
j
|||||||d}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    | f S r   r<   )inputs)moduler|   r<   r=   custom_forward  s    zPLayoutLMv2Encoder.forward.<locals>.create_custom_forward.<locals>.custom_forwardr<   )r   r   r|   )r   r=   create_custom_forward  s    z8LayoutLMv2Encoder.forward.<locals>.create_custom_forwardr   r   r   c                 s   s   | ]}|d k	r|V  qd S r   r<   )r   rl   r<   r<   r=   	<genexpr>  s   z,LayoutLMv2Encoder.forward.<locals>.<genexpr>)last_hidden_stateri   
attentions)rW   r   rX   r   	enumerater   r   Ztrainingr4   utils
checkpointtupler   )r8   ri   rz   r{   r|   output_hidden_statesreturn_dictrC   r   Zall_hidden_statesZall_self_attentionsr}   r~   iZlayer_moduleZlayer_head_maskr   Zlayer_outputsr<   r   r=   r     sV    
		
	zLayoutLMv2Encoder.forward)NNFFTNN)rG   rH   rI   r$   r   r   r   rK   r<   r<   r:   r=   r   k  s          r   c                   @   s.   e Zd ZdZeZeZdZdd Z	d	ddZ
dS )
LayoutLMv2PreTrainedModelz
    An abstract class to handle weights initialization and a simple interface for downloading and loading pretrained
    models.
    
layoutlmv2c                 C   s   t |tjr:|jjjd| jjd |jdk	r|jj	  nft |tj
rz|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 weightsg        )meanZstdN      ?)r   r   rY   r   dataZnormal_r9   Zinitializer_rangerO   Zzero_r%   r   r.   Zfill_)r8   r   r<   r<   r=   _init_weights  s    

z'LayoutLMv2PreTrainedModel._init_weightsFc                 C   s   t |tr||_d S r   )r   r   r   )r8   r   ra   r<   r<   r=   _set_gradient_checkpointing  s    
z5LayoutLMv2PreTrainedModel._set_gradient_checkpointingN)F)rG   rH   rI   rJ   r   config_class(LAYOUTLMV2_PRETRAINED_MODEL_ARCHIVE_LISTZpretrained_model_archive_mapZbase_model_prefixr   r   r<   r<   r<   r=   r     s   r   c                 C   s   t | tjjjjr"tjj| |S | }t | tj	j
rtjj| j| jdd|d}tj| j|_tj| j|_| j|_| j|_tjdtj| jjd|_|  D ]\}}||t|| q~ |S )NT)num_featuresr   ZaffineZtrack_running_statsprocess_groupr   ro   device)r   r4   r   modulesZ	batchnormZ
_BatchNormZSyncBatchNormZconvert_sync_batchnorm
detectron2ZlayersZFrozenBatchNorm2dr   r   r[   r   rO   Zrunning_meanZrunning_vartensorr   r   Znum_batches_trackedZnamed_childrenZ
add_modulemy_convert_sync_batchnorm)r   r   Zmodule_outputnamechildr<   r<   r=   r   
  s(    r   c                       s,   e Zd Z fddZdd Zdd Z  ZS )LayoutLMv2VisualBackbonec              	      s  t    | | _| jjj}t|| j}t|j	t
jj	jsDt|j	| _	t| jjjt| jjjksltt| jjj}| jdt| jjj|dddd | jdt| jjj|dddd d| _t rDtd d}| j	 | j j}ttt|d	 | |jd	  tt|d | |jd  f| _ nt!|jd d
 | _ t|jd
kr|j"| j	 | j j# | j	 | j j#|jd
 kstd S )N
pixel_meanr   Fr!   	pixel_stdp2z0using `AvgPool2d` instead of `AdaptiveAvgPool2d`)   r   r   r>   )$r#   r$   Zget_detectron2_configcfgZMODELZMETA_ARCHITECTUREr   getr   backboner   ZmodelingZFPNAssertionErrorlenZ
PIXEL_MEANZ	PIXEL_STDr3   r4   r   rc   out_feature_keyZ$are_deterministic_algorithms_enabledloggerwarningZoutput_shapeZstrider   Z	AvgPool2drp   ceilimage_feature_pool_shapepoolZAdaptiveAvgPool2dappendZchannels)r8   r9   Z	meta_archmodelZnum_channelsinput_shapeZbackbone_strider:   r<   r=   r$   #  s@    


   

  z!LayoutLMv2VisualBackbone.__init__c                 C   sV   t |r|n|j| j | j }| |}|| j }| |jdd	dd
 }|S )Nr>   )Z	start_dimr   )r4   Z	is_tensorr   r   r   r   r   r   flattenrs   ry   )r8   ZimagesZimages_inputfeaturesr<   r<   r=   r   F  s
     

z LayoutLMv2VisualBackbone.forwardc                    s   t j r"t j r"t j dks*tdt j }t j t j }| dks\tdfddt	| D   fddt	| D }| }t
| j|| d| _d S )	Nr    z/Make sure torch.distributed is set up properly.r   zGMake sure the number of processes can be divided by the number of nodesc                    s&   g | ]}t t|  |d    qS rg   )listr   r   r   )	node_sizer<   r=   r   [  s     zCLayoutLMv2VisualBackbone.synchronize_batch_norm.<locals>.<listcomp>c                    s   g | ]}t jj | d qS ))Zranks)r4   distributedZ	new_groupr   )node_global_ranksr<   r=   r   \  s    )r   )r4   r   Zis_availableZis_initializedZget_rankRuntimeErrorcudaZdevice_countZget_world_sizer   r   r   )r8   Z	self_rankZ
world_sizeZsync_bn_groupsZ	node_rankr<   )r   r   r=   synchronize_batch_normM  s$    




z/LayoutLMv2VisualBackbone.synchronize_batch_norm)rG   rH   rI   r$   r   r   rK   r<   r<   r:   r=   r   "  s   #r   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 ([`LayoutLMv2Config`]): 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.

            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.

        image (`torch.FloatTensor` of shape `(batch_size, num_channels, height, width)` or `detectron.structures.ImageList` whose `tensors` is of shape `(batch_size, num_channels, height, width)`):
            Batch of document images.

        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 `(batch_size, 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.
        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 fddZdd Z  ZS )LayoutLMv2Poolerc                    s*   t    t|j|j| _t | _d S r   )r#   r$   r   rY   r&   r   ZTanh
activationr7   r:   r<   r=   r$     s    
zLayoutLMv2Pooler.__init__c                 C   s(   |d d df }|  |}| |}|S )Nr   )r   r  )r8   ri   Zfirst_token_tensorpooled_outputr<   r<   r=   r     s    

zLayoutLMv2Pooler.forwardr   r<   r<   r:   r=   r     s   r   zdThe bare LayoutLMv2 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d	Zd
d Zdd Zd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 )LayoutLMv2Modelc                    s   t | d t | || _|j| _t|| _t|| _t	
|jd |j| _| jrpt	t	d|jjd | _t	j|j|jd| _t	|j| _t|| _t|| _|   d S )Nr   r    r   r   r   )r   r#   r$   r9   has_visual_segment_embeddingr   
embeddingsr   visualr   rY   r   r&   visual_projr[   r%   r   visual_segment_embeddingr.   r/   visual_LayerNormr0   r1   visual_dropoutr   encoderr   pooler	post_initr7   r:   r<   r=   r$     s    




zLayoutLMv2Model.__init__c                 C   s   | j jS r   r  r'   r8   r<   r<   r=   get_input_embeddings  s    z$LayoutLMv2Model.get_input_embeddingsc                 C   s   || j _d S r   r  )r8   ra   r<   r<   r=   set_input_embeddings  s    z$LayoutLMv2Model.set_input_embeddingsNc                 C   s   |d k	r|  }n|  d d }|d }|d krVtj|tj|jd}|d|}|d krht|}|d kr|| j	|}| j
|}| j|}	| j|}
|| |	 |
 }| j|}| j|}|S )Nr    r   r   r   )rb   r4   r5   r   r   r   Z	expand_asr   r  r'   r(   rF   r-   r.   r2   )r8   	input_idsrC   r   token_type_idsinputs_embedsr   
seq_lengthr(   rE   r-   r  r<   r<   r=   _calc_text_embeddings  s$    

z%LayoutLMv2Model._calc_text_embeddingsc                 C   s\   |  | |}| j|}| j|}|| | }| jrD|| j7 }| |}| |}|S r   )	r  r  r  r(   rF   r  r  r	  r
  )r8   imagerC   r   Zvisual_embeddingsr(   rE   r  r<   r<   r=   _calc_img_embeddings  s    


z$LayoutLMv2Model._calc_img_embeddingsc                 C   s
  t jt jdd|d d  d||jd| jjd dd}t jt jdd| jjd d  d||jd| jj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}||d dd}|S )	Nr   i  r   )r   ro   floor)Zrounding_moder    r?   )r4   divr5   ro   r9   r   stackrepeatrs   rc   rb   )r8   r   rC   r   final_shapeZvisual_bbox_xZvisual_bbox_yvisual_bboxr<   r<   r=   _calc_visual_bbox  sF    

 
z!LayoutLMv2Model._calc_visual_bboxc                 C   sN   |d k	r|d k	rt dn0|d k	r*| S |d k	rB| d d S t dd S )NDYou cannot specify both input_ids and inputs_embeds at the same timer    5You have to specify either input_ids or inputs_embeds)rR   rb   )r8   r  r  r<   r<   r=   _get_input_shape"  s    
z LayoutLMv2Model._get_input_shapez(batch_size, sequence_length)output_typer   )r  rC   r  rz   r  r   r{   r  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	rV|jn|j}t|}| j jd | j jd  |d< t	|}t| ||}|d  |d 7  < t	|}| 
| j j|||}tj||gdd}|dkrtj||d}tj||d}tj||gdd}|dkr0tj|tj|d}|dkrd|d }| jjddd|f }||}tjd|d tj|d|d d}tj||gdd}|dkrtjtt|dg tj|d}| j|||||d}| j|||d	}tj||gdd}|dd
}|j| jd}d| t| jj }|dk	r| dkrz|dddd}|| j jdddd}n$| d
kr|ddd}|jt|  jd}ndg| j j }| j ||||||	|
|d}|d }| !|}|s
||f|dd  S t"|||j#|j$dS )au  
        Return:

        Examples:

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

        >>> set_seed(88)

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


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

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

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

        >>> last_hidden_states.shape
        torch.Size([1, 342, 768])
        ```
        Nr   r   r?   )r   r      )r  rC   r  r   r  r  rC   r   r>   )ro   r   r    )rC   r   r{   r|   r   r   )r   Zpooler_outputri   r   )%r9   r|   r   use_return_dictr"  r   r   r   r4   Sizer  rB   Zonesr\   r   r  r   r6   r5   r  r   r  r  r   ru   ro   rw   rx   r@   r   next
parametersr  r  r   ri   r   )r8   r  rC   r  rz   r  r   r{   r  r|   r   r   r   r   visual_shaper  r  Z
final_bboxZvisual_attention_maskZfinal_attention_maskr  visual_position_idsZfinal_position_idsZtext_layout_embZ
visual_embZ	final_embZextended_attention_maskZencoder_outputssequence_outputr  r<   r<   r=   r   ,  s    .




 
 


zLayoutLMv2Model.forward)N)NN)NNNNNNNNNNN)rG   rH   rI   r$   r  r  r  r  r  r"  r   LAYOUTLMV2_INPUTS_DOCSTRINGformatr   r   _CONFIG_FOR_DOCr   r4   
LongTensorFloatTensorrv   r   r   r   r   rK   r<   r<   r:   r=   r    sD   
%


           
r  ax  
    LayoutLMv2 Model with a sequence classification head on top (a linear layer on top of the concatenation of the
    final hidden state of the [CLS] token, average-pooled initial visual embeddings and average-pooled final visual
    embeddings, e.g. for document image classification tasks such as the
    [RVL-CDIP](https://www.cs.cmu.edu/~aharley/rvl-cdip/) dataset.
    c                       s   e Zd Z f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j ee ee ee eee	f dd	d
Z  ZS )#LayoutLMv2ForSequenceClassificationc                    sN   t  | |j| _t|| _t|j| _t	|j
d |j| _|   d S )Nr	   r#   r$   
num_labelsr  r   r   r0   r1   r2   rY   r&   
classifierr  r7   r:   r<   r=   r$     s    
z,LayoutLMv2ForSequenceClassification.__init__c                 C   s
   | j jjS r   r   r  r'   r  r<   r<   r=   r    s    z8LayoutLMv2ForSequenceClassification.get_input_embeddingsbatch_size, sequence_lengthr#  Nr  rC   r  rz   r  r   r{   r  labelsr|   r   r   r   c                 C   s4  |dk	r|n| j j}|dk	r.|dk	r.tdn@|dk	rL| || | }n"|dk	rf| dd }ntd|dk	r||jn|j}t|}| j jd | j jd  |d< t	|}t|}|d  |d 7  < t	|}| j
| j j|||}tjd|d tj|d|d d}| j
j|||d}| j
|||||||||
||d	}|dk	rV| }n| dd }|d }|d ddd|f |d dd|df  }}|dddddf }|jdd
}|jdd
}tj|||gdd
}| |}| |}d}|	dk	r| j jdkrb| jdkr(d| j _n:| jdkrZ|	jtjksP|	jtjkrZd| j _nd| j _| j jdkrt }| jdkr|| |	 }n
|||	}nN| j jdkrt }||d| j|	d}n| j jdkrt }|||	}|s |f|dd  }|dk	r|f| S |S t|||j|jdS )a5  
        labels (`torch.LongTensor` of shape `(batch_size,)`, *optional*):
            Labels for computing the sequence classification/regression loss. Indices should be in `[0, ...,
            config.num_labels - 1]`. If `config.num_labels == 1` a regression loss is computed (Mean-Square loss), If
            `config.num_labels > 1` a classification loss is computed (Cross-Entropy).

        Returns:

        Example:

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

        >>> set_seed(88)

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

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

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

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

        >>> loss, logits = outputs.loss, outputs.logits
        >>> predicted_idx = logits.argmax(dim=-1).item()
        >>> predicted_answer = dataset.info.features["label"].names[4]
        >>> predicted_idx, predicted_answer
        (4, 'advertisement')
        ```
        Nr   r    r!  r   r   r   r&  r  rC   r  rz   r  r   r{   r  r|   r   r   r?   Z
regressionZsingle_label_classificationZmulti_label_classificationr>   losslogitsri   r   ) r9   r'  rR   Z%warn_if_padding_and_no_attention_maskrb   r   r   r   r4   r(  r   r  r5   r   r  r  r   rB   r2   r6  Zproblem_typer5  ro   rT   r   squeezer   rc   r   r   ri   r   )r8   r  rC   r  rz   r  r   r{   r  r:  r|   r   r   r   r   r+  r  r  r,  Zinitial_image_embeddingsr   r  r-  Zfinal_image_embeddingsZcls_final_outputZpooled_initial_image_embeddingsZpooled_final_image_embeddingsr>  r=  loss_fctr   r<   r<   r=   r     s    9



    

2 



(

z+LayoutLMv2ForSequenceClassification.forward)NNNNNNNNNNNN)rG   rH   rI   r$   r  r   r.  r/  r   r   r0  r   r4   r1  r2  rv   r   r   r   rK   r<   r<   r:   r=   r3    s>   


            
r3  a  
    LayoutLMv2 Model with a token classification head on top (a linear layer on top of the text part of the hidden
    states) e.g. for sequence labeling (information extraction) tasks such as
    [FUNSD](https://guillaumejaume.github.io/FUNSD/), [SROIE](https://rrc.cvc.uab.es/?ch=13),
    [CORD](https://github.com/clovaai/cord) and [Kleister-NDA](https://github.com/applicaai/kleister-nda).
    c                       s   e Zd Z f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j ee ee ee eee	f dd	d
Z  ZS ) LayoutLMv2ForTokenClassificationc                    sJ   t  | |j| _t|| _t|j| _t	|j
|j| _|   d S r   r4  r7   r:   r<   r=   r$   z  s    
z)LayoutLMv2ForTokenClassification.__init__c                 C   s
   | j jjS r   r7  r  r<   r<   r=   r    s    z5LayoutLMv2ForTokenClassification.get_input_embeddingsr8  r#  Nr9  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 )a2  
        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:

        Example:

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

        >>> set_seed(88)

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

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

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

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

        >>> predicted_token_class_ids = logits.argmax(-1)
        >>> predicted_tokens_classes = [id2label[t.item()] for t in predicted_token_class_ids[0]]
        >>> predicted_tokens_classes[:5]
        ['B-ANSWER', 'B-HEADER', 'B-HEADER', 'B-HEADER', 'B-HEADER']
        ```
        Nr;  r    r   r   r>   r<  )r9   r'  r   rb   r2   r6  r   rc   r5  r   ri   r   )r8   r  rC   r  rz   r  r   r{   r  r:  r|   r   r   r   r   r  r-  r>  r=  r@  r   r<   r<   r=   r     sD    B


z(LayoutLMv2ForTokenClassification.forward)NNNNNNNNNNNN)rG   rH   rI   r$   r  r   r.  r/  r   r   r0  r   r4   r1  r2  rv   r   r   r   rK   r<   r<   r:   r=   rA  p  s>   


            
rA  a  
    LayoutLMv2 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d f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j eej ee ee ee eee	f d	d
dZ  ZS )LayoutLMv2ForQuestionAnsweringTc                    sB   t  | |j| _||_t|| _t|j|j| _	| 
  d S r   )r#   r$   r5  r  r  r   r   rY   r&   
qa_outputsr  )r8   r9   r  r:   r<   r=   r$     s    
z'LayoutLMv2ForQuestionAnswering.__init__c                 C   s
   | j jjS r   r7  r  r<   r<   r=   r    s    z3LayoutLMv2ForQuestionAnswering.get_input_embeddingsr8  r#  N)r  rC   r  rz   r  r   r{   r  start_positionsend_positionsr|   r   r   r   c                 C   s  |dk	r|n| j j}| j|||||||||||d}|dk	rF| }n| dd }|d }|d ddd|f }| |}|jddd\}}|d }|d }d}|	dk	rF|
dk	rFt|	 dkr|	d}	t|
 dkr|
d}
|d}|		d|}	|
	d|}
t
|d}|||	}|||
}|| d }|sx||f|dd  }|dk	rt|f| S |S t||||j|jd	S )
am  
        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:

        Example:

        In this example below, we give the LayoutLMv2 model an image (of texts) and ask it a question. It will give us
        a prediction of what it thinks the answer is (the span of the answer within the texts parsed from the image).

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

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

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

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

        >>> predicted_answer_tokens = encoding.input_ids.squeeze()[predicted_start_idx : predicted_end_idx + 1]
        >>> predicted_answer = processor.tokenizer.decode(predicted_answer_tokens)
        >>> predicted_answer  # results are not very good without further fine-tuning
        'council mem - bers conducted by trrf treasurer philip g. kuehn to get answers which the public ...
        ```

        ```python
        >>> target_start_index = torch.tensor([7])
        >>> target_end_index = torch.tensor([14])
        >>> outputs = model(**encoding, start_positions=target_start_index, end_positions=target_end_index)
        >>> predicted_answer_span_start = outputs.start_logits.argmax(-1).item()
        >>> predicted_answer_span_end = outputs.end_logits.argmax(-1).item()
        >>> predicted_answer_span_start, predicted_answer_span_end
        (154, 287)
        ```
        Nr;  r    r   r   r?   )Zignore_indexr>   )r=  start_logits
end_logitsri   r   )r9   r'  r   rb   rC  splitr?  ry   r   clampr   r   ri   r   )r8   r  rC   r  rz   r  r   r{   r  rD  rE  r|   r   r   r   r   r  r-  r>  rF  rG  Z
total_lossZignored_indexr@  Z
start_lossZend_lossr   r<   r<   r=   r   
  s\    J







z&LayoutLMv2ForQuestionAnswering.forward)T)NNNNNNNNNNNNN)rG   rH   rI   r$   r  r   r.  r/  r   r   r0  r   r4   r1  r2  rv   r   r   r   rK   r<   r<   r:   r=   rB    sB   	

             
rB  )Tr   r   )N)?rJ   rp   typingr   r   r   r4   Ztorch.utils.checkpointr   Ztorch.nnr   r   r   Zactivationsr
   Zmodeling_outputsr   r   r   r   r   Zmodeling_utilsr   Zpytorch_utilsr   r   r   r   r   r   r   r   Zconfiguration_layoutlmv2r   r   Zdetectron2.modelingr   Z
get_loggerrG   r   Z_CHECKPOINT_FOR_DOCr0  r   Moduler   rL   r   r   r   r   r   r   r   r   r   r   ZLAYOUTLMV2_START_DOCSTRINGr.  r   r  r3  rA  rB  r<   r<   r<   r=   <module>   sv    
/]+
, 
B< }	 .	{