o
    Zh                     @   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mZ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j#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.Z0eG d*d+ d+e.Z1G d,d- d-ej#Z2eG d.d/ d/e.Z3g d0Z4dS )1zPyTorch LiLT model.    N)OptionalTupleUnion)nn)BCEWithLogitsLossCrossEntropyLossMSELoss   )ACT2FN)BaseModelOutputBaseModelOutputWithPoolingQuestionAnsweringModelOutputSequenceClassifierOutputTokenClassifierOutput)PreTrainedModel)apply_chunking_to_forward find_pruneable_heads_and_indicesprune_linear_layer)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 t|dd| _|j| _tj|j|j| jd| _	d S )	Npadding_idxZepsposition_ids)r   F)
persistentposition_embedding_typeabsolute)super__init__r   	EmbeddingZ
vocab_sizehidden_sizepad_token_idword_embeddingsmax_position_embeddingsposition_embeddingsZtype_vocab_sizetoken_type_embeddings	LayerNormlayer_norm_epsDropouthidden_dropout_probdropoutZregister_buffertorcharangeexpandgetattrr   r   selfconfig	__class__ U/var/www/auris/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| 
|}| |}|| }| jdkrY| |}||7 }| |}| |}||fS )Nr   dtypedevicer    )"create_position_ids_from_input_idsr   tor<   &create_position_ids_from_inputs_embedssizer/   zeroslongr   r&   r)   r   r(   r*   r.   )	r4   	input_idstoken_type_idsr   inputs_embedsinput_shaper)   
embeddingsr(   r8   r8   r9   forwardB   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/   ZcumsumZtype_asrB   )r4   rC   r   maskZincremental_indicesr8   r8   r9   r=   f   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   r:   r   )r@   r/   r0   r   rB   r<   Z	unsqueezer1   )r4   rE   rF   Zsequence_lengthr   r8   r8   r9   r?   s   s   z9LiltTextEmbeddings.create_position_ids_from_inputs_embeds)NNNN)__name__
__module____qualname__r"   rH   r=   r?   __classcell__r8   r8   r6   r9   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   )Zin_featuresZout_featuresr   )r!   r"   r   r#   Z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.   r3   r6   r8   r9   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   rI   )rT   rU   
IndexErrorrV   rW   r/   catr[   rY   r*   r.   )r4   bboxr   Zleft_position_embeddingsZupper_position_embeddingsZright_position_embeddingsZlower_position_embeddingserV   rW   Zspatial_position_embeddingsrY   r8   r8   r9   rH      s6    
22



zLiltLayoutEmbeddings.forward)NN)rN   rO   rP   r"   rH   rQ   r8   r8   r6   r9   rR      s    rR   c                       s8   e Zd Zd
 fdd	ZdddZ			ddd	Z  ZS )LiltSelfAttentionNc                    sX  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| _|pt|dd| _| jdks| jd	kr|j| _t	d
|j d | j| _|j| _d S )Nr   Zembedding_sizezThe hidden size (z6) is not a multiple of the number of attention heads ()r   r    relative_keyrelative_key_queryr\   r   )r!   r"   r$   num_attention_headshasattr
ValueErrorrL   attention_head_sizeall_head_sizer   rZ   querykeyvaluerX   layout_query
layout_keylayout_valuer,   Zattention_probs_dropout_probr.   r2   r   r'   r#   distance_embedding)r4   r5   r   r6   r8   r9   r"      s<   

zLiltSelfAttention.__init__r   c                 C   s:   |  d d | j| j| f }|j| }|ddddS )Nr   r   r\   r   r	   )r@   re   rh   viewpermute)r4   xrZnew_x_shaper8   r8   r9   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}| jdksY| jdkr| d }tj|tj|jddd}tj|tj|jddd}|| }| || j d }|j|jd}| jdkrtd	||}|| }n| jdkrtd	||}td
|
|}|| | }|t| j }|t| j| j  }|| }|| }|d ur|| }tjdd|}| |}|d ur|| }t	||}|dddd }| d d | j| j f }|j| }|d ur|| }tjdd|}| |}|d ur5|| }t	||}|dddd }| d d | jf }|j| }|ra||f|f}|S ||ff}|S )N)rt   r   rc   rd   r   r:   )r;   zbhld,lrd->bhlrzbhrd,lrd->bhlrrI   r   r\   r	   )ru   ro   rX   rn   rm   rj   rk   rl   r/   matmulZ	transposer   r@   r0   rB   r<   rq   rp   r'   r>   r;   Zeinsummathsqrtrh   r   ZSoftmaxr.   rr   
contiguousri   )r4   hidden_stateslayout_inputsattention_mask	head_maskoutput_attentionsZlayout_value_layerZlayout_key_layerZlayout_query_layerZmixed_query_layerZ	key_layerZvalue_layerZquery_layerZattention_scoresZlayout_attention_scores
seq_lengthZposition_ids_lZposition_ids_rZdistanceZpositional_embeddingZrelative_position_scoresZrelative_position_scores_queryZrelative_position_scores_keyZtmp_attention_scoresZtmp_layout_attention_scoresZlayout_attention_probsZlayout_context_layerZnew_context_layer_shapeZattention_probsZcontext_layeroutputsr8   r8   r9   rH      sp   











zLiltSelfAttention.forwardN)r   NNF)rN   rO   rP   r"   ru   rH   rQ   r8   r8   r6   r9   ra      s    
$	ra   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   rZ   r$   denser*   r+   r,   r-   r.   r3   r6   r8   r9   r"   F     
zLiltSelfOutput.__init__r{   input_tensorreturnc                 C   &   |  |}| |}| || }|S r   r   r.   r*   r4   r{   r   r8   r8   r9   rH   L     

zLiltSelfOutput.forwardrN   rO   rP   r"   r/   TensorrH   rQ   r8   r8   r6   r9   r   E      $r   c                       sj   e Zd Zd fdd	Zdd Z			ddejdejd	eej d
eej dee	 de
ej fddZ  ZS )LiltAttentionNc                    sR   t    t||d| _t|| _t | _|j}|j|j	 |_t|| _
||_d S )N)r   )r!   r"   ra   r4   r   outputsetpruned_headsr$   rX   layout_output)r4   r5   r   ori_hidden_sizer6   r8   r9   r"   T  s   



zLiltAttention.__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   rI   )lenr   r4   re   rh   r   r   rj   rk   rl   r   r   ri   union)r4   headsindexr8   r8   r9   prune_heads`  s   zLiltAttention.prune_headsFr{   r|   r}   r~   r   r   c           
      C   sT   |  |||||}| |d d |}| |d d |}||ff|dd   }	|	S )Nr   r   )r4   r   r   )
r4   r{   r|   r}   r~   r   Zself_outputsattention_outputlayout_attention_outputr   r8   r8   r9   rH   r  s   zLiltAttention.forwardr   r   )rN   rO   rP   r"   r   r/   r   r   FloatTensorboolr   rH   rQ   r8   r8   r6   r9   r   S  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   rZ   r$   intermediate_sizer   
isinstanceZ
hidden_actstrr
   intermediate_act_fnr3   r6   r8   r9   r"     s
   
zLiltIntermediate.__init__r{   r   c                 C   s   |  |}| |}|S r   )r   r   )r4   r{   r8   r8   r9   rH     s   

zLiltIntermediate.forwardr   r8   r8   r6   r9   r     s    r   c                       r   )
LiltOutputc                    sB   t    t|j|j| _tj|j|jd| _t	|j
| _d S r   )r!   r"   r   rZ   r   r$   r   r*   r+   r,   r-   r.   r3   r6   r8   r9   r"     r   zLiltOutput.__init__r{   r   r   c                 C   r   r   r   r   r8   r8   r9   rH     r   zLiltOutput.forwardr   r8   r8   r6   r9   r     r   r   c                       sp   e Zd Z fddZ			ddejdejdeej deej d	ee d
e	ej fddZ
dd Zdd Z  ZS )	LiltLayerc                    s   t    |j| _d| _t|| _t|| _t|| _	|j
}|j}|j
|j |_
|j|j |_t|| _t|| _||_
||_d S )Nr   )r!   r"   chunk_size_feed_forwardseq_len_dimr   	attentionr   intermediater   r   r$   r   rX   layout_intermediater   )r4   r5   r   Zori_intermediate_sizer6   r8   r9   r"     s   






zLiltLayer.__init__NFr{   r|   r}   r~   r   r   c                 C   sr   | j |||||d}|d d }|d d }|dd  }	t| j| j| j|}
t| j| j| j|}|
|ff|	 }	|	S )N)r   r   r   )r   r   feed_forward_chunkr   r   layout_feed_forward_chunk)r4   r{   r|   r}   r~   r   Zself_attention_outputsr   r   r   layer_outputZlayout_layer_outputr8   r8   r9   rH     s$   zLiltLayer.forwardc                 C      |  |}| ||}|S r   )r   r   r4   r   Zintermediate_outputr   r8   r8   r9   r        
zLiltLayer.feed_forward_chunkc                 C   r   r   )r   r   r   r8   r8   r9   r     r   z#LiltLayer.layout_feed_forward_chunkr   )rN   rO   rP   r"   r/   r   r   r   r   r   rH   r   r   rQ   r8   r8   r6   r9   r     s(    
r   c                       s|   e Zd Z fddZ					ddejdejdeej d	eej d
ee dee dee de	e
ej ef fddZ  ZS )LiltEncoderc                    s:   t     | _t fddt jD | _d| _d S )Nc                    s   g | ]}t  qS r8   )r   ).0_r5   r8   r9   
<listcomp>  s    z(LiltEncoder.__init__.<locals>.<listcomp>F)	r!   r"   r5   r   Z
ModuleListrangenum_hidden_layerslayergradient_checkpointingr3   r6   r   r9   r"     s   
 
zLiltEncoder.__init__NFTr{   r|   r}   r~   r   output_hidden_statesreturn_dictr   c              	   C   s   |rdnd }|r
dnd }	t | jD ]D\}
}|r||f }|d ur$||
 nd }| jr8| jr8| |j|||||}n||||||}|d d }|d d }|rU|	|d f }	q|r]||f }|sktdd |||	fD S t|||	dS )Nr8   r   r   c                 s   s    | ]	}|d ur|V  qd S r   r8   )r   vr8   r8   r9   	<genexpr>  s    z&LiltEncoder.forward.<locals>.<genexpr>)last_hidden_stater{   
attentions)	enumerater   r   ZtrainingZ_gradient_checkpointing_func__call__tupler   )r4   r{   r|   r}   r~   r   r   r   Zall_hidden_statesZall_self_attentionsiZlayer_moduleZlayer_head_maskZlayer_outputsr8   r8   r9   rH     sR   

	
	zLiltEncoder.forward)NNFFT)rN   rO   rP   r"   r/   r   r   r   r   r   r   r   rH   rQ   r8   r8   r6   r9   r     s0    
	r   c                       r   )
LiltPoolerc                    s*   t    t|j|j| _t | _d S r   )r!   r"   r   rZ   r$   r   ZTanh
activationr3   r6   r8   r9   r"   +  s   
zLiltPooler.__init__r{   r   c                 C   s(   |d d df }|  |}| |}|S Nr   )r   r   )r4   r{   Zfirst_token_tensorpooled_outputr8   r8   r9   rH   0  s   

zLiltPooler.forwardr   r8   r8   r6   r9   r   *  s    r   c                   @   s$   e Zd ZeZdZdZg Zdd ZdS )LiltPreTrainedModelliltTc                 C   s   t |tjr |jjjd| jjd |jdur|jj	  dS dS t |tj
rC|jjjd| jjd |jdurA|jj|j 	  dS dS t |tjrX|jj	  |jjd dS dS )zInitialize the weightsg        )meanZstdNg      ?)r   r   rZ   weightdataZnormal_r5   Zinitializer_rangeZbiasZzero_r#   r   r*   Zfill_)r4   moduler8   r8   r9   _init_weights@  s   

z!LiltPreTrainedModel._init_weightsN)	rN   rO   rP   r   Zconfig_classZbase_model_prefixZsupports_gradient_checkpointingZ_no_split_modulesr   r8   r8   r8   r9   r   9  s    r   c                       s   e Zd Zd fdd	Zdd Zdd Zdd	 Ze	
	
	
	
	
	
	
	
	
	
ddee	j
 dee	j
 dee	j
 dee	j
 dee	j
 dee	j
 dee	j
 dee dee dee deee	j
 ef 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"   r5   r   rG   rR   layout_embeddingsr   encoderr   pooler	post_init)r4   r5   add_pooling_layerr6   r8   r9   r"   S  s   


zLiltModel.__init__c                 C   s   | j jS r   rG   r&   )r4   r8   r8   r9   get_input_embeddingsd  s   zLiltModel.get_input_embeddingsc                 C   s   || j _d S r   r   )r4   rl   r8   r8   r9   set_input_embeddingsg  s   zLiltModel.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   )r4   Zheads_to_pruner   r   r8   r8   r9   _prune_headsj  s   zLiltModel._prune_headsNrC   r_   r}   rD   r   r~   rE   r   r   r   r   c              	   C   s  |dur|n| j j}|	dur|	n| j j}	|
dur|
n| j j}
|dur*|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 j}| 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", trust_remote_code=True)
        >>> 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)   r:   )r<   rD   )rC   r   rD   rE   )r_   r   )r}   r~   r   r   r   r   r   )r   Zpooler_outputr{   r   )r5   r   r   use_return_dictrg   Z%warn_if_padding_and_no_attention_maskr@   r<   r/   rA   rB   Zonesrf   rG   rD   r1   Zget_extended_attention_maskZget_head_maskr   r   r   r   r   r{   r   )r4   rC   r_   r}   rD   r   r~   rE   r   r   r   rF   Z
batch_sizer   r<   Zbuffered_token_type_idsZ buffered_token_type_ids_expandedZextended_attention_maskZembedding_outputZlayout_embedding_outputZencoder_outputssequence_outputr   r8   r8   r9   rH   r  sh   (

	zLiltModel.forward)T)
NNNNNNNNNN)rN   rO   rP   r"   r   r   r   r   r   r/   r   r   r   r   r   rH   rQ   r8   r8   r6   r9   r   Q  sN    	
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.
    )Zcustom_introc                       s   e Zd Z fddZe											ddeej deej deej	 deej deej d	eej	 d
eej	 deej dee
 dee
 dee
 deeej ef fddZ  ZS )LiltForSequenceClassificationc                    s>   t  | |j| _|| _t|dd| _t|| _|   d S NF)r   )	r!   r"   
num_labelsr5   r   r   LiltClassificationHead
classifierr   r3   r6   r8   r9   r"     s   
z&LiltForSequenceClassification.__init__NrC   r_   r}   rD   r   r~   rE   labelsr   r   r   r   c                 C   sv  |dur|n| j j}| j||||||||	|
|d
}|d }| |}d}|dur||j}| j jdu rX| jdkr>d| j _n| jdkrT|jt	j
ksO|jt	jkrTd| j _nd| j _| j jdkrvt }| jdkrp|| | }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", trust_remote_code=True)
        >>> 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	r_   r}   rD   r   r~   rE   r   r   r   r   r   Z
regressionZsingle_label_classificationZmulti_label_classificationr   r\   losslogitsr{   r   )r5   r   r   r   r>   r<   Zproblem_typer   r;   r/   rB   rL   r   squeezer   rq   r   r   r{   r   r4   rC   r_   r}   rD   r   r~   rE   r   r   r   r   r   r   r   r   loss_fctr   r8   r8   r9   rH     sX   .


"


z%LiltForSequenceClassification.forwardNNNNNNNNNNN)rN   rO   rP   r"   r   r   r/   
LongTensorr   r   r   r   r   r   rH   rQ   r8   r8   r6   r9   r     sN    	
r   c                       s   e Zd Z fddZe											ddeej deej deej deej deej d	eej d
eej deej dee	 dee	 dee	 de
eej ef 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.   rZ   r$   r   r   r4   r5   r   r6   r8   r9   r"   `  s   z#LiltForTokenClassification.__init__NrC   r_   r}   rD   r   r~   rE   r   r   r   r   r   c                 C   s   |dur|n| j j}| j||||||||	|
|d
}|d }| |}| |}d}|durC||j}t }||d| j	|d}|sY|f|dd  }|durW|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", trust_remote_code=True)
        >>> 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   r\   r   )r5   r   r   r.   r   r>   r<   r   rq   r   r   r{   r   r   r8   r8   r9   rH   n  s<   +

z"LiltForTokenClassification.forwardr   )rN   rO   rP   r"   r   r   r/   r   r   r   r   r   r   r   rH   rQ   r8   r8   r6   r9   r   ]  sN    	
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   rZ   r$   r   r   r-   r,   r.   r   out_projr   r6   r8   r9   r"     s   
zLiltClassificationHead.__init__c                 K   sL   |d d dd d f }|  |}| |}t|}|  |}| |}|S r   )r.   r   r/   tanhr   )r4   featureskwargsrs   r8   r8   r9   rH     s   




zLiltClassificationHead.forward)rN   rO   rP   __doc__r"   rH   rQ   r8   r8   r6   r9   r     s    	r   c                       s   e Zd Z fddZe												ddeej deej deej deej deej d	eej d
eej deej deej dee	 dee	 dee	 de
eej ef 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   rZ   r$   
qa_outputsr   r3   r6   r8   r9   r"     s
   z!LiltForQuestionAnswering.__init__NrC   r_   r}   rD   r   r~   rE   start_positionsend_positionsr   r   r   r   c                 C   sJ  |dur|n| j j}| j||||||||
||d
}|d }| |}|jddd\}}|d }|d }d}|dur|	durt| dkrP|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", trust_remote_code=True)
        >>> 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   rI   )Zignore_indexr\   )r   start_logits
end_logitsr{   r   )r5   r   r   r   splitr   rz   r   r@   clampr   r   r{   r   )r4   rC   r_   r}   rD   r   r~   rE   r   r   r   r   r   r   r   r   r   r   Z
total_lossZignored_indexr   Z
start_lossZend_lossr   r8   r8   r9   rH     sR   /






z LiltForQuestionAnswering.forward)NNNNNNNNNNNN)rN   rO   rP   r"   r   r   r/   r   r   r   r   r   r   r   rH   rQ   r8   r8   r6   r9   r     sT    
	
r   )r   r   r   r   r   )5r   rx   typingr   r   r   r/   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   utilsr   r   Zconfiguration_liltr   Z
get_loggerrN   loggerModuler   rR   ra   r   r   r   r   r   r   r   r   r   r   r   r   r   __all__r8   r8   r8   r9   <module>   sP   
Y8 5<H qco