o
    ik                     @   s  d Z ddlZddlmZm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 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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/d0 d0e.Z3g d1Z4dS )2zPyTorch LiLT model.    N)OptionalUnion)nn)BCEWithLogitsLossCrossEntropyLossMSELoss   )ACT2FN)GradientCheckpointingLayer)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epsposition_ids)r   F)
persistentposition_embedding_typeabsolute)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expandgetattrr    r   selfconfig	__class__ c/home/ubuntu/veenaModal/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| 
|}| |}|| }| jdkrY| |}||7 }| |}| |}||fS )Nr   dtypedevicer!   )"create_position_ids_from_input_idsr   tor@   &create_position_ids_from_inputs_embedssizer3   zeroslongr   r(   r,   r    r*   r-   r1   )	r8   	input_idstoken_type_idsr   inputs_embedsinput_shaper,   
embeddingsr*   r<   r<   r=   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intr3   cumsumtype_asrF   )r8   rG   r   maskincremental_indicesr<   r<   r=   rA   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   )rD   r3   r4   r   rF   r@   	unsqueezer5   )r8   rI   rJ   sequence_lengthr   r<   r<   r=   rC   s   s   z9LiltTextEmbeddings.create_position_ids_from_inputs_embeds)NNNN)__name__
__module____qualname__r#   rL   rA   rC   __classcell__r<   r<   r:   r=   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/   r0   r1   r7   r:   r<   r=   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   rM   )r`   ra   
IndexErrorrb   rc   r3   catrg   re   r-   r1   )r8   bboxr   left_position_embeddingsupper_position_embeddingsright_position_embeddingslower_position_embeddingserb   rc   spatial_position_embeddingsre   r<   r<   r=   rL      s6    
22



zLiltLayoutEmbeddings.forwardNN)rW   rX   rY   r#   rL   rZ   r<   r<   r:   r=   r[      s    r[   c                       s8   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| _|pt|dd| _| jdks| jd	kr|j| _t	d
|j d | j| _|j| _|| _d S )Nr   embedding_sizezThe hidden size (z6) is not a multiple of the number of attention heads ()r    r!   relative_keyrelative_key_queryrh   r   )r"   r#   r&   num_attention_headshasattr
ValueErrorrP   attention_head_sizeall_head_sizer   rf   querykeyvaluerd   layout_query
layout_keylayout_valuer/   attention_probs_dropout_probr1   r6   r    r)   r$   distance_embedding	layer_idx)r8   r9   r    r   r:   r<   r=   r#      s>   


zLiltSelfAttention.__init__r   c                 C   s:   |  d d | j| j| f }|j| }|ddddS )Nr   r   rh   r   r   )rD   rx   r{   viewpermute)r8   xrnew_x_shaper<   r<   r=   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)r   r   rv   rw   r   r>   )r?   zbhld,lrd->bhlrzbhrd,lrd->bhlrrM   r   rh   r   )r   r   rd   r   r   r}   r~   r   r3   matmul	transposer    rD   r4   rF   r@   r   r   r)   rB   r?   einsummathsqrtr{   r   Softmaxr1   r   
contiguousr|   )r8   hidden_stateslayout_inputsattention_mask	head_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
seq_lengthposition_ids_lposition_ids_rdistancepositional_embeddingrelative_position_scoresrelative_position_scores_queryrelative_position_scores_keytmp_attention_scorestmp_layout_attention_scoreslayout_attention_probslayout_context_layernew_context_layer_shapeattention_probscontext_layeroutputsr<   r<   r=   rL      sp   











zLiltSelfAttention.forwardrr   )r   NNF)rW   rX   rY   r#   r   rL   rZ   r<   r<   r:   r=   rs      s    
%	rs   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   rf   r&   denser-   r.   r/   r0   r1   r7   r:   r<   r=   r#   G     
zLiltSelfOutput.__init__r   input_tensorreturnc                 C   &   |  |}| |}| || }|S Nr   r1   r-   r8   r   r   r<   r<   r=   rL   M     

zLiltSelfOutput.forwardrW   rX   rY   r#   r3   TensorrL   rZ   r<   r<   r:   r=   r   F      $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                    sT   t    t|||d| _t|| _t | _|j}|j|j	 |_t|| _
||_d S )N)r    r   )r"   r#   rs   r8   r   outputsetpruned_headsr&   rd   layout_output)r8   r9   r    r   ori_hidden_sizer:   r<   r=   r#   U  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   rM   )lenr   r8   rx   r{   r   r   r}   r~   r   r   r   r|   union)r8   headsindexr<   r<   r=   prune_headsa  s   zLiltAttention.prune_headsFr   r   r   r   r   r   c           
      C   sT   |  |||||}| |d d |}| |d d |}||ff|dd   }	|	S )Nr   r   )r8   r   r   )
r8   r   r   r   r   r   self_outputsattention_outputlayout_attention_outputr   r<   r<   r=   rL   s  s   zLiltAttention.forwardrr   r   )rW   rX   rY   r#   r   r3   r   r   FloatTensorbooltuplerL   rZ   r<   r<   r:   r=   r   T  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   rf   r&   intermediate_sizer   
isinstance
hidden_actstrr	   intermediate_act_fnr7   r:   r<   r=   r#     s
   
zLiltIntermediate.__init__r   r   c                 C   s   |  |}| |}|S r   )r   r   )r8   r   r<   r<   r=   rL     s   

zLiltIntermediate.forwardr   r<   r<   r:   r=   r     s    r   c                       r   )
LiltOutputc                    sB   t    t|j|j| _tj|j|jd| _t	|j
| _d S r   )r"   r#   r   rf   r   r&   r   r-   r.   r/   r0   r1   r7   r:   r<   r=   r#     r   zLiltOutput.__init__r   r   r   c                 C   r   r   r   r   r<   r<   r=   rL     r   zLiltOutput.forwardr   r<   r<   r:   r=   r     r   r   c                       sr   e Zd Zd 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 )	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   rd   layout_intermediater   )r8   r9   r   r   ori_intermediate_sizer:   r<   r=   r#     s   





zLiltLayer.__init__Fr   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)r8   r   r   r   r   r   self_attention_outputsr   r   r   layer_outputlayout_layer_outputr<   r<   r=   rL     s$   zLiltLayer.forwardc                 C      |  |}| ||}|S r   )r   r   r8   r   intermediate_outputr   r<   r<   r=   r        
zLiltLayer.feed_forward_chunkc                 C   r   r   )r   r   r   r<   r<   r=   r     r   z#LiltLayer.layout_feed_forward_chunkr   r   )rW   rX   rY   r#   r3   r   r   r   r   r   rL   r   r   rZ   r<   r<   r:   r=   r     s(    
r   c                       s~   e Zd Zd 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 )LiltEncoderNc                    s:   t     | _t fddt jD | _d| _d S )Nc                    s   g | ]}t  |d qS )r   )r   ).0ir9   r<   r=   
<listcomp>  s    z(LiltEncoder.__init__.<locals>.<listcomp>F)	r"   r#   r9   r   
ModuleListrangenum_hidden_layerslayergradient_checkpointing)r8   r9   r   r:   r   r=   r#     s   
 
zLiltEncoder.__init__FTr   r   r   r   r   output_hidden_statesreturn_dictr   c                 C   s   |rdnd }|r
dnd }	t | jD ]2\}
}|r||f }|d ur$||
 nd }||||||}|d d }|d d }|rC|	|d f }	q|rK||f }|sYtdd |||	fD S t|||	dS )Nr<   r   r   c                 s   s    | ]	}|d ur|V  qd S r   r<   )r   vr<   r<   r=   	<genexpr>  s    z&LiltEncoder.forward.<locals>.<genexpr>)last_hidden_stater   
attentions)	enumerater   r   r   )r8   r   r   r   r   r   r   r   all_hidden_statesall_self_attentionsr   layer_modulelayer_head_masklayer_outputsr<   r<   r=   rL     s@   


	zLiltEncoder.forwardr   )NNFFT)rW   rX   rY   r#   r3   r   r   r   r   r   r   r   rL   rZ   r<   r<   r:   r=   r     s0    
	r   c                       r   )
LiltPoolerc                    s*   t    t|j|j| _t | _d S r   )r"   r#   r   rf   r&   r   Tanh
activationr7   r:   r<   r=   r#   "  s   
zLiltPooler.__init__r   r   c                 C   s(   |d d df }|  |}| |}|S Nr   )r   r  )r8   r   first_token_tensorpooled_outputr<   r<   r=   rL   '  s   

zLiltPooler.forwardr   r<   r<   r:   r=   r  !  s    r  c                   @   s*   e Zd ZU eed< dZdZg Zdd ZdS )LiltPreTrainedModelr9   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        )meanstdNg      ?)r   r   rf   weightdatanormal_r9   initializer_rangebiaszero_r$   r   r-   fill_)r8   moduler<   r<   r=   _init_weights7  s   

z!LiltPreTrainedModel._init_weightsN)	rW   rX   rY   r   __annotations__base_model_prefixsupports_gradient_checkpointing_no_split_modulesr  r<   r<   r<   r=   r  0  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#   r9   r   rK   r[   layout_embeddingsr   encoderr  pooler	post_init)r8   r9   add_pooling_layerr:   r<   r=   r#   J  s   


zLiltModel.__init__c                 C   s   | j jS r   rK   r(   )r8   r<   r<   r=   get_input_embeddings[  s   zLiltModel.get_input_embeddingsc                 C   s   || j _d S r   r  )r8   r   r<   r<   r=   set_input_embeddings^  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   )r8   heads_to_pruner   r   r<   r<   r=   _prune_headsa  s   zLiltModel._prune_headsNrG   rk   r   rH   r   r   rI   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")
        >>> 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@   rH   )rG   r   rH   rI   )rk   r   )r   r   r   r   r   r   r   )r   pooler_outputr   r   )r9   r   r   use_return_dictrz   %warn_if_padding_and_no_attention_maskrD   r@   r3   rE   rF   onesry   rK   rH   r5   get_extended_attention_maskget_head_maskr   r  r  r  r   r   r   )r8   rG   rk   r   rH   r   r   rI   r   r   r   rJ   
batch_sizer   r@   buffered_token_type_ids buffered_token_type_ids_expandedextended_attention_maskembedding_outputlayout_embedding_outputencoder_outputssequence_outputr  r<   r<   r=   rL   i  sh   (

	zLiltModel.forward)T)
NNNNNNNNNN)rW   rX   rY   r#   r   r!  r$  r   r   r3   r   r   r   r   r   rL   rZ   r<   r<   r:   r=   r  H  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.
    )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_labelsr9   r  r	  LiltClassificationHead
classifierr  r7   r:   r<   r=   r#     s   
z&LiltForSequenceClassification.__init__NrG   rk   r   rH   r   r   rI   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")
        >>> 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	rk   r   rH   r   r   rI   r   r   r   r   r   
regressionsingle_label_classificationmulti_label_classificationr   rh   losslogitsr   r   )r9   r'  r	  r9  rB   r@   problem_typer7  r?   r3   rF   rP   r   squeezer   r   r   r   r   r   r8   rG   rk   r   rH   r   r   rI   r:  r   r   r   r   r3  rA  r@  loss_fctr   r<   r<   r=   rL     sX   .


"


z%LiltForSequenceClassification.forwardNNNNNNNNNNN)rW   rX   rY   r#   r   r   r3   
LongTensorr   r   r   r   r   r   rL   rZ   r<   r<   r:   r=   r5    sN    	
r5  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 r6  )r"   r#   r7  r  r	  classifier_dropoutr0   r   r/   r1   rf   r&   r9  r  r8   r9   rI  r:   r<   r=   r#   W  s   z#LiltForTokenClassification.__init__NrG   rk   r   rH   r   r   rI   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")
        >>> 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   rh   r?  )r9   r'  r	  r1   r9  rB   r@   r   r   r7  r   r   r   rD  r<   r<   r=   rL   e  s<   +

z"LiltForTokenClassification.forwardrF  )rW   rX   rY   r#   r   r   r3   rG  r   r   r   r   r   r   rL   rZ   r<   r<   r:   r=   rH  T  sN    	
rH  c                       s(   e Zd ZdZ fddZdd Z  ZS )r8  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   rf   r&   r   rI  r0   r/   r1   r7  out_projrJ  r:   r<   r=   r#     s   
zLiltClassificationHead.__init__c                 K   sL   |d d dd d f }|  |}| |}t|}|  |}| |}|S r  )r1   r   r3   tanhrK  )r8   featureskwargsr   r<   r<   r=   rL     s   




zLiltClassificationHead.forward)rW   rX   rY   __doc__r#   rL   rZ   r<   r<   r:   r=   r8    s    	r8  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 r6  )
r"   r#   r7  r  r	  r   rf   r&   
qa_outputsr  r7   r:   r<   r=   r#     s
   z!LiltForQuestionAnswering.__init__NrG   rk   r   rH   r   r   rI   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")
        >>> 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   rM   )ignore_indexrh   )r@  start_logits
end_logitsr   r   )r9   r'  r	  rQ  splitrC  r   r   rD   clampr   r   r   r   )r8   rG   rk   r   rH   r   r   rI   rR  rS  r   r   r   r   r3  rA  rU  rV  
total_lossignored_indexrE  
start_lossend_lossr   r<   r<   r=   rL     sR   /






z LiltForQuestionAnswering.forward)NNNNNNNNNNNN)rW   rX   rY   r#   r   r   r3   rG  r   r   r   r   r   r   rL   rZ   r<   r<   r:   r=   rP    sT    
	
rP  )rP  r5  rH  r  r  )5rO  r   typingr   r   r3   r   torch.nnr   r   r   activationsr	   modeling_layersr
   modeling_outputsr   r   r   r   r   modeling_utilsr   pytorch_utilsr   r   r   utilsr   r   configuration_liltr   
get_loggerrW   loggerModuler   r[   rs   r   r   r   r   r   r   r  r  r  r5  rH  r8  rP  __all__r<   r<   r<   r=   <module>   sP   
Y8 5<> qco