U
    ,-es                     @   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mZmZ ddl m!Z! e"e#Z$dZ%dgZ&G dd dej'Z(G dd dej'Z)G dd dej'Z*G dd dej'Z+G dd dej'Z,G dd dej'Z-G dd dej'Z.G dd dej'Z/G d d! d!ej'Z0G d"d# d#ej'Z1G d$d% d%eZ2d&Z3d'Z4ed(e3G d)d* d*e2Z5ed+e3G d,d- d-e2Z6ed.e3G d/d0 d0e2Z7G d1d2 d2ej'Z8ed3e3G d4d5 d5e2Z9dS )6z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)add_start_docstrings%add_start_docstrings_to_model_forwardloggingreplace_return_docstrings   )
LiltConfigr   z!SCUT-DLVCLab/lilt-roberta-en-basec                       s6   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__ g/var/www/html/Darija-Ai-Train/env/lib/python3.8/site-packages/transformers/models/lilt/modeling_lilt.pyr$   2   s$    
    zLiltTextEmbeddings.__init__Nc           	      C   s   |d kr2|d k	r(|  || j|j}n
| |}|d k	rD| }n| d d }|d krrtj|tj| j	jd}|d kr| 
|}| |}|| }| jdkr| |}||7 }| |}| |}||fS )Nr   dtypedevicer"   )"create_position_ids_from_input_idsr   tor>   &create_position_ids_from_inputs_embedssizer1   zeroslongr   r(   r+   r!   r*   r,   r0   )	r6   	input_idstoken_type_idsr   inputs_embedsinput_shaper+   
embeddingsr*   r:   r:   r;   forwardI   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intr1   ZcumsumZtype_asrD   )r6   rE   r   maskZincremental_indicesr:   r:   r;   r?   m   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   )rB   r1   r2   r   rD   r>   Z	unsqueezer3   )r6   rG   rH   Zsequence_lengthr   r:   r:   r;   rA   z   s       z9LiltTextEmbeddings.create_position_ids_from_inputs_embeds)NNNN)__name__
__module____qualname__r$   rJ   r?   rA   __classcell__r:   r:   r8   r;   r   1   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/   r0   r5   r8   r:   r;   r$      s"    

 
zLiltLayoutEmbeddings.__init__Nc              
   C   sT  zt|  |d d d d df }| |d d d d df }|  |d d d d df }| |d d d d df }W n, tk
r } ztd|W 5 d }~X Y nX | |d d d d df |d d d d df  }| |d d d d df |d d d d df  }	tj||||||	gdd}
| |
}
| |}|
| }
| 	|
}
| 
|
}
|
S )Nr   r      r	   z;The `bbox` coordinate values should be within 0-1000 range.r   rK   )rV   rW   
IndexErrorrX   rY   r1   catr]   r[   r,   r0   )r6   bboxr   Zleft_position_embeddingsZupper_position_embeddingsZright_position_embeddingsZlower_position_embeddingserX   rY   Zspatial_position_embeddingsr[   r:   r:   r;   rJ      s2     22



zLiltLayoutEmbeddings.forward)NN)rP   rQ   rR   r$   rJ   rS   r:   r:   r8   r;   rT      s   rT   c                       s2   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| _|pt|dd| _| jdks0| jd	krR|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
ValueErrorrN   attention_head_sizeall_head_sizer   r\   querykeyvaluerZ   layout_query
layout_keylayout_valuer.   Zattention_probs_dropout_probr0   r4   r!   r)   r%   distance_embedding)r6   r7   r!   r8   r:   r;   r$      sB    

 

 

 
  zLiltSelfAttention.__init__r   c                 C   s:   |  d d | j| j| f }|j| }|ddddS )Nr   r   r^   r   r	   )rB   rg   rj   viewpermute)r6   xrZ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s| jdkrz| 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rFtd	||}|| }n4| jdkrztd	||}td
|
|}|| | }|t| j }|t| j| j  }|| }|| }|d k	r|| }tjdd|}| |}|d k	r|| }t	||}|dddd }| d d | j| j f }|j| }|d k	rH|| }tjdd|}| |}|d k	rt|| }t	||}|dddd }| d d | jf }|j| }|r||f|fn||ff}|S )N)rv   r   re   rf   r   r<   )r=   zbhld,lrd->bhlrzbhrd,lrd->bhlrrK   r   r^   r	   )rw   rq   rZ   rp   ro   rl   rm   rn   r1   matmulZ	transposer!   rB   r2   rD   r>   rs   rr   r)   r@   r=   Zeinsummathsqrtrj   r   ZSoftmaxr0   rt   
contiguousrk   )r6   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outputsr:   r:   r;   rJ      sl    











zLiltSelfAttention.forward)N)r   )NNF)rP   rQ   rR   r$   rw   rJ   rS   r:   r:   r8   r;   rc      s   $
	   rc   c                       s4   e Zd Z fddZejejejdddZ  ZS )LiltSelfOutputc                    sB   t    t|j|j| _tj|j|jd| _t|j	| _
d S Nr   )r#   r$   r   r\   r&   denser,   r-   r.   r/   r0   r5   r8   r:   r;   r$   M  s    
zLiltSelfOutput.__init__r}   input_tensorreturnc                 C   s&   |  |}| |}| || }|S Nr   r0   r,   r6   r}   r   r:   r:   r;   rJ   S  s    

zLiltSelfOutput.forwardrP   rQ   rR   r$   r1   TensorrJ   rS   r:   r:   r8   r;   r   L  s   r   c                       sZ   e Zd Zd
 fdd	Zdd Zdejejeej eej ee	 e
ej ddd	Z  ZS )LiltAttentionNc                    sR   t    t||d| _t|| _t | _|j}|j|j	 |_t|| _
||_d S )N)r!   )r#   r$   rc   r6   r   outputsetpruned_headsr&   rZ   layout_output)r6   r7   r!   ori_hidden_sizer8   r:   r;   r$   [  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   rK   )lenr   r6   rg   rj   r   r   rl   rm   rn   r   r   rk   union)r6   headsindexr:   r:   r;   prune_headsg  s       zLiltAttention.prune_headsFr}   r~   r   r   r   r   c           
      C   sT   |  |||||}| |d d |}| |d d |}||ff|dd   }	|	S )Nr   r   )r6   r   r   )
r6   r}   r~   r   r   r   Zself_outputsattention_outputlayout_attention_outputr   r:   r:   r;   rJ   y  s    zLiltAttention.forward)N)NNF)rP   rQ   rR   r$   r   r1   r   r   FloatTensorboolr   rJ   rS   r:   r:   r8   r;   r   Z  s      r   c                       s0   e Zd Z fddZejejdddZ  ZS )LiltIntermediatec                    sB   t    t|j|j| _t|jt	r6t
|j | _n|j| _d S r   )r#   r$   r   r\   r&   intermediate_sizer   
isinstanceZ
hidden_actstrr
   intermediate_act_fnr5   r8   r:   r;   r$     s
    
zLiltIntermediate.__init__r}   r   c                 C   s   |  |}| |}|S r   )r   r   )r6   r}   r:   r:   r;   rJ     s    

zLiltIntermediate.forwardr   r:   r:   r8   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 )
LiltOutputc                    sB   t    t|j|j| _tj|j|jd| _t	|j
| _d S r   )r#   r$   r   r\   r   r&   r   r,   r-   r.   r/   r0   r5   r8   r:   r;   r$     s    
zLiltOutput.__init__r   c                 C   s&   |  |}| |}| || }|S r   r   r   r:   r:   r;   rJ     s    

zLiltOutput.forwardr   r:   r:   r8   r;   r     s   r   c                       s`   e Zd Z fddZdejejeej eej ee e	ej d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   rZ   layout_intermediater   )r6   r7   r   Zori_intermediate_sizer8   r:   r;   r$     s    





zLiltLayer.__init__NFr   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)r6   r}   r~   r   r   r   Zself_attention_outputsr   r   r   layer_outputZlayout_layer_outputr:   r:   r;   rJ     s0          zLiltLayer.forwardc                 C   s   |  |}| ||}|S r   )r   r   r6   r   Zintermediate_outputr   r:   r:   r;   r     s    
zLiltLayer.feed_forward_chunkc                 C   s   |  |}| ||}|S r   )r   r   r   r:   r:   r;   r     s    
z#LiltLayer.layout_feed_forward_chunk)NNF)rP   rQ   rR   r$   r1   r   r   r   r   r   rJ   r   r   rS   r:   r:   r8   r;   r     s      r   c                       sd   e Zd Z fddZd	ej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 )
LiltEncoderc                    s:   t     | _t fddt jD | _d| _d S )Nc                    s   g | ]}t  qS r:   )r   ).0_r7   r:   r;   
<listcomp>  s     z(LiltEncoder.__init__.<locals>.<listcomp>F)	r#   r$   r7   r   Z
ModuleListrangenum_hidden_layerslayergradient_checkpointingr5   r8   r   r;   r$     s    
 zLiltEncoder.__init__NFT)r}   r~   r   r   r   output_hidden_statesreturn_dictr   c                    s   |rdnd } rdnd }	t | jD ]\}
}|r8||f }|d k	rH||
 nd }| jr| jr fdd}tjj||||||}n||||| }|d d }|d d } r"|	|d f }	q"|r||f }|stdd |||	fD S t|||	dS )	Nr:   c                    s    fdd}|S )Nc                     s    | f S r   r:   )inputs)moduler   r:   r;   custom_forward  s    zJLiltEncoder.forward.<locals>.create_custom_forward.<locals>.custom_forwardr:   )r   r   r   )r   r;   create_custom_forward  s    z2LiltEncoder.forward.<locals>.create_custom_forwardr   r   c                 s   s   | ]}|d k	r|V  qd S r   r:   )r   vr:   r:   r;   	<genexpr>&  s   z&LiltEncoder.forward.<locals>.<genexpr>)last_hidden_stater}   
attentions)		enumerater   r   Ztrainingr1   utils
checkpointtupler   )r6   r}   r~   r   r   r   r   r   Zall_hidden_statesZall_self_attentionsiZlayer_moduleZlayer_head_maskr   Zlayer_outputsr:   r   r;   rJ     sP    


	zLiltEncoder.forward)NNFFT)rP   rQ   rR   r$   r1   r   r   r   r   r   r   r   rJ   rS   r:   r:   r8   r;   r     s    
     r   c                       s0   e Zd Z fddZejejdddZ  ZS )
LiltPoolerc                    s*   t    t|j|j| _t | _d S r   )r#   r$   r   r\   r&   r   ZTanh
activationr5   r8   r:   r;   r$   8  s    
zLiltPooler.__init__r   c                 C   s(   |d d df }|  |}| |}|S Nr   )r   r   )r6   r}   Zfirst_token_tensorpooled_outputr:   r:   r;   rJ   =  s    

zLiltPooler.forwardr   r:   r:   r8   r;   r   7  s   r   c                   @   s2   e Zd ZdZeZdZdZg Zdd Z	d
ddZ
d	S )LiltPreTrainedModelz
    An abstract class to handle weights initialization and a simple interface for downloading and loading pretrained
    models.
    liltTc                 C   s   t |tjr:|jjjd| jjd |jdk	r|jj	  nft |tj
rz|jjjd| jjd |jdk	r|jj|j 	  n&t |tjr|jj	  |jjd dS )zInitialize the weightsg        )ZmeanZstdNg      ?)r   r   r\   weightdataZnormal_r7   Zinitializer_rangeZbiasZzero_r%   r   r,   Zfill_)r6   r   r:   r:   r;   _init_weightsR  s    

z!LiltPreTrainedModel._init_weightsFc                 C   s   t |tr||_d S r   )r   r   r   )r6   r   rn   r:   r:   r;   _set_gradient_checkpointingb  s    
z/LiltPreTrainedModel._set_gradient_checkpointingN)F)rP   rQ   rR   __doc__r   config_classZbase_model_prefixZsupports_gradient_checkpointingZ_no_split_modulesr   r   r:   r:   r:   r;   r   F  s   r   a=  
    This model inherits from [`PreTrainedModel`]. Check the superclass documentation for the generic methods the
    library implements for all its model (such as downloading or saving, resizing the input embeddings, pruning heads
    etc.)

    This model is also a PyTorch [torch.nn.Module](https://pytorch.org/docs/stable/nn.html#torch.nn.Module) subclass.
    Use it as a regular PyTorch Module and refer to the PyTorch documentation for all matter related to general usage
    and behavior.

    Parameters:
        config ([`LiltConfig`]): Model configuration class with all the parameters of the
            model. Initializing with a config file does not load the weights associated with the model, only the
            configuration. Check out the [`~PreTrainedModel.from_pretrained`] method to load the model weights.
a-  
    Args:
        input_ids (`torch.LongTensor` of shape `({0})`):
            Indices of input sequence tokens in the vocabulary.

            Indices can be obtained using [`AutoTokenizer`]. See [`PreTrainedTokenizer.encode`] and
            [`PreTrainedTokenizer.__call__`] for details.

            [What are input IDs?](../glossary#input-ids)

        bbox (`torch.LongTensor` of shape `({0}, 4)`, *optional*):
            Bounding boxes of each input sequence tokens. Selected in the range `[0,
            config.max_2d_position_embeddings-1]`. Each bounding box should be a normalized version in (x0, y0, x1, y1)
            format, where (x0, y0) corresponds to the position of the upper left corner in the bounding box, and (x1,
            y1) represents the position of the lower right corner. See [Overview](#Overview) for normalization.

        attention_mask (`torch.FloatTensor` of shape `({0})`, *optional*):
            Mask to avoid performing attention on padding token indices. Mask values selected in `[0, 1]`:

            - 1 for tokens that are **not masked**,
            - 0 for tokens that are **masked**.

            [What are attention masks?](../glossary#attention-mask)
        token_type_ids (`torch.LongTensor` of shape `({0})`, *optional*):
            Segment token indices to indicate first and second portions of the inputs. Indices are selected in `[0,
            1]`:

            - 0 corresponds to a *sentence A* token,
            - 1 corresponds to a *sentence B* token.

            [What are token type IDs?](../glossary#token-type-ids)
        position_ids (`torch.LongTensor` of shape `({0})`, *optional*):
            Indices of positions of each input sequence tokens in the position embeddings. Selected in the range `[0,
            config.max_position_embeddings - 1]`.

            [What are position IDs?](../glossary#position-ids)
        head_mask (`torch.FloatTensor` of shape `(num_heads,)` or `(num_layers, num_heads)`, *optional*):
            Mask to nullify selected heads of the self-attention modules. Mask values selected in `[0, 1]`:

            - 1 indicates the head is **not masked**,
            - 0 indicates the head is **masked**.

        inputs_embeds (`torch.FloatTensor` of shape `({0}, hidden_size)`, *optional*):
            Optionally, instead of passing `input_ids` you can choose to directly pass an embedded representation. This
            is useful if you want more control over how to convert `input_ids` indices into associated vectors than the
            model's internal embedding lookup matrix.
        output_attentions (`bool`, *optional*):
            Whether or not to return the attentions tensors of all attention layers. See `attentions` under returned
            tensors for more detail.
        output_hidden_states (`bool`, *optional*):
            Whether or not to return the hidden states of all layers. See `hidden_states` under returned tensors for
            more detail.
        return_dict (`bool`, *optional*):
            Whether or not to return a [`~utils.ModelOutput`] instead of a plain tuple.
z^The bare LiLT Model transformer outputting raw hidden-states without any specific head on top.c                       s   e Zd Zd fdd	Zdd Zdd Zdd	 Zee	d
e
eeddeej eej eej eej eej eej eej ee ee ee eeej ef dddZ  ZS )	LiltModelTc                    sN   t  | || _t|| _t|| _t|| _|r<t	|nd | _
|   d S r   )r#   r$   r7   r   rI   rT   layout_embeddingsr   encoderr   pooler	post_init)r6   r7   add_pooling_layerr8   r:   r;   r$     s    


zLiltModel.__init__c                 C   s   | j jS r   rI   r(   )r6   r:   r:   r;   get_input_embeddings  s    zLiltModel.get_input_embeddingsc                 C   s   || j _d S r   r   )r6   rn   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   )r6   Zheads_to_pruner   r   r:   r:   r;   _prune_heads  s    zLiltModel._prune_headsbatch_size, sequence_lengthoutput_typer   N)rE   ra   r   rF   r   r   rG   r   r   r   r   c              	   C   s  |dk	r|n| j j}|	dk	r |	n| j j}	|
dk	r4|
n| j j}
|dk	rV|dk	rVtdn@|dk	rt| || | }n"|dk	r| dd }ntd|\}}|dk	r|jn|j}|dkrtj	|d tj
|d}|dkrtj||f|d}|dkr>t| 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k	r| |nd}|
s||f|dd  S t|||j|jdS )a  

        Returns:

        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>   rF   )rE   r   rF   rG   )ra   r   )r   r   r   r   r   r   r   )r   Zpooler_outputr}   r   )r7   r   r   use_return_dictri   Z%warn_if_padding_and_no_attention_maskrB   r>   r1   rC   rD   Zonesrh   rI   rF   r3   Zget_extended_attention_maskZget_head_maskr   r   r   r   r   r}   r   )r6   rE   ra   r   rF   r   r   rG   r   r   r   rH   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   r:   r:   r;   rJ     sh    &



	zLiltModel.forward)T)
NNNNNNNNNN)rP   rQ   rR   r$   r   r   r   r   LILT_INPUTS_DOCSTRINGformatr   r   _CONFIG_FOR_DOCr   r1   r   r   r   r   rJ   rS   r:   r:   r8   r;   r     s:   
          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.
    c                       s   e Zd Z fddZeedeee	dd	e
ej e
ej e
ej e
ej e
ej e
ej e
ej e
ej e
e e
e e
e eeej ef dddZ  ZS )
LiltForSequenceClassificationc                    s>   t  | |j| _|| _t|dd| _t|| _|   d S NF)r   )	r#   r$   
num_labelsr7   r   r   LiltClassificationHead
classifierr   r5   r8   r:   r;   r$   J  s    
z&LiltForSequenceClassification.__init__r   r   NrE   ra   r   rF   r   r   rG   labelsr   r   r   r   c                 C   s  |dk	r|n| j j}| j||||||||	|
|d
}|d }| |}d}|dk	r<||j}| j jdk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 }|||}|sl|f|d	d  }|dk	rh|f| S |S t|||j|jd
S )a  
        labels (`torch.LongTensor` of shape `(batch_size,)`, *optional*):
            Labels for computing the sequence classification/regression loss. Indices should be in `[0, ...,
            config.num_labels - 1]`. If `config.num_labels == 1` a regression loss is computed (Mean-Square loss), If
            `config.num_labels > 1` a classification loss is computed (Cross-Entropy).

        Returns:

        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	ra   r   rF   r   r   rG   r   r   r   r   r   Z
regressionZsingle_label_classificationZmulti_label_classificationr   r^   losslogitsr}   r   )r7   r   r   r   r@   r>   Zproblem_typer   r=   r1   rD   rN   r   squeezer   rs   r   r   r}   r   r6   rE   ra   r   rF   r   r   rG   r   r   r   r   r   r   r   r   loss_fctr   r:   r:   r;   rJ   U  sX    ,



"


z%LiltForSequenceClassification.forward)NNNNNNNNNNN)rP   rQ   rR   r$   r   r   r   r   r   r   r   r1   
LongTensorr   r   r   r   r   rJ   rS   r:   r:   r8   r;   r   A  s8   	
           r   z
    Lilt Model with a token classification head on top (a linear layer on top of the hidden-states output) e.g. for
    Named-Entity-Recognition (NER) tasks.
    c                       s   e Zd Z fddZeedeee	dd	e
ej e
ej e
ej e
ej e
ej e
ej e
ej e
ej e
e e
e e
e eeej ef dddZ  ZS )
LiltForTokenClassificationc                    sb   t  | |j| _t|dd| _|jd k	r2|jn|j}t|| _	t
|j|j| _|   d S r   )r#   r$   r   r   r   classifier_dropoutr/   r   r.   r0   r\   r&   r   r   r6   r7   r   r8   r:   r;   r$     s    z#LiltForTokenClassification.__init__r   r   Nr   c                 C   s   |dk	r|n| j j}| j||||||||	|
|d
}|d }| |}| |}d}|dk	r||j}t }||d| j	|d}|s|f|dd  }|dk	r|f| S |S t
|||j|jdS )a  
        labels (`torch.LongTensor` of shape `(batch_size, sequence_length)`, *optional*):
            Labels for computing the token classification loss. Indices should be in `[0, ..., config.num_labels - 1]`.

        Returns:

        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   r^   r   )r7   r   r   r0   r   r@   r>   r   rs   r   r   r}   r   r   r:   r:   r;   rJ     s<    )

z"LiltForTokenClassification.forward)NNNNNNNNNNN)rP   rQ   rR   r$   r   r   r   r   r   r   r   r1   r   r   r   r   r   r   rJ   rS   r:   r:   r8   r;   r     s8   	
           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 k	r,|jn|j}t|| _	t|j|j
| _d S r   )r#   r$   r   r\   r&   r   r   r/   r.   r0   r   out_projr   r8   r:   r;   r$   "  s    
zLiltClassificationHead.__init__c                 K   sL   |d d dd d f }|  |}| |}t|}|  |}| |}|S r   )r0   r   r1   tanhr   )r6   featureskwargsru   r:   r:   r;   rJ   +  s    




zLiltClassificationHead.forward)rP   rQ   rR   r   r$   rJ   rS   r:   r:   r8   r;   r     s   	r   z
    Lilt Model with a span classification head on top for extractive question-answering tasks like SQuAD (a linear
    layers on top of the hidden-states output to compute `span start logits` and `span end logits`).
    c                       s   e Zd Z fddZeedeee	dd	e
ej e
ej e
ej e
ej e
ej e
ej e
ej e
ej e
ej e
e e
e e
e eeej ef dddZ  ZS )
LiltForQuestionAnsweringc                    s@   t  | |j| _t|dd| _t|j|j| _| 	  d S r   )
r#   r$   r   r   r   r   r\   r&   
qa_outputsr   r5   r8   r:   r;   r$   >  s
    z!LiltForQuestionAnswering.__init__r   r   N)rE   ra   r   rF   r   r   rG   start_positionsend_positionsr   r   r   r   c                 C   sR  |dk	r|n| j j}| j||||||||
||d
}|d }| |}|jddd\}}|d }|d }d}|dk	r
|	dk	r
t| dkr|d}t|	 dkr|	d}	|d}|	d|}|		d|}	t
|d}|||}|||	}|| d }|s<||f|dd  }|dk	r8|f| S |S t||||j|jd	S )
a  
        start_positions (`torch.LongTensor` of shape `(batch_size,)`, *optional*):
            Labels for position (index) of the start of the labelled span for computing the token classification loss.
            Positions are clamped to the length of the sequence (`sequence_length`). Position outside of the sequence
            are not taken into account for computing the loss.
        end_positions (`torch.LongTensor` of shape `(batch_size,)`, *optional*):
            Labels for position (index) of the end of the labelled span for computing the token classification loss.
            Positions are clamped to the length of the sequence (`sequence_length`). Position outside of the sequence
            are not taken into account for computing the loss.

        Returns:

        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   rK   )Zignore_indexr^   )r   start_logits
end_logitsr}   r   )r7   r   r   r   splitr   r|   r   rB   clampr   r   r}   r   )r6   rE   ra   r   rF   r   r   rG   r  r  r   r   r   r   r   r   r  r  Z
total_lossZignored_indexr   Z
start_lossZend_lossr   r:   r:   r;   rJ   H  sR    5






z LiltForQuestionAnswering.forward)NNNNNNNNNNNN)rP   rQ   rR   r$   r   r   r   r   r   r   r   r1   r   r   r   r   r   r   rJ   rS   r:   r:   r8   r;   r   5  s<   	

            r   ):r   rz   typingr   r   r   r1   Ztorch.utils.checkpointr   Ztorch.nnr   r   r   Zactivationsr
   Zmodeling_outputsr   r   r   r   r   Zmodeling_utilsr   Zpytorch_utilsr   r   r   r   r   r   r   r   Zconfiguration_liltr   Z
get_loggerrP   loggerr   Z"LILT_PRETRAINED_MODEL_ARCHIVE_LISTModuler   rT   rc   r   r   r   r   r   r   r   r   ZLILT_START_DOCSTRINGr   r   r   r   r   r   r:   r:   r:   r;   <module>   sh   
Y8 5<N!9 oa