a
    h                  
   @   sl  d 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 dd	lmZmZmZmZmZmZ dd
lmZmZ ddlmZmZmZ ddlmZm Z m!Z! ddl"m#Z# e!$e%Z&ej'Z(G dd dej)Z*d;ej)ej+ej+ej+eej+ e,e,eej+ ddd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)Z2G dd  d eZ3G d!d" d"ej)Z4G d#d$ d$ej)Z5G d%d& d&ej)Z6G d'd( d(ej)Z7G d)d* d*ej)Z8eG d+d, d,eZ9eG d-d. d.e9Z:eG d/d0 d0e9Z;ed1d2G d3d4 d4e9Z<ed5d2G d6d7 d7e9Z=eG d8d9 d9e9Z>g d:Z?dS )<zPyTorch LayoutLM model.    )CallableOptionalUnionN)nn)BCEWithLogitsLossCrossEntropyLossMSELoss   )ACT2FN)GradientCheckpointingLayer)BaseModelOutputBaseModelOutputWithPoolingMaskedLMOutputQuestionAnsweringModelOutputSequenceClassifierOutputTokenClassifierOutput)ALL_ATTENTION_FUNCTIONSPreTrainedModel)apply_chunking_to_forward find_pruneable_heads_and_indicesprune_linear_layer)auto_docstringcan_return_tuplelogging   )LayoutLMConfigc                       s*   e Zd ZdZ fddZdddZ  ZS )LayoutLMEmbeddingszGConstruct the embeddings from word, position and token_type embeddings.c                    s   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d| _t|j| _| jdt|jddd d S )N)padding_idxepsposition_ids)r   F)
persistent)super__init__r   	Embedding
vocab_sizehidden_sizeZpad_token_idword_embeddingsZmax_position_embeddingsposition_embeddingsZmax_2d_position_embeddingsx_position_embeddingsy_position_embeddingsh_position_embeddingsw_position_embeddingsZtype_vocab_sizetoken_type_embeddingsLayoutLMLayerNormlayer_norm_eps	LayerNormDropouthidden_dropout_probdropoutZregister_buffertorchZarangeexpandselfconfig	__class__ j/var/www/html/assistant/venv/lib/python3.9/site-packages/transformers/models/layoutlm/modeling_layoutlm.pyr$   1   s    
zLayoutLMEmbeddings.__init__Nc              
   C   s  |d ur|  }n|  d d }|d }|d ur8|jn|j}|d u r\| jd d d |f }|d u rvtj|tj|d}|d u r| |}|}	| |}
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 n0 t
y: } zt
d|W Y d }~n
d }~0 0 | |d d d d df |d d d d df  }| |d d d d df |d d d d df  }| |}|	|
 | | | | | | | }| |}| |}|S )Nr!   r   dtypedevicer      r	   z:The `bbox`coordinate values should be within 0-1000 range.)sizer@   r    r5   zeroslongr(   r)   r*   r+   
IndexErrorr,   r-   r.   r1   r4   )r8   	input_idsbboxtoken_type_idsr    inputs_embedsinput_shapeZ
seq_lengthr@   Zwords_embeddingsr)   Zleft_position_embeddingsZupper_position_embeddingsZright_position_embeddingsZlower_position_embeddingser,   r-   r.   
embeddingsr<   r<   r=   forwardB   sX    


  22


zLayoutLMEmbeddings.forward)NNNNN)__name__
__module____qualname____doc__r$   rM   __classcell__r<   r<   r:   r=   r   .   s        r           )modulequerykeyvalueattention_maskscalingr4   	head_maskc                 K   s   t ||dd| }	|d urN|d d d d d d d |jd f }
|	|
 }	tjj|	dt jd|j	}	tjj
|	|| jd}	|d ur|	|dddd }	t |	|}|dd }||	fS )NrA   r	   r!   )dimr?   )ptrainingr   )r5   matmul	transposeshaper   Z
functionalZsoftmaxZfloat32tor?   r4   r^   view
contiguous)rT   rU   rV   rW   rX   rY   r4   rZ   kwargsattn_weightsZcausal_maskattn_outputr<   r<   r=   eager_attention_forward{   s    &rh   c                       sL   e Zd Z fddZdejeej eej ee e	ej dddZ
  ZS )	LayoutLMSelfAttentionc                    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 | _d S )Nr   Zembedding_sizezThe hidden size (z6) is not a multiple of the number of attention heads ()g      )r#   r$   r'   num_attention_headshasattr
ValueErrorr9   intattention_head_sizeall_head_sizer   LinearrU   rV   rW   r2   Zattention_probs_dropout_probr4   attention_dropoutrY   r7   r:   r<   r=   r$      s"    

zLayoutLMSelfAttention.__init__NFhidden_statesrX   rZ   output_attentionsreturnc                 K   s   |j d d }g |d| jR }| ||dd}| ||dd}	| ||dd}
t}| jj	dkrt
| jj	 }|| ||	|
|f| jsdn| j| j|d|\}}|jg |dR   }|r||fn|f}|S )Nr!   r   rA   eagerrS   )r4   rY   rZ   )ra   ro   rU   rc   r`   rV   rW   rh   r9   Z_attn_implementationr   r^   rr   rY   Zreshaperd   )r8   rt   rX   rZ   ru   re   rJ   Zhidden_shapeZquery_statesZ
key_statesZvalue_statesZattention_interfacerg   rf   outputsr<   r<   r=   rM      s0    	
zLayoutLMSelfAttention.forward)NNF)rN   rO   rP   r$   r5   Tensorr   FloatTensorbooltuplerM   rR   r<   r<   r:   r=   ri      s      ri   c                       s4   e Zd Z fddZejejejdddZ  ZS )LayoutLMSelfOutputc                    sB   t    t|j|j| _tj|j|jd| _t|j	| _
d S Nr   )r#   r$   r   rq   r'   denser1   r0   r2   r3   r4   r7   r:   r<   r=   r$      s    
zLayoutLMSelfOutput.__init__rt   input_tensorrv   c                 C   s&   |  |}| |}| || }|S Nr   r4   r1   r8   rt   r   r<   r<   r=   rM      s    

zLayoutLMSelfOutput.forwardrN   rO   rP   r$   r5   ry   rM   rR   r<   r<   r:   r=   r}      s   r}   c                       sT   e Zd Z fddZdd Zd
ejeej eej ee	 e
ej ddd	Z  ZS )LayoutLMAttentionc                    s*   t    t|| _t|| _t | _d S r   )r#   r$   ri   r8   r}   outputsetpruned_headsr7   r:   r<   r=   r$      s    


zLayoutLMAttention.__init__c                 C   s   t |dkrd S t|| jj| jj| j\}}t| jj|| j_t| jj|| j_t| jj	|| j_	t| j
j|dd| j
_| jjt | | j_| jj| jj | j_| j|| _d S )Nr   r   r\   )lenr   r8   rk   ro   r   r   rU   rV   rW   r   r   rp   union)r8   headsindexr<   r<   r=   prune_heads   s    zLayoutLMAttention.prune_headsNFrs   c           	      K   s@   | j |f|||d|}| |d |}|f|dd   }|S N)rX   rZ   ru   r   r   )r8   r   )	r8   rt   rX   rZ   ru   re   Zself_outputsattention_outputrx   r<   r<   r=   rM      s    zLayoutLMAttention.forward)NNF)rN   rO   rP   r$   r   r5   ry   r   rz   r{   r|   rM   rR   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 )LayoutLMIntermediatec                    sB   t    t|j|j| _t|jt	r6t
|j | _n|j| _d S r   )r#   r$   r   rq   r'   intermediate_sizer   
isinstance
hidden_actstrr
   intermediate_act_fnr7   r:   r<   r=   r$     s
    
zLayoutLMIntermediate.__init__rt   rv   c                 C   s   |  |}| |}|S r   )r   r   r8   rt   r<   r<   r=   rM     s    

zLayoutLMIntermediate.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 )LayoutLMOutputc                    sB   t    t|j|j| _tj|j|jd| _t	|j
| _d S r~   )r#   r$   r   rq   r   r'   r   r1   r0   r2   r3   r4   r7   r:   r<   r=   r$      s    
zLayoutLMOutput.__init__r   c                 C   s&   |  |}| |}| || }|S r   r   r   r<   r<   r=   rM   &  s    

zLayoutLMOutput.forwardr   r<   r<   r:   r=   r     s   r   c                       sT   e Zd Z fddZd
ejeej eej ee e	ej dddZ
dd	 Z  ZS )LayoutLMLayerc                    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LayoutLMLayer.__init__NFrs   c           
      K   sP   | j |f|||d|}|d }|dd  }t| j| j| j|}	|	f| }|S r   )r   r   feed_forward_chunkr   r   )
r8   rt   rX   rZ   ru   re   Zself_attention_outputsr   rx   layer_outputr<   r<   r=   rM   7  s     
zLayoutLMLayer.forwardc                 C   s   |  |}| ||}|S r   )r   r   )r8   r   Zintermediate_outputr   r<   r<   r=   r   P  s    
z LayoutLMLayer.feed_forward_chunk)NNF)rN   rO   rP   r$   r5   ry   r   rz   r{   r|   rM   r   rR   r<   r<   r:   r=   r   .  s      r   c                       sd   e Zd Z fddZed	ejeej eej ee	 ee	 ee	 e
eej ef dddZ  ZS )
LayoutLMEncoderc                    s:   t     | _t fddt jD | _d| _d S )Nc                    s   g | ]}t  qS r<   )r   ).0ir9   r<   r=   
<listcomp>[      z,LayoutLMEncoder.__init__.<locals>.<listcomp>F)	r#   r$   r9   r   Z
ModuleListrangenum_hidden_layerslayerZgradient_checkpointingr7   r:   r   r=   r$   X  s    
 zLayoutLMEncoder.__init__NFT)rt   rX   rZ   ru   output_hidden_statesreturn_dictrv   c                 K   s   |rdnd }|rdnd }	t | jD ]\\}
}|r8||f }|d urH||
 nd }|f ||||d|}|d }|r"|	|d f }	q"|r||f }t|||	dS )Nr<   )rt   rX   rZ   ru   r   r   )last_hidden_statert   
attentions)	enumerater   r   )r8   rt   rX   rZ   ru   r   r   re   Zall_hidden_statesZall_self_attentionsr   Zlayer_moduleZlayer_head_maskZlayer_outputsr<   r<   r=   rM   ^  s0    

zLayoutLMEncoder.forward)NNFFT)rN   rO   rP   r$   r   r5   ry   r   rz   r{   r   r|   r   rM   rR   r<   r<   r:   r=   r   W  s         r   c                       s0   e Zd Z fddZejejdddZ  ZS )LayoutLMPoolerc                    s*   t    t|j|j| _t | _d S r   )r#   r$   r   rq   r'   r   ZTanh
activationr7   r:   r<   r=   r$     s    
zLayoutLMPooler.__init__r   c                 C   s(   |d d df }|  |}| |}|S )Nr   )r   r   )r8   rt   Zfirst_token_tensorpooled_outputr<   r<   r=   rM     s    

zLayoutLMPooler.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 )LayoutLMPredictionHeadTransformc                    sV   t    t|j|j| _t|jtr6t	|j | _
n|j| _
tj|j|jd| _d S r~   )r#   r$   r   rq   r'   r   r   r   r   r
   transform_act_fnr1   r0   r7   r:   r<   r=   r$     s    
z(LayoutLMPredictionHeadTransform.__init__r   c                 C   s"   |  |}| |}| |}|S r   )r   r   r1   r   r<   r<   r=   rM     s    


z'LayoutLMPredictionHeadTransform.forwardr   r<   r<   r:   r=   r     s   	r   c                       s,   e Zd Z fddZdd Zdd Z  ZS )LayoutLMLMPredictionHeadc                    sL   t    t|| _tj|j|jdd| _t	t
|j| _| j| j_d S )NF)bias)r#   r$   r   	transformr   rq   r'   r&   decoder	Parameterr5   rC   r   r7   r:   r<   r=   r$     s
    

z!LayoutLMLMPredictionHead.__init__c                 C   s   | j | j_ d S r   )r   r   r8   r<   r<   r=   _tie_weights  s    z%LayoutLMLMPredictionHead._tie_weightsc                 C   s   |  |}| |}|S r   )r   r   r   r<   r<   r=   rM     s    

z LayoutLMLMPredictionHead.forward)rN   rO   rP   r$   r   rM   rR   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 )LayoutLMOnlyMLMHeadc                    s   t    t|| _d S r   )r#   r$   r   predictionsr7   r:   r<   r=   r$     s    
zLayoutLMOnlyMLMHead.__init__)sequence_outputrv   c                 C   s   |  |}|S r   )r   )r8   r   prediction_scoresr<   r<   r=   rM     s    
zLayoutLMOnlyMLMHead.forwardr   r<   r<   r:   r=   r     s   r   c                   @   s&   e Zd ZU eed< dZdZdd ZdS )LayoutLMPreTrainedModelr9   layoutlmTc                 C   s   t |tjr:|jjjd| jjd |jdur|jj	  n|t |tj
rz|jjjd| jjd |jdur|jj|j 	  n<t |tr|jj	  |jjd nt |tr|jj	  dS )zInitialize the weightsrS   )meanZstdN      ?)r   r   rq   weightdataZnormal_r9   Zinitializer_ranger   Zzero_r%   r   r/   Zfill_r   )r8   rT   r<   r<   r=   _init_weights  s    



z%LayoutLMPreTrainedModel._init_weightsN)rN   rO   rP   r   __annotations__Zbase_model_prefixZsupports_gradient_checkpointingr   r<   r<   r<   r=   r     s   
r   c                       s   e Zd Z fddZdd Zdd Zdd Zee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ef d
ddZ  ZS )LayoutLMModelc                    s<   t  | || _t|| _t|| _t|| _| 	  d S r   )
r#   r$   r9   r   rL   r   encoderr   pooler	post_initr7   r:   r<   r=   r$     s    


zLayoutLMModel.__init__c                 C   s   | j jS r   rL   r(   r   r<   r<   r=   get_input_embeddings  s    z"LayoutLMModel.get_input_embeddingsc                 C   s   || j _d S r   r   )r8   rW   r<   r<   r=   set_input_embeddings  s    z"LayoutLMModel.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   r   )r8   Zheads_to_pruner   r   r<   r<   r=   _prune_heads  s    zLayoutLMModel._prune_headsN)rF   rG   rX   rH   r    rZ   rI   ru   r   r   rv   c                 C   s  |dur|n| j j}|	dur |	n| j j}	|
dur4|
n| j j}
|durV|durVtdn@|durt| || | }n"|dur| dd }ntd|dur|jn|j}|du rtj	||d}|du rtj
|tj|d}|du rtj
|d tj|d}|dd	}|j| jd
}d| t| jj }|dur| dkrx|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}| j|||||	dd}|d }| |}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. See [Overview](#Overview) for normalization.

        Examples:

        ```python
        >>> from transformers import AutoTokenizer, LayoutLMModel
        >>> import torch

        >>> tokenizer = AutoTokenizer.from_pretrained("microsoft/layoutlm-base-uncased")
        >>> model = LayoutLMModel.from_pretrained("microsoft/layoutlm-base-uncased")

        >>> words = ["Hello", "world"]
        >>> normalized_word_boxes = [637, 773, 693, 782], [698, 773, 733, 782]

        >>> token_boxes = []
        >>> for word, box in zip(words, normalized_word_boxes):
        ...     word_tokens = tokenizer.tokenize(word)
        ...     token_boxes.extend([box] * len(word_tokens))
        >>> # add bounding boxes of cls + sep tokens
        >>> token_boxes = [[0, 0, 0, 0]] + token_boxes + [[1000, 1000, 1000, 1000]]

        >>> encoding = tokenizer(" ".join(words), return_tensors="pt")
        >>> input_ids = encoding["input_ids"]
        >>> attention_mask = encoding["attention_mask"]
        >>> token_type_ids = encoding["token_type_ids"]
        >>> bbox = torch.tensor([token_boxes])

        >>> outputs = model(
        ...     input_ids=input_ids, bbox=bbox, attention_mask=attention_mask, token_type_ids=token_type_ids
        ... )

        >>> last_hidden_states = outputs.last_hidden_state
        ```NzDYou cannot specify both input_ids and inputs_embeds at the same timer!   z5You have to specify either input_ids or inputs_embeds)r@   r>   )   r   rA   )r?   r   r   )rF   rG   r    rH   rI   T)rZ   ru   r   r   )r   Zpooler_outputrt   r   )r9   ru   r   use_return_dictrm   Z%warn_if_padding_and_no_attention_maskrB   r@   r5   ZonesrC   rD   Z	unsqueezerb   r?   Zfinfominr\   r6   r   next
parametersrL   r   r   r   rt   r   )r8   rF   rG   rX   rH   r    rZ   rI   ru   r   r   rJ   r@   Zextended_attention_maskZembedding_outputZencoder_outputsr   r   r<   r<   r=   rM     sj    5



zLayoutLMModel.forward)
NNNNNNNNNN)rN   rO   rP   r$   r   r   r   r   r   r   r5   
LongTensorrz   r{   r   r|   r   rM   rR   r<   r<   r:   r=   r     s:             
r   c                       s   e Zd ZddgZ fddZdd Zdd Zd	d
 Zee	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 )LayoutLMForMaskedLMzcls.predictions.decoder.biaszcls.predictions.decoder.weightc                    s,   t  | t|| _t|| _|   d S r   )r#   r$   r   r   r   clsr   r7   r:   r<   r=   r$   }  s    

zLayoutLMForMaskedLM.__init__c                 C   s
   | j jjS r   r   rL   r(   r   r<   r<   r=   r     s    z(LayoutLMForMaskedLM.get_input_embeddingsc                 C   s
   | j jjS r   )r   r   r   r   r<   r<   r=   get_output_embeddings  s    z)LayoutLMForMaskedLM.get_output_embeddingsc                 C   s   || j j_|j| j j_d S r   )r   r   r   r   )r8   Znew_embeddingsr<   r<   r=   set_output_embeddings  s    
z)LayoutLMForMaskedLM.set_output_embeddingsNrF   rG   rX   rH   r    rZ   rI   labelsru   r   r   rv   c                 C   s   |dur|n| j j}| j||||||||	|
dd
}|d }| |}d}|durrt }||d| j j|d}t|||j|j	dS )a2	  
        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. See [Overview](#Overview) for normalization.
        labels (`torch.LongTensor` of shape `(batch_size, sequence_length)`, *optional*):
            Labels for computing the masked language modeling loss. Indices should be in `[-100, 0, ...,
            config.vocab_size]` (see `input_ids` docstring) Tokens with indices set to `-100` are ignored (masked), the
            loss is only computed for the tokens with labels in `[0, ..., config.vocab_size]`

        Examples:

        ```python
        >>> from transformers import AutoTokenizer, LayoutLMForMaskedLM
        >>> import torch

        >>> tokenizer = AutoTokenizer.from_pretrained("microsoft/layoutlm-base-uncased")
        >>> model = LayoutLMForMaskedLM.from_pretrained("microsoft/layoutlm-base-uncased")

        >>> words = ["Hello", "[MASK]"]
        >>> normalized_word_boxes = [637, 773, 693, 782], [698, 773, 733, 782]

        >>> token_boxes = []
        >>> for word, box in zip(words, normalized_word_boxes):
        ...     word_tokens = tokenizer.tokenize(word)
        ...     token_boxes.extend([box] * len(word_tokens))
        >>> # add bounding boxes of cls + sep tokens
        >>> token_boxes = [[0, 0, 0, 0]] + token_boxes + [[1000, 1000, 1000, 1000]]

        >>> encoding = tokenizer(" ".join(words), return_tensors="pt")
        >>> input_ids = encoding["input_ids"]
        >>> attention_mask = encoding["attention_mask"]
        >>> token_type_ids = encoding["token_type_ids"]
        >>> bbox = torch.tensor([token_boxes])

        >>> labels = tokenizer("Hello world", return_tensors="pt")["input_ids"]

        >>> outputs = model(
        ...     input_ids=input_ids,
        ...     bbox=bbox,
        ...     attention_mask=attention_mask,
        ...     token_type_ids=token_type_ids,
        ...     labels=labels,
        ... )

        >>> loss = outputs.loss
        ```NT)rX   rH   r    rZ   rI   ru   r   r   r   r!   losslogitsrt   r   )
r9   r   r   r   r   rc   r&   r   rt   r   )r8   rF   rG   rX   rH   r    rZ   rI   r   ru   r   r   rx   r   r   Zmasked_lm_lossloss_fctr<   r<   r=   rM     s8    @
zLayoutLMForMaskedLM.forward)NNNNNNNNNNN)rN   rO   rP   Z_tied_weights_keysr$   r   r   r   r   r   r   r5   r   rz   r{   r   r|   r   rM   rR   r<   r<   r:   r=   r   y  s@   	           
r   z
    LayoutLM Model with a sequence classification head on top (a linear layer on top of the pooled output) e.g. for
    document image classification tasks such as the [RVL-CDIP](https://www.cs.cmu.edu/~aharley/rvl-cdip/) dataset.
    )Zcustom_introc                       s   e Zd Z fddZdd Zee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 )
!LayoutLMForSequenceClassificationc                    sJ   t  | |j| _t|| _t|j| _t	|j
|j| _|   d S r   r#   r$   
num_labelsr   r   r   r2   r3   r4   rq   r'   
classifierr   r7   r:   r<   r=   r$     s    
z*LayoutLMForSequenceClassification.__init__c                 C   s
   | j jjS r   r   r   r<   r<   r=   r     s    z6LayoutLMForSequenceClassification.get_input_embeddingsNr   c                 C   sN  |dur|n| j j}| j||||||||	|
dd
}|d }| |}| |}d}|dur:| j jdu r| jdkr|d| 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r:t }|||}t|||j|jd	S )
aB	  
        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. See [Overview](#Overview) for normalization.
        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).

        Examples:

        ```python
        >>> from transformers import AutoTokenizer, LayoutLMForSequenceClassification
        >>> import torch

        >>> tokenizer = AutoTokenizer.from_pretrained("microsoft/layoutlm-base-uncased")
        >>> model = LayoutLMForSequenceClassification.from_pretrained("microsoft/layoutlm-base-uncased")

        >>> words = ["Hello", "world"]
        >>> normalized_word_boxes = [637, 773, 693, 782], [698, 773, 733, 782]

        >>> token_boxes = []
        >>> for word, box in zip(words, normalized_word_boxes):
        ...     word_tokens = tokenizer.tokenize(word)
        ...     token_boxes.extend([box] * len(word_tokens))
        >>> # add bounding boxes of cls + sep tokens
        >>> token_boxes = [[0, 0, 0, 0]] + token_boxes + [[1000, 1000, 1000, 1000]]

        >>> encoding = tokenizer(" ".join(words), return_tensors="pt")
        >>> input_ids = encoding["input_ids"]
        >>> attention_mask = encoding["attention_mask"]
        >>> token_type_ids = encoding["token_type_ids"]
        >>> bbox = torch.tensor([token_boxes])
        >>> sequence_label = torch.tensor([1])

        >>> outputs = model(
        ...     input_ids=input_ids,
        ...     bbox=bbox,
        ...     attention_mask=attention_mask,
        ...     token_type_ids=token_type_ids,
        ...     labels=sequence_label,
        ... )

        >>> loss = outputs.loss
        >>> logits = outputs.logits
        ```NT
rF   rG   rX   rH   r    rZ   rI   ru   r   r   r   Z
regressionZsingle_label_classificationZmulti_label_classificationr!   r   )r9   r   r   r4   r   Zproblem_typer   r?   r5   rD   rn   r   squeezer   rc   r   r   rt   r   )r8   rF   rG   rX   rH   r    rZ   rI   r   ru   r   r   rx   r   r   r   r   r<   r<   r=   rM     sR    @




"


z)LayoutLMForSequenceClassification.forward)NNNNNNNNNNN)rN   rO   rP   r$   r   r   r   r   r5   r   rz   r{   r   r|   r   rM   rR   r<   r<   r:   r=   r     s:   
           
r   a3  
    LayoutLM Model with a token classification head on top (a linear layer on top of the hidden-states output) e.g. for
    sequence labeling (information extraction) tasks such as the [FUNSD](https://guillaumejaume.github.io/FUNSD/)
    dataset and the [SROIE](https://rrc.cvc.uab.es/?ch=13) dataset.
    c                       s   e Zd Z fddZdd Zee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 )
LayoutLMForTokenClassificationc                    sJ   t  | |j| _t|| _t|j| _t	|j
|j| _|   d S r   r   r7   r:   r<   r=   r$     s    
z'LayoutLMForTokenClassification.__init__c                 C   s
   | j jjS r   r   r   r<   r<   r=   r     s    z3LayoutLMForTokenClassification.get_input_embeddingsNr   c                 C   s   |dur|n| j j}| j||||||||	|
dd
}|d }| |}| |}d}|durzt }||d| j|d}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. See [Overview](#Overview) for normalization.
        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 AutoTokenizer, LayoutLMForTokenClassification
        >>> import torch

        >>> tokenizer = AutoTokenizer.from_pretrained("microsoft/layoutlm-base-uncased")
        >>> model = LayoutLMForTokenClassification.from_pretrained("microsoft/layoutlm-base-uncased")

        >>> words = ["Hello", "world"]
        >>> normalized_word_boxes = [637, 773, 693, 782], [698, 773, 733, 782]

        >>> token_boxes = []
        >>> for word, box in zip(words, normalized_word_boxes):
        ...     word_tokens = tokenizer.tokenize(word)
        ...     token_boxes.extend([box] * len(word_tokens))
        >>> # add bounding boxes of cls + sep tokens
        >>> token_boxes = [[0, 0, 0, 0]] + token_boxes + [[1000, 1000, 1000, 1000]]

        >>> encoding = tokenizer(" ".join(words), return_tensors="pt")
        >>> input_ids = encoding["input_ids"]
        >>> attention_mask = encoding["attention_mask"]
        >>> token_type_ids = encoding["token_type_ids"]
        >>> bbox = torch.tensor([token_boxes])
        >>> token_labels = torch.tensor([1, 1, 0, 0]).unsqueeze(0)  # batch size of 1

        >>> outputs = model(
        ...     input_ids=input_ids,
        ...     bbox=bbox,
        ...     attention_mask=attention_mask,
        ...     token_type_ids=token_type_ids,
        ...     labels=token_labels,
        ... )

        >>> loss = outputs.loss
        >>> logits = outputs.logits
        ```NTr   r   r!   r   )r9   r   r   r4   r   r   rc   r   r   rt   r   )r8   rF   rG   rX   rH   r    rZ   rI   r   ru   r   r   rx   r   r   r   r   r<   r<   r=   rM     s4    >

z&LayoutLMForTokenClassification.forward)NNNNNNNNNNN)rN   rO   rP   r$   r   r   r   r   r5   r   rz   r{   r   r|   r   rM   rR   r<   r<   r:   r=   r   y  s:   
           
r   c                       s   e Zd Zd
 fdd	Zdd Zee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 )LayoutLMForQuestionAnsweringTc                    s<   t  | |j| _t|| _t|j|j| _| 	  dS )z
        has_visual_segment_embedding (`bool`, *optional*, defaults to `True`):
            Whether or not to add visual segment embeddings.
        N)
r#   r$   r   r   r   r   rq   r'   
qa_outputsr   )r8   r9   Zhas_visual_segment_embeddingr:   r<   r=   r$     s
    
z%LayoutLMForQuestionAnswering.__init__c                 C   s
   | j jjS r   r   r   r<   r<   r=   r     s    z1LayoutLMForQuestionAnswering.get_input_embeddingsN)rF   rG   rX   rH   r    rZ   rI   start_positionsend_positionsru   r   r   rv   c                 C   s   |dur|n| j j}| j||||||||
|dd
}|d }| |}|jddd\}}|d }|d }d}|dur
|	dur
t| dkr|d}t|	 dkr|	d}	|d}|	d|}|		d|}	t
|d}|||}|||	}|| d	 }t||||j|jd
S )a4	  
        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. See [Overview](#Overview) for normalization.

        Example:

        In the example below, we prepare a question + context pair for the LayoutLM model. 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 AutoTokenizer, LayoutLMForQuestionAnswering
        >>> from datasets import load_dataset
        >>> import torch

        >>> tokenizer = AutoTokenizer.from_pretrained("impira/layoutlm-document-qa", add_prefix_space=True)
        >>> model = LayoutLMForQuestionAnswering.from_pretrained("impira/layoutlm-document-qa", revision="1e3ebac")

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

        >>> encoding = tokenizer(
        ...     question.split(), words, is_split_into_words=True, return_token_type_ids=True, return_tensors="pt"
        ... )
        >>> bbox = []
        >>> for i, s, w in zip(encoding.input_ids[0], encoding.sequence_ids(0), encoding.word_ids(0)):
        ...     if s == 1:
        ...         bbox.append(boxes[w])
        ...     elif i == tokenizer.sep_token_id:
        ...         bbox.append([1000] * 4)
        ...     else:
        ...         bbox.append([0] * 4)
        >>> encoding["bbox"] = torch.tensor([bbox])

        >>> word_ids = encoding.word_ids(0)
        >>> outputs = model(**encoding)
        >>> loss = outputs.loss
        >>> start_scores = outputs.start_logits
        >>> end_scores = outputs.end_logits
        >>> start, end = word_ids[start_scores.argmax(-1)], word_ids[end_scores.argmax(-1)]
        >>> print(" ".join(words[start : end + 1]))
        M. Hamann P. Harper, P. Martinez
        ```NTr   r   r   r!   r   )Zignore_indexrA   )r   start_logits
end_logitsrt   r   )r9   r   r   r   splitr   rd   r   rB   clampr   r   rt   r   )r8   rF   rG   rX   rH   r    rZ   rI   r   r   ru   r   r   rx   r   r   r   r   Z
total_lossZignored_indexr   Z
start_lossZend_lossr<   r<   r=   rM      sL    B






z$LayoutLMForQuestionAnswering.forward)T)NNNNNNNNNNNN)rN   rO   rP   r$   r   r   r   r   r5   r   rz   r{   r   r|   r   rM   rR   r<   r<   r:   r=   r     s>               
r   )r   r   r   r   r   r   )rS   N)@rQ   typingr   r   r   r5   Ztorch.utils.checkpointr   Ztorch.nnr   r   r   Zactivationsr
   Zmodeling_layersr   Zmodeling_outputsr   r   r   r   r   r   Zmodeling_utilsr   r   Zpytorch_utilsr   r   r   utilsr   r   r   Zconfiguration_layoutlmr   Z
get_loggerrN   loggerr1   r/   Moduler   ry   floatrh   ri   r}   r   r   r   r   r   r   r   r   r   r   r   r   r   r   r   __all__r<   r<   r<   r=   <module>   st    
T  ;.)2
 x m 