o
    0 i.-                     @   s   d dl mZ d dlmZ d dlZd dlmZ ddlmZ ddl	m
Z
mZmZmZ ddlmZ ddlmZ dd	lmZmZmZmZ eeZG d
d dejZeG dd dZeG dd dZeG dd dZdS )    )partial)OptionalN   )Cache)BaseModelOutputWithPastQuestionAnsweringModelOutput SequenceClassifierOutputWithPastTokenClassifierOutput)	AutoModel)Unpack)TransformersKwargsauto_docstringcan_return_tupleloggingc                       s$   e Zd ZdZdZ fddZ  ZS )GradientCheckpointingLayera  Base class for layers with gradient checkpointing.

    This class enables gradient checkpointing functionality for a layer. By default, gradient checkpointing is disabled
    (`gradient_checkpointing = False`). When `model.set_gradient_checkpointing()` is called, gradient checkpointing is
    enabled by setting `gradient_checkpointing = True` and assigning a checkpointing function to `_gradient_checkpointing_func`.

    Important:

        When using gradient checkpointing with `use_reentrant=True`, inputs that require gradients (e.g. hidden states)
        must be passed as positional arguments (`*args`) rather than keyword arguments to properly propagate gradients.

        Example:

            ```python
            >>> # Correct - hidden_states passed as positional arg
            >>> out = self.layer(hidden_states, attention_mask=attention_mask)

            >>> # Incorrect - hidden_states passed as keyword arg
            >>> out = self.layer(hidden_states=hidden_states, attention_mask=attention_mask)
            ```
    Fc                    s  | j r| jrd}| jj}d| d}d|v r$|d r$d|d< |d7 }d}d|v r8|d d ur8d |d< |d7 }d}d	|v rL|d	 d urLd |d	< |d
7 }d}d|v r`|d d ur`d |d< |d7 }d}|rn|dd }t| | jtt	 j
fi |g|R  S t	 j
|i |S )NFz7Caching is incompatible with gradient checkpointing in z	. Setting	use_cachez `use_cache=False`,TZpast_key_valuez `past_key_value=None`,past_key_valuesz `past_key_values=None`,Z
layer_pastz `layer_past=None`,,.)gradient_checkpointingZtraining	__class____name__rstriploggerwarning_onceZ_gradient_checkpointing_funcr   super__call__)selfargskwargsZdo_warnZ
layer_namemessager    h/home/app/PaddleOCR-VL-test/.venv_paddleocr/lib/python3.10/site-packages/transformers/modeling_layers.pyr   <   s2   
"z#GradientCheckpointingLayer.__call__)r   
__module____qualname____doc__r   r   __classcell__r"   r"   r!   r#   r   #   s    r   c                          e Zd ZdZ fddZee							ddeej	 deej
 deej	 dee d	eej d
eej	 dee dee defddZ  ZS ) GenericForSequenceClassificationmodelc                    sJ   t  | |j| _t| | jt| tj|j	| jdd| _
|   d S )NF)Zbias)r   __init__
num_labelssetattrbase_model_prefixr
   from_confignnLinearhidden_sizescore	post_initr   configr!   r"   r#   r+   e   s
   z)GenericForSequenceClassification.__init__N	input_idsattention_maskposition_idsr   inputs_embedslabelsr   r   returnc                 K   s2  t | | j|f|||||d|}	|	j}
| |
}|d ur$|jd }n|jd }| jjd u r7|dkr7td| jjd u r@d}n1|d ure|| jjk|j	t
j}t
j|jd |j	t
jd}|| d}nd}t| jj d |t
j||j	d|f }d }|d ur| j|||| jd	}t|||	j|	j|	jd
S )Nr8   r9   r   r:   r   r   r   z=Cannot handle batch sizes > 1 if no padding token is defined.)deviceZdtypez will not detect padding tokens in `inputs_embeds`. Results may be unexpected if using padding tokens in conjunction with `inputs_embeds.`)r?   )logitsr;   pooled_logitsr6   )lossr@   r   hidden_states
attentions)getattrr.   last_hidden_stater3   shaper6   Zpad_token_id
ValueErrortor?   torchZint32ZarangeZargmaxr   r   r   r   loss_functionr   r   rC   rD   )r   r7   r8   r9   r   r:   r;   r   r   Ztransformer_outputsrC   r@   Z
batch_sizeZlast_non_pad_tokenZnon_pad_maskZtoken_indicesrA   rB   r"   r"   r#   forwardo   sN   
	

z(GenericForSequenceClassification.forwardNNNNNNN)r   r$   r%   r.   r+   r   r   r   rJ   
LongTensorTensorr   FloatTensorboolr   r   r   rL   r'   r"   r"   r!   r#   r)   a   s>    
	
r)   c                       s   e Zd ZdZ fddZdd Zdd Zee							dd	e	e
j d
e	e
j de	e
j de	e de	e
j de	e
j de	e
j dee defddZ  ZS )GenericForQuestionAnsweringr*   c                    s<   t  | t| | jt| t|jd| _	| 
  d S )N   )r   r+   r-   r.   r
   r/   r0   r1   r2   
qa_outputsr4   r5   r!   r"   r#   r+      s   z$GenericForQuestionAnswering.__init__c                 C   s   t | | jjS NrE   r.   Zembed_tokens)r   r"   r"   r#   get_input_embeddings   s   z0GenericForQuestionAnswering.get_input_embeddingsc                 C   s   |t | | j_d S rU   rV   )r   valuer"   r"   r#   set_input_embeddings   s   z0GenericForQuestionAnswering.set_input_embeddingsNr7   r8   r9   r   r:   start_positionsend_positionsr   r<   c                 K   s   t | | j|f||||d|}	|	j}
| |
}|jddd\}}|d }|d }d }|d urF|d urF| j||||fi |}t||||	j	|	j
dS )N)r8   r9   r   r:   r   r>   )dim)rB   start_logits
end_logitsrC   rD   )rE   r.   rF   rT   splitZsqueeze
contiguousrK   r   rC   rD   )r   r7   r8   r9   r   r:   rZ   r[   r   outputssequence_outputr@   r]   r^   rB   r"   r"   r#   rL      s2   
	
z#GenericForQuestionAnswering.forwardrM   )r   r$   r%   r.   r+   rW   rY   r   r   r   rJ   rN   rO   r   rP   r   r   r   rL   r'   r"   r"   r!   r#   rR      sB    		
rR   c                       r(   )GenericForTokenClassificationr*   c                    s   t  | |j| _t| | jt| t|dd d ur |j}nt|dd d ur,|j	}nd}t
|| _t
|j|j| _|   d S )Nclassifier_dropouthidden_dropoutg?)r   r+   r,   r-   r.   r
   r/   rE   rd   re   r0   ZDropoutdropoutr1   r2   r3   r4   )r   r6   rd   r!   r"   r#   r+      s   z&GenericForTokenClassification.__init__Nr7   r8   r9   r   r:   r;   r   r   r<   c                 K   sn   t | | j|f|||||d|}	|	j}
| |
}
| |
}d }|d ur-| ||| j}t|||	j|	j	dS )Nr=   )rB   r@   rC   rD   )
rE   r.   rF   rf   r3   rK   r6   r	   rC   rD   )r   r7   r8   r9   r   r:   r;   r   r   ra   rb   r@   rB   r"   r"   r#   rL      s.   
	

z%GenericForTokenClassification.forwardrM   )r   r$   r%   r.   r+   r   r   r   rJ   rN   rO   r   rP   rQ   r   r   r	   rL   r'   r"   r"   r!   r#   rc      s>    	
rc   )	functoolsr   typingr   rJ   Ztorch.nnr0   Zcache_utilsr   Zmodeling_outputsr   r   r   r	   Zmodels.autor
   Zprocessing_utilsr   utilsr   r   r   r   Z
get_loggerr   r   Moduler   r)   rR   rc   r"   r"   r"   r#   <module>   s"   
>J<