o
    eiC                     @   s  d 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 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 ddlmZ e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(G dd deZ)G dd  d ej!Z*G d!d" d"ej!Z+eG d#d$ d$eZ,eG d%d& d&e,Z-ed'd(G d)d* d*e,Z.eG d+d, d,e,Z/G d-d. d.ej!Z0eG d/d0 d0e,Z1g d1Z2dS )2zPyTorch LiLT model.    N)nn)BCEWithLogitsLossCrossEntropyLossMSELoss   )initialization)ACT2FN)GradientCheckpointingLayer)BaseModelOutputBaseModelOutputWithPoolingQuestionAnsweringModelOutputSequenceClassifierOutputTokenClassifierOutput)PreTrainedModel)apply_chunking_to_forward)auto_docstringlogging   )
LiltConfigc                       s>   e Zd Z fddZ				d
ddZdd Zdd	 Z  ZS )LiltTextEmbeddingsc                    s   t    tj|j|j|jd| _t|j|j| _	t|j
|j| _tj|j|jd| _t|j| _| jdt|jddd |j| _tj|j|j| jd| _	d S )Npadding_idxepsposition_idsr   F)
persistent)super__init__r   	Embedding
vocab_sizehidden_sizepad_token_idword_embeddingsmax_position_embeddingsposition_embeddingstype_vocab_sizetoken_type_embeddings	LayerNormlayer_norm_epsDropouthidden_dropout_probdropoutregister_buffertorcharangeexpandr   selfconfig	__class__ d/home/ubuntu/transcripts/venv/lib/python3.10/site-packages/transformers/models/lilt/modeling_lilt.pyr   *   s   
zLiltTextEmbeddings.__init__Nc           	      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 }| |}| |}||fS )Nr   dtypedevice)"create_position_ids_from_input_idsr   tor;   &create_position_ids_from_inputs_embedssizer/   zeroslongr   r$   r(   r&   r)   r-   )	r3   	input_idstoken_type_idsr   inputs_embedsinput_shaper(   
embeddingsr&   r7   r7   r8   forward>   s(   






zLiltTextEmbeddings.forwardc                 C   s2   | | }tj|dd|| }| | S )a  
        Args:
        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`.
            x: torch.Tensor x:
        Returns: torch.Tensor
        r   dim)neintr/   cumsumtype_asrA   )r3   rB   r   maskincremental_indicesr7   r7   r8   r<   b   s   	z5LiltTextEmbeddings.create_position_ids_from_input_idsc                 C   sN   |  dd }|d }tj| jd || j d tj|jd}|d|S )z
        Args:
        We are provided embeddings directly. We cannot infer which are padded so just generate sequential position ids.:
            inputs_embeds: torch.Tensor
        Returns: torch.Tensor
        Nr   r   r9   r   )r?   r/   r0   r   rA   r;   	unsqueezer1   )r3   rD   rE   sequence_lengthr   r7   r7   r8   r>   o   s   z9LiltTextEmbeddings.create_position_ids_from_inputs_embeds)NNNN)__name__
__module____qualname__r   rG   r<   r>   __classcell__r7   r7   r5   r8   r   )   s    
$r   c                       s&   e Zd Z fddZdddZ  ZS )LiltLayoutEmbeddingsc                    s   t    t|j|jd | _t|j|jd | _t|j|jd | _t|j|jd | _	|j
| _tj|j|j|j | jd| _tj|j|j|j d| _tj|j|j |jd| _t|j| _d S )N   r   )in_featuresout_featuresr   )r   r   r   r    max_2d_position_embeddingsr"   x_position_embeddingsy_position_embeddingsh_position_embeddingsw_position_embeddingsr#   r   r%   channel_shrink_ratiobox_position_embeddingsLinearbox_linear_embeddingsr)   r*   r+   r,   r-   r2   r5   r7   r8   r      s    

zLiltLayoutEmbeddings.__init__Nc              
   C   sJ  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 | |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   rH   )r[   r\   
IndexErrorr]   r^   r/   catrb   r`   r)   r-   )r3   bboxr   left_position_embeddingsupper_position_embeddingsright_position_embeddingslower_position_embeddingser]   r^   spatial_position_embeddingsr`   r7   r7   r8   rG      s6    
22



zLiltLayoutEmbeddings.forward)NN)rR   rS   rT   r   rG   rU   r7   r7   r5   r8   rV      s    rV   c                       s6   e Zd Zd
 fdd	ZdddZ		ddd	Z  ZS )LiltSelfAttentionNc                    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|j | _t	
|j|j | j|j | _t	
|j|j | j|j | _t	|j| _|j| _|| _d S )Nr   embedding_sizezThe hidden size (z6) is not a multiple of the number of attention heads ())r   r   r"   num_attention_headshasattr
ValueErrorrK   attention_head_sizeall_head_sizer   ra   querykeyvaluer_   layout_query
layout_keylayout_valuer+   attention_probs_dropout_probr-   	layer_idx)r3   r4   r|   r5   r7   r8   r      s2   


zLiltSelfAttention.__init__r   c                 C   s:   |  d d | j| j| f }|j| }|ddddS )Nr   r   rc   r   r   )r?   rp   rs   viewpermute)r3   xrnew_x_shaper7   r7   r8   transpose_for_scores   s    
z&LiltSelfAttention.transpose_for_scoresFc                 C   s  | j | || jd}| j | || jd}| j | || jd}| |}|  | |}	|  | |}
|  |}t	||	
dd}t	||
dd}|t| j }|t| j| j  }|| }|| }|d urr|| }tjdd|}| |}t	||}|dddd }| d d | j| j f }|j| }|d ur|| }tjdd|}| |}t	||
}|dddd }| d d | jf }|j| }||f}|r||f }|S )	N)r   r   rH   r   rc   r   r   )r   rz   r_   ry   rx   ru   rv   rw   r/   matmul	transposemathsqrtrs   r   Softmaxr-   r~   
contiguousr?   rt   r}   )r3   hidden_stateslayout_inputsattention_maskoutput_attentionslayout_value_layerlayout_key_layerlayout_query_layermixed_query_layer	key_layervalue_layerquery_layerattention_scoreslayout_attention_scorestmp_attention_scorestmp_layout_attention_scoreslayout_attention_probslayout_context_layernew_context_layer_shapeattention_probscontext_layeroutputsr7   r7   r8   rG      sF   







zLiltSelfAttention.forwardN)r   NF)rR   rS   rT   r   r   rG   rU   r7   r7   r5   r8   rm      s    
	rm   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 )LiltSelfOutputc                    sB   t    t|j|j| _tj|j|jd| _t|j	| _
d S Nr   )r   r   r   ra   r"   denser)   r*   r+   r,   r-   r2   r5   r7   r8   r   "     
zLiltSelfOutput.__init__r   input_tensorreturnc                 C   &   |  |}| |}| || }|S r   r   r-   r)   r3   r   r   r7   r7   r8   rG   (     

zLiltSelfOutput.forwardrR   rS   rT   r   r/   TensorrG   rU   r7   r7   r5   r8   r   !      $r   c                       sV   e Zd Zd fdd	Z		ddejdejdejdB dedB d	eej f
d
dZ	  Z
S )LiltAttentionNc                    sJ   t    t||d| _t|| _|j}|j|j |_t|| _||_d S )Nr|   )	r   r   rm   r3   r   outputr"   r_   layout_output)r3   r4   r|   ori_hidden_sizer5   r7   r8   r   0  s   



zLiltAttention.__init__Fr   r   r   r   r   c           	      C   sH   |  ||||}| |d |}| |d |}||f|dd   }|S )Nr   r   rc   )r3   r   r   )	r3   r   r   r   r   self_outputsattention_outputlayout_attention_outputr   r7   r7   r8   rG   :  s   zLiltAttention.forwardr   r   )rR   rS   rT   r   r/   r   FloatTensorbooltuplerG   rU   r7   r7   r5   r8   r   /  s    r   c                       2   e Zd Z fddZdejdejfddZ  ZS )LiltIntermediatec                    sD   t    t|j|j| _t|jt	rt
|j | _d S |j| _d S r   )r   r   r   ra   r"   intermediate_sizer   
isinstance
hidden_actstrr   intermediate_act_fnr2   r5   r7   r8   r   O  s
   
zLiltIntermediate.__init__r   r   c                 C   s   |  |}| |}|S r   )r   r   )r3   r   r7   r7   r8   rG   W  s   

zLiltIntermediate.forwardr   r7   r7   r5   r8   r   N  s    r   c                       r   )
LiltOutputc                    sB   t    t|j|j| _tj|j|jd| _t	|j
| _d S r   )r   r   r   ra   r   r"   r   r)   r*   r+   r,   r-   r2   r5   r7   r8   r   _  r   zLiltOutput.__init__r   r   r   c                 C   r   r   r   r   r7   r7   r8   rG   e  r   zLiltOutput.forwardr   r7   r7   r5   r8   r   ^  r   r   c                       sf   e Zd Zd fdd	Z		ddejdejdejdB dedB d	eej f
d
dZ	dd Z
dd Z  ZS )	LiltLayerNc                    s   t    |j| _d| _t||d| _t|| _t|| _	|j
}|j}|j
|j |_
|j|j |_t|| _t|| _||_
||_d S )Nr   r   )r   r   chunk_size_feed_forwardseq_len_dimr   	attentionr   intermediater   r   r"   r   r_   layout_intermediater   )r3   r4   r|   r   ori_intermediate_sizer5   r7   r8   r   m  s   





zLiltLayer.__init__Fr   r   r   r   r   c                 C   sf   | j ||||d}|d }|d }|dd  }t| j| j| j|}	t| j| j| j|}
|	|
f| }|S )N)r   r   r   rc   )r   r   feed_forward_chunkr   r   layout_feed_forward_chunk)r3   r   r   r   r   self_attention_outputsr   r   r   layer_outputlayout_layer_outputr7   r7   r8   rG   ~  s"   zLiltLayer.forwardc                 C      |  |}| ||}|S r   )r   r   r3   r   intermediate_outputr   r7   r7   r8   r        
zLiltLayer.feed_forward_chunkc                 C   r   r   )r   r   r   r7   r7   r8   r     r   z#LiltLayer.layout_feed_forward_chunkr   r   )rR   rS   rT   r   r/   r   r   r   r   rG   r   r   rU   r7   r7   r5   r8   r   l  s"    
r   c                       sl   e Zd Z fddZ				ddejdejdejdB d	edB d
edB dedB deej e	B fddZ
  ZS )LiltEncoderc                    s4   t     | _t fddt jD | _d S )Nc                    s   g | ]}t  qS r7   )r   ).0_r4   r7   r8   
<listcomp>  s    z(LiltEncoder.__init__.<locals>.<listcomp>)r   r   r4   r   
ModuleListrangenum_hidden_layerslayerr2   r5   r   r8   r     s   
$zLiltEncoder.__init__NFTr   r   r   r   output_hidden_statesreturn_dictr   c                 C   s   |rdnd }|r
dnd }t | jD ]#\}	}
|r||f }|
||||}|d }|d }|r4||d f }q|r<||f }|sJtdd |||fD S t|||dS )Nr7   r   r   rc   c                 s   s    | ]	}|d ur|V  qd S r   r7   )r   vr7   r7   r8   	<genexpr>  s    z&LiltEncoder.forward.<locals>.<genexpr>)last_hidden_stater   
attentions)	enumerater   r   r
   )r3   r   r   r   r   r   r   all_hidden_statesall_self_attentionsilayer_modulelayer_outputsr7   r7   r8   rG     s<   	

	zLiltEncoder.forward)NFFT)rR   rS   rT   r   r/   r   r   r   r   r
   rG   rU   r7   r7   r5   r8   r     s*    	r   c                       r   )
LiltPoolerc                    s*   t    t|j|j| _t | _d S r   )r   r   r   ra   r"   r   Tanh
activationr2   r5   r7   r8   r     s   
zLiltPooler.__init__r   r   c                 C   s(   |d d df }|  |}| |}|S Nr   )r   r   )r3   r   first_token_tensorpooled_outputr7   r7   r8   rG     s   

zLiltPooler.forwardr   r7   r7   r5   r8   r     s    r   c                       s2   e Zd ZU eed< dZdZg Z fddZ  Z	S )LiltPreTrainedModelr4   liltTc                    s@   t  | t|trt|jt|jj	d 
d d S d S )Nr   r   )r   _init_weightsr   r   initcopy_r   r/   r0   shaper1   )r3   moduler5   r7   r8   r     s   
&z!LiltPreTrainedModel._init_weights)
rR   rS   rT   r   __annotations__base_model_prefixsupports_gradient_checkpointing_no_split_modulesr   rU   r7   r7   r5   r8   r     s   
 r   c                       s   e Zd Zd fdd	Zdd Zdd Ze									dd	ejdB d
ejdB dejdB dejdB dejdB dejdB de	dB de	dB de	dB de
ej eB fddZ  ZS )	LiltModelTc                    sN   t  | || _t|| _t|| _t|| _|rt	|nd| _
|   dS )zv
        add_pooling_layer (bool, *optional*, defaults to `True`):
            Whether to add a pooling layer
        N)r   r   r4   r   rF   rV   layout_embeddingsr   encoderr   pooler	post_init)r3   r4   add_pooling_layerr5   r7   r8   r     s   


zLiltModel.__init__c                 C   s   | j jS r   rF   r$   )r3   r7   r7   r8   get_input_embeddings  s   zLiltModel.get_input_embeddingsc                 C   s   || j _d S r   r   )r3   rw   r7   r7   r8   set_input_embeddings  s   zLiltModel.set_input_embeddingsNrB   rf   r   rC   r   rD   r   r   r   r   c
                 K   s  |dur|n| j j}|dur|n| j j}|	dur|	n| j j}	|dur*|dur*td|dur9| || | }n|durF| dd }ntd|\}}|durU|jn|j}|du rgtj	|d tj
|d}|du rttj||f|d}|du rt| jdr| jjddd|f }|||}|}n	tj	|tj
|d}| ||}| j||||d	\}}| j||d
}| j||||||	d}|d }| jdur| |nd}|	s||f|dd  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. See [Overview](#Overview) for normalization.

        Examples:

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

        >>> tokenizer = AutoTokenizer.from_pretrained("SCUT-DLVCLab/lilt-roberta-en-base")
        >>> model = AutoModel.from_pretrained("SCUT-DLVCLab/lilt-roberta-en-base")

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

        >>> encoding = tokenizer(words, boxes=boxes, return_tensors="pt")

        >>> outputs = model(**encoding)
        >>> 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)   r9   )r;   rC   )rB   r   rC   rD   )rf   r   )r   r   r   r   r   r   )r   pooler_outputr   r   )r4   r   r   use_return_dictrr   %warn_if_padding_and_no_attention_maskr?   r;   r/   r@   rA   onesrq   rF   rC   r1   get_extended_attention_maskr   r   r   r   r   r   )r3   rB   rf   r   rC   r   rD   r   r   r   kwargsrE   
batch_size
seq_lengthr;   buffered_token_type_ids buffered_token_type_ids_expandedextended_attention_maskembedding_outputlayout_embedding_outputencoder_outputssequence_outputr   r7   r7   r8   rG     sd   (

zLiltModel.forward)T)	NNNNNNNNN)rR   rS   rT   r   r   r   r   r/   r   r   r   r   rG   rU   r7   r7   r5   r8   r     sF    	
r   z
    LiLT Model transformer with a sequence classification/regression head on top (a linear layer on top of the pooled
    output) e.g. for GLUE tasks.
    )custom_introc                       s   e Zd Z fddZe										ddejdB dejdB dejdB dejdB dejdB d	ejdB d
ejdB de	dB de	dB de	dB de
ej eB fddZ  ZS )LiltForSequenceClassificationc                    s>   t  | |j| _|| _t|dd| _t|| _|   d S NF)r   )	r   r   
num_labelsr4   r   r   LiltClassificationHead
classifierr   r2   r5   r7   r8   r     s   
z&LiltForSequenceClassification.__init__NrB   rf   r   rC   r   rD   labelsr   r   r   r   c                 K   st  |
dur|
n| j j}
| j||||||||	|
d	}|d }| |}d}|dur||j}| j jdu rW| jdkr=d| j _n| jdkrS|jt	j
ksN|jt	jkrSd| j _nd| j _| j jdkrut }| jdkro|| | }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 )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,)`, *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, AutoModelForSequenceClassification
        >>> from datasets import load_dataset

        >>> tokenizer = AutoTokenizer.from_pretrained("SCUT-DLVCLab/lilt-roberta-en-base")
        >>> model = AutoModelForSequenceClassification.from_pretrained("SCUT-DLVCLab/lilt-roberta-en-base")

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

        >>> encoding = tokenizer(words, boxes=boxes, return_tensors="pt")

        >>> outputs = model(**encoding)
        >>> predicted_class_idx = outputs.logits.argmax(-1).item()
        >>> predicted_class = model.config.id2label[predicted_class_idx]
        ```Nrf   r   rC   r   rD   r   r   r   r   r   
regressionsingle_label_classificationmulti_label_classificationr   rc   losslogitsr   r   )r4   r  r   r  r=   r;   problem_typer  r:   r/   rA   rK   r   squeezer   r}   r   r   r   r   r3   rB   rf   r   rC   r   rD   r  r   r   r   r  r   r  r  r  loss_fctr   r7   r7   r8   rG     sV   .


"


z%LiltForSequenceClassification.forward
NNNNNNNNNN)rR   rS   rT   r   r   r/   
LongTensorr   r   r   r   r   rG   rU   r7   r7   r5   r8   r    sH    	
r  c                       s   e Zd Z fddZe										ddejdB dejdB dejdB dejdB dejdB d	ejdB d
ejdB dedB dedB dedB de	ej
 eB fddZ  ZS )LiltForTokenClassificationc                    sb   t  | |j| _t|dd| _|jd ur|jn|j}t|| _	t
|j|j| _|   d S r  )r   r   r  r   r   classifier_dropoutr,   r   r+   r-   ra   r"   r  r   r3   r4   r&  r5   r7   r8   r     s   z#LiltForTokenClassification.__init__NrB   rf   r   rC   r   rD   r  r   r   r   r   c                 K   s   |
dur|
n| j j}
| j||||||||	|
d	}|d }| |}| |}d}|durB||j}t }||d| j	|d}|
sX|f|dd  }|durV|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. 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, AutoModelForTokenClassification
        >>> from datasets import load_dataset

        >>> tokenizer = AutoTokenizer.from_pretrained("SCUT-DLVCLab/lilt-roberta-en-base")
        >>> model = AutoModelForTokenClassification.from_pretrained("SCUT-DLVCLab/lilt-roberta-en-base")

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

        >>> encoding = tokenizer(words, boxes=boxes, return_tensors="pt")

        >>> outputs = model(**encoding)
        >>> predicted_class_indices = outputs.logits.argmax(-1)
        ```Nr  r   r   rc   r  )r4   r  r   r-   r  r=   r;   r   r}   r  r   r   r   r!  r7   r7   r8   rG     s:   +

z"LiltForTokenClassification.forwardr#  )rR   rS   rT   r   r   r/   r$  r   r   r   r   r   rG   rU   r7   r7   r5   r8   r%    sH    	
r%  c                       s(   e Zd ZdZ fddZdd Z  ZS )r  z-Head for sentence-level classification tasks.c                    sT   t    t|j|j| _|jd ur|jn|j}t|| _	t|j|j
| _d S r   )r   r   r   ra   r"   r   r&  r,   r+   r-   r  out_projr'  r5   r7   r8   r   [  s   
zLiltClassificationHead.__init__c                 K   sL   |d d dd d f }|  |}| |}t|}|  |}| |}|S r   )r-   r   r/   tanhr(  )r3   featuresr  r   r7   r7   r8   rG   d  s   




zLiltClassificationHead.forward)rR   rS   rT   __doc__r   rG   rU   r7   r7   r5   r8   r  X  s    	r  c                       s   e Zd Z fddZe											ddejdB dejdB dejdB dejdB dejdB d	ejdB d
ejdB dejdB dedB dedB dedB de	ej
 eB fddZ  ZS )LiltForQuestionAnsweringc                    s@   t  | |j| _t|dd| _t|j|j| _| 	  d S r  )
r   r   r  r   r   r   ra   r"   
qa_outputsr   r2   r5   r7   r8   r   q  s
   z!LiltForQuestionAnswering.__init__NrB   rf   r   rC   r   rD   start_positionsend_positionsr   r   r   r   c                 K   sH  |dur|n| j j}| j|||||||	|
|d	}|d }| |}|jddd\}}|d }|d }d}|dur|durt| dkrO|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. See [Overview](#Overview) for normalization.

        Examples:

        ```python
        >>> from transformers import AutoTokenizer, AutoModelForQuestionAnswering
        >>> from datasets import load_dataset

        >>> tokenizer = AutoTokenizer.from_pretrained("SCUT-DLVCLab/lilt-roberta-en-base")
        >>> model = AutoModelForQuestionAnswering.from_pretrained("SCUT-DLVCLab/lilt-roberta-en-base")

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

        >>> encoding = tokenizer(words, boxes=boxes, return_tensors="pt")

        >>> outputs = model(**encoding)

        >>> answer_start_index = outputs.start_logits.argmax()
        >>> answer_end_index = outputs.end_logits.argmax()

        >>> predict_answer_tokens = encoding.input_ids[0, answer_start_index : answer_end_index + 1]
        >>> predicted_answer = tokenizer.decode(predict_answer_tokens)
        ```Nr  r   r   r   rH   )ignore_indexrc   )r  start_logits
end_logitsr   r   )r4   r  r   r-  splitr   r   lenr?   clampr   r   r   r   )r3   rB   rf   r   rC   r   rD   r.  r/  r   r   r   r  r   r  r  r1  r2  
total_lossignored_indexr"  
start_lossend_lossr   r7   r7   r8   rG   {  sP   /






z LiltForQuestionAnswering.forward)NNNNNNNNNNN)rR   rS   rT   r   r   r/   r$  r   r   r   r   r   rG   rU   r7   r7   r5   r8   r,  n  sN    
	
r,  )r,  r  r%  r   r   )3r+  r   r/   r   torch.nnr   r   r    r   r   activationsr   modeling_layersr	   modeling_outputsr
   r   r   r   r   modeling_utilsr   pytorch_utilsr   utilsr   r   configuration_liltr   
get_loggerrR   loggerModuler   rV   rm   r   r   r   r   r   r   r   r   r   r  r%  r  r,  __all__r7   r7   r7   r8   <module>   sN   
V8j:8 pbn