Ë
    T^(h ¯  ã                   óD  — d Z ddlZddlZddlmZmZmZ ddlZddlmZ ddl	m
Z
 ddlmZ ddlmZ dd	lmZmZ dd
lmZmZ ddlmZ ddlmZmZmZ ddlmZ  ej:                  e«      ZdZ dZ! G d„ dejD                  «      Z# G d„ dejD                  «      Z$ G d„ dejJ                  «      Z& G d„ dejJ                  «      Z' G d„ dejJ                  «      Z( G d„ de«      Z)dZ* G d„ de)«      Z+ ed e*«       G d!„ d"e)«      «       Z, ed#e*«       G d$„ d%e)e«      «       Z-d%dgZ.y)&z/PyTorch TrOCR decoder model (based on RoBERTa).é    N)ÚOptionalÚTupleÚUnion)Únn)ÚCrossEntropyLossé   )ÚACT2FN)ÚGenerationMixin)Ú_prepare_4d_attention_maskÚ!_prepare_4d_causal_attention_mask)Ú)BaseModelOutputWithPastAndCrossAttentionsÚ!CausalLMOutputWithCrossAttentions)ÚPreTrainedModel)Úadd_start_docstringsÚloggingÚreplace_return_docstringsé   )ÚTrOCRConfigr   z microsoft/trocr-base-handwrittenc                   óV   ‡ — e Zd ZdZdedefˆ fd„Zddej                  defˆ fd„Zˆ xZ	S )	ÚTrOCRLearnedPositionalEmbeddingzN
    This module learns positional embeddings up to a fixed maximum size.
    Únum_embeddingsÚembedding_dimc                 óN   •— d| _         t        ‰| �	  || j                   z   |«       y )Né   )ÚoffsetÚsuperÚ__init__)Úselfr   r   Ú	__class__s      €úf/var/www/skyplay_api_hub/venv/lib/python3.12/site-packages/transformers/models/trocr/modeling_trocr.pyr   z(TrOCRLearnedPositionalEmbedding.__init__.   s$   ø€ ð ˆŒÜ‰Ñ˜¨$¯+©+Ñ5°}ÕEó    Ú	input_idsÚpast_key_values_lengthc                 óü   •— |j                   dd \  }}t        j                  |||z   t        j                  | j                  j
                  ¬«      j                  |d«      }t        ‰| �!  || j                  z   «      S )z3`input_ids' shape is expected to be [bsz x seqlen].Nr   )ÚdtypeÚdeviceéÿÿÿÿ)
ÚshapeÚtorchÚarangeÚlongÚweightr&   Úexpandr   Úforwardr   )r   r"   r#   ÚbszÚseq_lenÚ	positionsr   s         €r    r.   z'TrOCRLearnedPositionalEmbedding.forward4   so   ø€ ð !—‘ r¨Ð*‰ˆˆWÜ—L‘LØ"Ð$:¸WÑ$DÌEÏJÉJÐ_c×_jÑ_j×_qÑ_qô
ç
‰&��b‹/ð 	ô ‰w‰˜y¨4¯;©;Ñ6Ó7Ð7r!   ©r   )
Ú__name__Ú
__module__Ú__qualname__Ú__doc__Úintr   r)   ÚTensorr.   Ú__classcell__©r   s   @r    r   r   )   s:   ø„ ñðF sð F¸3õ Fñ8 §¡ð 8Às÷ 8ñ 8r!   r   c            
       ó`   ‡ — e Zd ZdZd	dedededee   fˆ fd„Zdej                  fˆ fd„Z
ˆ xZS )
ÚTrOCRScaledWordEmbeddingz\
    This module overrides nn.Embeddings' forward by multiplying with embeddings scale.
    r   r   Úpadding_idxÚembed_scalec                 ó6   •— t         ‰| �  |||«       || _        y ©N)r   r   r>   )r   r   r   r=   r>   r   s        €r    r   z!TrOCRScaledWordEmbedding.__init__E   s   ø€ Ü‰Ñ˜¨¸ÔDØ&ˆÕr!   r"   c                 ó<   •— t         ‰| �  |«      | j                  z  S r@   )r   r.   r>   )r   r"   r   s     €r    r.   z TrOCRScaledWordEmbedding.forwardI   s   ø€ Ü‰w‰˜yÓ)¨D×,<Ñ,<Ñ<Ð<r!   )ç      ð?)r3   r4   r5   r6   r7   r   Úfloatr   r)   r8   r.   r9   r:   s   @r    r<   r<   @   sE   ø„ ññ' sð '¸3ð 'ÈSð 'Ð_gÐhmÑ_nõ 'ð= §¡÷ =ñ =r!   r<   c            	       óÞ   ‡ — e Zd ZdZddededee   fˆ fd„Zeddededee   fd„«       Z e	j                  «       dde	j                  d	efd
„«       Z	 dde	j                  ded	ee   fd„Zˆ xZS )Ú"TrOCRSinusoidalPositionalEmbeddingzDThis module produces sinusoidal positional embeddings of any length.Únum_positionsr   r=   c                 óÆ   •— t         ‰| �  «        d| _        || _        || _        | j                  |||«      | _        | j                  dt        j                  d«      «       y )Nr   Ú_float_tensorr   )
r   r   r   r   r=   Úget_embeddingÚweightsÚregister_bufferr)   ÚFloatTensor)r   rF   r   r=   r   s       €r    r   z+TrOCRSinusoidalPositionalEmbedding.__init__P   sV   ø€ Ü‰ÑÔØˆŒØ*ˆÔØ&ˆÔØ×)Ñ)¨-¸ÈÓTˆŒØ×Ñ˜_¬e×.?Ñ.?ÀÓ.BÕCr!   r   c                 óâ  — |dz  }t        j                  d«      |dz
  z  }t        j                  t        j                  |t        j
                  ¬«      j                  «       | z  «      }t        j                  | t        j
                  ¬«      j                  «       j                  d«      |j                  d«      z  }t        j                  t        j                  |«      t        j                  |«      gd¬«      j                  | d«      }|dz  dk(  r-t        j                  |t        j                  | d«      gd¬«      }|�	d||dd…f<   |j                  t        j                  «       «      S )	zÁ
        Build sinusoidal embeddings. This matches the implementation in tensor2tensor, but differs slightly from the
        description in Section 3.5 of "Attention Is All You Need".
        r   i'  r   )r%   r   ©Údimr'   N)ÚmathÚlogr)   Úexpr*   Úint64rC   Ú	unsqueezeÚcatÚsinÚcosÚviewÚzerosÚtoÚget_default_dtype)r   r   r=   Úhalf_dimÚembs        r    rI   z0TrOCRSinusoidalPositionalEmbedding.get_embeddingX   s  € ð ! AÑ%ˆÜ�h‰h�u‹o ¨A¡Ñ.ˆÜ�i‰iœŸ™ X´U·[±[ÔA×GÑGÓIÈSÈDÑPÓQˆÜ�l‰l˜>´·±Ô=×CÑCÓE×OÑOÐPQÓRÐUX×UbÑUbÐcdÓUeÑeˆÜ�i‰iœŸ™ 3›¬¯©°3«Ð8¸aÔ@×EÑEÀnÐVXÓYˆØ˜1Ñ Ò!ä—)‘)˜S¤%§+¡+¨n¸aÓ"@ÐAÀqÔIˆCØÐ"Ø"#ˆC�šQ�Ñà�v‰v”e×-Ñ-Ó/Ó0Ð0r!   r"   r#   c                 óP  — |j                  «       \  }}| j                  || j                  |«      j                  |j                  «      }| j                  dz   |z   }| j
                  �|| j
                  j                  d«      kD  r,| j                  || j                  | j                  «      | _        | j
                  j                  | j                  «      | _        | j
                  j                  d|j                  d«      «      j                  ||d«      j                  «       }|S )Nr   r   r'   )ÚsizeÚ"create_position_ids_from_input_idsr=   rZ   r&   rJ   rI   r   rH   Úindex_selectrX   Údetach)r   r"   r#   r/   r0   Úposition_idsÚmax_posÚxs           r    r.   z*TrOCRSinusoidalPositionalEmbedding.forwardk   só   € à —~‘~Ó'‰ˆˆWà×>Ñ>¸yÈ$×JZÑJZÐ\rÓs×vÑvØ×Ñó
ˆð
 ×"Ñ" QÑ&¨Ñ0ˆØ�<‰<Ð 7¨T¯\©\×->Ñ->¸qÓ-AÒ#Aà×-Ñ-¨g°t×7IÑ7IÈ4×K[ÑK[Ó\ˆDŒLØ—|‘|—‘ t×'9Ñ'9Ó:ˆŒà�L‰L×%Ñ% a¨×):Ñ):¸2Ó)>Ó?×DÑDÀSÈ'ÐSUÓV×]Ñ]Ó_ˆàˆr!   c                 ó¾   — |j                  |«      j                  «       }t        j                  |d¬«      j	                  |«      |z   |z  }|j                  «       |z   S )zÐ
        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`.
        r   rN   )Úner7   r)   ÚcumsumÚtype_asr+   )r   r"   r=   r#   ÚmaskÚincremental_indicess         r    r`   zETrOCRSinusoidalPositionalEmbedding.create_position_ids_from_input_ids~   sW   € ð �|‰|˜KÓ(×,Ñ,Ó.ˆÜ$Ÿ|™|¨D°aÔ8×@Ñ@ÀÓFÐI_Ñ_ÐcgÑgÐØ"×'Ñ'Ó)¨KÑ7Ð7r!   r@   r2   )r3   r4   r5   r6   r7   r   r   ÚstaticmethodrI   r)   Úno_gradr8   r.   r`   r9   r:   s   @r    rE   rE   M   s³   ø„ ÙNñD cð D¸#ð DÈHÐUXÉMõ Dð ñ1 cð 1¸#ð 1ÈHÐUXÉMò 1ó ð1ð$ €U‡]�]ƒ_ñ §¡ð Àsò ó ðð& bcñ
8ØŸ™ð
8Ø47ð
8ØQYÐZ]ÑQ^÷
8r!   rE   c                   ó’  ‡ — e Zd ZdZ	 	 	 	 	 	 ddededee   dee   dededed	efˆ fd
„Zde	j                  dedefd„Z	 	 	 	 	 dde	j                  dee	j                     deee	j                        dee	j                     dee	j                     dedee	j                  ee	j                     eee	j                        f   fd„Zˆ xZS )ÚTrOCRAttentionz>Multi-headed attention from 'Attention Is All You Need' paper.Ú	embed_dimÚ	num_headsÚkdimÚvdimÚdropoutÚ
is_decoderÚbiasÚis_cross_attentionc
                 óB  •— t         ‰
| �  «        || _        |�|n|| _        |�|n|| _        || _        || _        ||z  | _        | j                  |z  | j                  k(  st        d| j                  › d|› d�«      ‚| j                  dz  | _	        || _
        t        j                  | j                  ||¬«      | _        t        j                  | j                  ||¬«      | _        t        j                  |||¬«      | _        t        j                  |||¬«      | _        y )Nz;embed_dim must be divisible by num_heads (got `embed_dim`: z and `num_heads`: z).g      à¿©rv   )r   r   rp   rr   rs   rq   rt   Úhead_dimÚ
ValueErrorÚscalingru   r   ÚLinearÚk_projÚv_projÚq_projÚout_proj)r   Úconfigrp   rq   rr   rs   rt   ru   rv   rw   r   s             €r    r   zTrOCRAttention.__init__Ž   sþ   ø€ ô 	‰ÑÔØ"ˆŒØ Ð,‘D°)ˆŒ	Ø Ð,‘D°)ˆŒ	Ø"ˆŒØˆŒØ! YÑ.ˆŒØ—‘ 	Ñ)¨T¯^©^Ò;ÜØMÈdÏnÉnÐM]ð ^Ø�;˜bð"óð ð —}‘} dÑ*ˆŒØ$ˆŒä—i‘i §	¡	¨9¸4Ô@ˆŒÜ—i‘i §	¡	¨9¸4Ô@ˆŒÜ—i‘i 	¨9¸4Ô@ˆŒäŸ	™	 )¨Y¸TÔBˆ�r!   Útensorr0   r/   c                 óŽ   — |j                  ||| j                  | j                  «      j                  dd«      j	                  «       S )Nr   r   )rX   rq   rz   Ú	transposeÚ
contiguous)r   rƒ   r0   r/   s       r    Ú_shapezTrOCRAttention._shape¯   s7   € Ø�{‰{˜3 ¨¯©¸¿¹ÓG×QÑQÐRSÐUVÓW×bÑbÓdÐdr!   Úhidden_statesÚkey_value_statesÚpast_key_valueÚattention_maskÚlayer_head_maskÚoutput_attentionsÚreturnc                 óª	  — |du}|j                  «       \  }}	}
| j                  |«      | j                  z  }|r|�|d   }|d   }�n
|rE| j                  | j	                  |«      d|«      }| j                  | j                  |«      d|«      }nÃ|�}| j                  | j	                  |«      d|«      }| j                  | j                  |«      d|«      }t        j                  |d   |gd¬«      }t        j                  |d   |gd¬«      }nD| j                  | j	                  |«      d|«      }| j                  | j                  |«      d|«      }| j                  r||f}|| j                  z  d| j                  f} | j                  ||	|«      j                  |Ž } |j                  |Ž } |j                  |Ž }|j                  d«      }t        j                  ||j                  dd«      «      }|j                  «       || j                  z  |	|fk7  r/t        d|| j                  z  |	|f› d|j                  «       › �«      ‚|�{|j                  «       |d|	|fk7  r#t        d	|d|	|f› d|j                  «       › �«      ‚|j                  || j                  |	|«      |z   }|j                  || j                  z  |	|«      }t        j                   j#                  |d¬«      }|�›|j                  «       | j                  fk7  r*t        d
| j                  f› d|j                  «       › �«      ‚|j                  dddd«      |j                  || j                  |	|«      z  }|j                  || j                  z  |	|«      }|r?|j                  || j                  |	|«      }|j                  || j                  z  |	|«      }nd}t        j                   j%                  || j$                  | j&                  ¬«      }t        j                  ||«      }|j                  «       || j                  z  |	| j                  fk7  r7t        d|| j                  |	| j                  f› d|j                  «       › �«      ‚|j                  || j                  |	| j                  «      }|j                  dd«      }|j)                  ||	|
«      }| j+                  |«      }|||fS )z#Input shape: Batch x Time x ChannelNr   r   r'   r   rN   z$Attention weights should be of size z	, but is z!Attention mask should be of size z/Head mask for a single layer should be of size ©ÚpÚtrainingz `attn_output` should be of size )r_   r€   r|   r‡   r~   r   r)   rU   ru   rq   rz   rX   Úbmmr…   r{   r   Ú
functionalÚsoftmaxrt   r’   Úreshaper�   )r   rˆ   r‰   rŠ   r‹   rŒ   r�   rw   r/   Útgt_lenrp   Úquery_statesÚ
key_statesÚvalue_statesÚ
proj_shapeÚsrc_lenÚattn_weightsÚattn_weights_reshapedÚ
attn_probsÚattn_outputs                       r    r.   zTrOCRAttention.forward²   sÐ  € ð .°TÐ9ÐØ"/×"4Ñ"4Ó"6ÑˆˆW�ið —{‘{ =Ó1°D·L±LÑ@ˆá .Ð"<à'¨Ñ*ˆJØ)¨!Ñ,ŠLÙàŸ™ T§[¡[Ð1AÓ%BÀBÈÓLˆJØŸ;™; t§{¡{Ð3CÓ'DÀbÈ#ÓN‰LØÐ'àŸ™ T§[¡[°Ó%?ÀÀSÓIˆJØŸ;™; t§{¡{°=Ó'AÀ2ÀsÓKˆLÜŸ™ N°1Ñ$5°zÐ#BÈÔJˆJÜ Ÿ9™9 n°QÑ&7¸Ð%FÈAÔN‰Lð Ÿ™ T§[¡[°Ó%?ÀÀSÓIˆJØŸ;™; t§{¡{°=Ó'AÀ2ÀsÓKˆLà�?Š?ð )¨,Ð7ˆNà˜DŸN™NÑ*¨B°·±Ð>ˆ
ØC�t—{‘{ <°¸#Ó>×CÑCÀZÐPˆØ$�Z—_‘_ jÐ1ˆ
Ø(�|×(Ñ(¨*Ð5ˆà—/‘/ !Ó$ˆÜ—y‘y ¨z×/CÑ/CÀAÀqÓ/IÓJˆà×ÑÓ 3¨¯©Ñ#7¸À'Ð"JÒJÜØ6¸¸d¿n¹nÑ8LÈgÐW^Ð7_Ð6`ð aØ ×%Ñ%Ó'Ð(ð*óð ð
 Ð%Ø×"Ñ"Ó$¨¨a°¸'Ð(BÒBÜ Ø7¸¸aÀÈ'Ð8RÐ7SÐS\Ð]k×]pÑ]pÓ]rÐ\sÐtóð ð (×,Ñ,¨S°$·.±.À'È7ÓSÐVdÑdˆLØ'×,Ñ,¨S°4·>±>Ñ-AÀ7ÈGÓTˆLä—}‘}×,Ñ,¨\¸rÐ,ÓBˆàÐ&Ø×#Ñ#Ó%¨$¯.©.Ð):Ò:Ü ØEÀtÇ~Á~ÐFWÐEXð YØ'×,Ñ,Ó.Ð/ð1óð ð +×/Ñ/°°2°q¸!Ó<¸|×?PÑ?PÐQTÐVZ×VdÑVdÐfmÐovÓ?wÑwˆLØ'×,Ñ,¨S°4·>±>Ñ-AÀ7ÈGÓTˆLáð
 %1×$5Ñ$5°c¸4¿>¹>È7ÐT[Ó$\Ð!Ø0×5Ñ5°c¸D¿N¹NÑ6JÈGÐU\Ó]‰Là$(Ð!ä—]‘]×*Ñ*¨<¸4¿<¹<ÐRV×R_ÑR_Ð*Ó`ˆ
ä—i‘i 
¨LÓ9ˆà×ÑÓ #¨¯©Ñ"6¸ÀÇÁÐ!OÒOÜØ2°C¸¿¹ÈÐRV×R_ÑR_Ð3`Ð2að bØ×$Ñ$Ó&Ð'ð)óð ð
 "×&Ñ& s¨D¯N©N¸GÀTÇ]Á]ÓSˆØ!×+Ñ+¨A¨qÓ1ˆØ!×)Ñ)¨#¨w¸	ÓBˆà—m‘m KÓ0ˆàÐ1°>ÐAÐAr!   )NNç        FTF)NNNNF)r3   r4   r5   r6   r7   r   rC   Úboolr   r)   r8   r‡   r   r.   r9   r:   s   @r    ro   ro   ‹   sa  ø„ ÙHð #Ø"ØØ ØØ#(ñCð ðCð ð	Cð
 �s‰mðCð �s‰mðCð ðCð ðCð ðCð !õCðBe˜UŸ\™\ð e°Cð e¸có eð 48Ø8<Ø15Ø26Ø"'ñkBà—|‘|ðkBð # 5§<¡<Ñ0ðkBð !  u§|¡|Ñ!4Ñ5ð	kBð
 ! §¡Ñ.ðkBð " %§,¡,Ñ/ðkBð  ðkBð 
ˆu�|‰|˜X e§l¡lÑ3°X¸eÀEÇLÁLÑ>QÑ5RÐRÑ	S÷kBr!   ro   c                   ó$  ‡ — e Zd Zdefˆ fd„Z	 	 	 	 	 	 	 	 dd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ej                        d
ee	   dee	   fd„Z
ˆ xZS )ÚTrOCRDecoderLayerr‚   c           
      ó^  •— t         ‰| �  «        |j                  | _        t	        || j                  |j
                  |j                  d¬«      | _        |j                  | _        t        |j                     | _        |j                  | _        t        j                  | j                  «      | _        |j                   rnt	        || j                  |j
                  |j"                  |j"                  |j                  dd¬«      | _        t        j                  | j                  «      | _        t        j(                  | j                  |j*                  «      | _        t        j(                  |j*                  | j                  «      | _        t        j                  | j                  «      | _        y )NT)rp   rq   rt   ru   )rp   rq   rr   rs   rt   ru   rw   )r   r   Úhidden_sizerp   ro   Údecoder_attention_headsÚattention_dropoutÚ	self_attnrt   r	   Úactivation_functionÚactivation_fnÚactivation_dropoutr   Ú	LayerNormÚself_attn_layer_normru   Úcross_attention_hidden_sizeÚencoder_attnÚencoder_attn_layer_normr}   Údecoder_ffn_dimÚfc1Úfc2Úfinal_layer_norm©r   r‚   r   s     €r    r   zTrOCRDecoderLayer.__init__!  s7  ø€ Ü‰ÑÔØ×+Ñ+ˆŒä'ØØ—n‘nØ×4Ñ4Ø×,Ñ,Øô
ˆŒð —~‘~ˆŒÜ# F×$>Ñ$>Ñ?ˆÔØ"(×";Ñ";ˆÔä$&§L¡L°·±Ó$@ˆÔ!à×ÒÜ .ØØŸ.™.Ø ×8Ñ8Ø×7Ñ7Ø×7Ñ7Ø×0Ñ0ØØ#'ô	!ˆDÔô ,.¯<©<¸¿¹Ó+GˆDÔ(ä—9‘9˜TŸ^™^¨V×-CÑ-CÓDˆŒÜ—9‘9˜V×3Ñ3°T·^±^ÓDˆŒÜ "§¡¨T¯^©^Ó <ˆÕr!   rˆ   r‹   Úencoder_hidden_statesÚencoder_attention_maskrŒ   Úcross_attn_layer_head_maskrŠ   r�   Ú	use_cachec
                 ót  — |}
|�|dd nd}| j                  |||||¬«      \  }}}t        j                  j                  || j                  | j                  ¬«      }|
|z   }| j                  |«      }d}d}|�w|}
|�|dd nd}| j                  ||||||¬«      \  }}}t        j                  j                  || j                  | j                  ¬«      }|
|z   }| j                  |«      }||z   }|}
| j                  | j                  |«      «      }t        j                  j                  || j                  | j                  ¬«      }| j                  |«      }t        j                  j                  || j                  | j                  ¬«      }|
|z   }| j                  |«      }|f}|r|||fz  }|	r||fz  }|S )a  
        Args:
            hidden_states (`torch.FloatTensor`): input to the layer of shape `(batch, seq_len, embed_dim)`
            attention_mask (`torch.FloatTensor`): attention mask of size
                `(batch, 1, tgt_len, src_len)` where padding elements are indicated by very large negative values.
            encoder_hidden_states (`torch.FloatTensor`):
                cross attention input to the layer of shape `(batch, seq_len, embed_dim)`
            encoder_attention_mask (`torch.FloatTensor`): encoder attention mask of size
                `(batch, 1, tgt_len, src_len)` where padding elements are indicated by very large negative values.
            layer_head_mask (`torch.FloatTensor`): mask for attention heads in a given layer of size
                `(encoder_attention_heads,)`.
            cross_attn_layer_head_mask (`torch.FloatTensor`): mask for cross-attention heads in a given layer of
                size *(decoder_attention_heads,)*.
            past_key_value (`Tuple(torch.FloatTensor)`): cached past key and value projection states
            output_attentions (`bool`, *optional*):
                Whether or not to return the attentions tensors of all attention layers. See `attentions` under
                returned tensors for more detail.
        Nr   )rˆ   rŠ   r‹   rŒ   r�   r�   éþÿÿÿ)rˆ   r‰   r‹   rŒ   rŠ   r�   )r©   r   r”   rt   r’   r®   r°   r±   r«   r³   r¬   r´   rµ   )r   rˆ   r‹   r·   r¸   rŒ   r¹   rŠ   r�   rº   ÚresidualÚself_attn_past_key_valueÚself_attn_weightsÚpresent_key_valueÚcross_attn_present_key_valueÚcross_attn_weightsÚcross_attn_past_key_valueÚoutputss                     r    r.   zTrOCRDecoderLayer.forwardC  s  € ð< !ˆð :HÐ9S >°"°1Ñ#5ÐY]Ð à>B¿n¹nØ'Ø3Ø)Ø+Ø/ð ?Mó ?
Ñ;ˆÐ(Ð*;ô Ÿ™×-Ñ-¨m¸t¿|¹|ÐVZ×VcÑVcÐ-ÓdˆØ  =Ñ0ˆØ×1Ñ1°-Ó@ˆð (,Ð$Ø!Ðà Ð,Ø$ˆHð @NÐ?Y¨°r°sÑ(;Ð_cÐ%ØNR×N_ÑN_Ø+Ø!6Ø5Ø :Ø8Ø"3ð O`ó OÑKˆMÐ-Ð/Kô ŸM™M×1Ñ1°-À4Ç<Á<ÐZ^×ZgÑZgÐ1ÓhˆMØ$ }Ñ4ˆMØ ×8Ñ8¸ÓGˆMð !2Ð4PÑ PÐð !ˆØ×*Ñ*¨4¯8©8°MÓ+BÓCˆÜŸ™×-Ñ-¨m¸t×?VÑ?VÐae×anÑanÐ-ÓoˆØŸ™ Ó/ˆäŸ™×-Ñ-¨m¸t¿|¹|ÐVZ×VcÑVcÐ-ÓdˆØ  =Ñ0ˆØ×-Ñ-¨mÓ<ˆà Ð"ˆáØÐ)Ð+=Ð>Ñ>ˆGáØÐ)Ð+Ñ+ˆGàˆr!   )NNNNNNFT)r3   r4   r5   r   r   r)   r8   r   r   r¢   r.   r9   r:   s   @r    r¤   r¤      sØ   ø„ ð =˜{õ  =ðJ 26Ø8<Ø9=Ø26Ø=AØ8<Ø,1Ø$(ñ[à—|‘|ð[ð ! §¡Ñ.ð[ð  (¨¯©Ñ5ð	[ð
 !)¨¯©Ñ 6ð[ð " %§,¡,Ñ/ð[ð %-¨U¯\©\Ñ$:ð[ð !  u§|¡|Ñ!4Ñ5ð[ð $ D™>ð[ð ˜D‘>÷[r!   r¤   c                   ó$   — e Zd ZeZdZdZdgZd„ Zy)ÚTrOCRPreTrainedModelÚmodelTr¤   c                 ó6  — | j                   j                  }t        |t        j                  t        j
                  f«      rY|j                  j                  j                  d|¬«       |j                  �%|j                  j                  j                  «        y y t        |t        j                  «      rf|j                  j                  j                  d|¬«       |j                  �2|j                  j                  |j                     j                  «        y y y )Nr¡   )ÚmeanÚstd)r‚   Úinit_stdÚ
isinstancer   r}   ÚConv1dr,   ÚdataÚnormal_rv   Úzero_Ú	Embeddingr=   )r   ÚmodulerÊ   s      r    Ú_init_weightsz"TrOCRPreTrainedModel._init_weights§  sÌ   € Ø�k‰k×"Ñ"ˆÜ�fœrŸy™y¬"¯)©)Ð4Ô5Ø�M‰M×Ñ×&Ñ&¨C°SÐ&Ô9Ø�{‰{Ð&Ø—‘× Ñ ×&Ñ&Õ(ð 'ä˜¤§¡Ô-Ø�M‰M×Ñ×&Ñ&¨C°SÐ&Ô9Ø×!Ñ!Ð-Ø—‘×"Ñ" 6×#5Ñ#5Ñ6×<Ñ<Õ>ð .ð .r!   N)	r3   r4   r5   r   Úconfig_classÚbase_model_prefixÚsupports_gradient_checkpointingÚ_no_split_modulesrÓ   © r!   r    rÆ   rÆ   ¡  s!   „ Ø€LØÐØ&*Ð#Ø,Ð-Ðó	?r!   rÆ   aJ  
    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 ([`TrOCRConfig`]):
            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.
c                   óT   ‡ — e Zd ZdZdefˆ fd„Zd„ Zd„ Z	 	 	 	 	 	 	 	 	 	 	 	 dd„Zˆ xZ	S )ÚTrOCRDecoderz˜
    Transformer decoder consisting of *config.decoder_layers* layers. Each layer is a [`TrOCRDecoderLayer`]

    Args:
        config: TrOCRConfig
    r‚   c                 ó\  •— t         ‰| �  |«       |j                  | _        |j                  | _        |j
                  | _        |j                  rt        j                  |j                  «      nd}t        |j                  |j                  | j                  |¬«      | _        |j                  r&t        |j                   |j                  «      | _        n@t%        |j                   | j                  z   dz   |j                  | j                  «      | _        |j&                  r%t)        j*                  |j                  «      | _        nd | _        t)        j,                  t/        |j0                  «      D �cg c]  }t3        |«      ‘Œ c}«      | _        d| _        | j9                  «        y c c}w )NrB   )r>   r   F)r   r   rt   Údecoder_layerdropÚ	layerdropÚpad_token_idr=   Úscale_embeddingrP   Úsqrtr¦   r<   Ú
vocab_sizeÚembed_tokensÚuse_learned_position_embeddingsr   Úmax_position_embeddingsÚembed_positionsrE   Úlayernorm_embeddingr   r­   Ú
ModuleListÚrangeÚdecoder_layersr¤   ÚlayersÚgradient_checkpointingÚ	post_init)r   r‚   r>   Ú_r   s       €r    r   zTrOCRDecoder.__init__Ì  sK  ø€ Ü‰Ñ˜Ô Ø—~‘~ˆŒØ×1Ñ1ˆŒØ!×.Ñ.ˆÔØ7=×7MÒ7M”d—i‘i × 2Ñ 2Ô3ÐSVˆä4Ø×Ñ˜v×1Ñ1°4×3CÑ3CÐQ\ô
ˆÔð ×1Ò1Ü#BÀ6×CaÑCaÐci×cuÑcuÓ#vˆDÕ ä#EØ×.Ñ.°×1AÑ1AÑAÀAÑEØ×"Ñ"Ø× Ñ ó$ˆDÔ ð ×%Ò%Ü')§|¡|°F×4FÑ4FÓ'GˆDÕ$à'+ˆDÔ$ä—m‘mÌÈf×NcÑNcÓHdÖ$eÀ1Ô%6°vÕ%>Ò$eÓfˆŒà&+ˆÔ#à�‰Õùò	 %fs   Å3F)c                 ó   — | j                   S r@   ©râ   ©r   s    r    Úget_input_embeddingsz!TrOCRDecoder.get_input_embeddingsë  s   € Ø× Ñ Ð r!   c                 ó   — || _         y r@   rï   ©r   Úvalues     r    Úset_input_embeddingsz!TrOCRDecoder.set_input_embeddingsî  s
   € Ø!ˆÕr!   c                 ón  — |
�|
n| j                   j                  }
|�|n| j                   j                  }|	�|	n| j                   j                  }	|�|n| j                   j                  }|�|�t        d«      ‚|�"|}|j                  d|j                  d   «      }n-|� |j                  «       dd }|dd…dd…df   }nt        d«      ‚|�|d   d   j                  d   nd}|€| j                  |«      }| j                   j                  r| j                  ||¬«      }n| j                  ||¬«      }||z   }| j                  �| j                  |«      }t        j                  j                  || j                  | j                   ¬«      }|j                  }t#        ||||«      }|�|�t%        ||j&                  |d   ¬	«      }| j(                  r%| j                   r|	rt*        j-                  d
«       d}	|rdnd}|
rdnd}|
r|�dnd}|	rdnd}t/        ||gddg«      D ]j  \  }}|€Œ	|j                  «       d   t1        | j2                  «      k7  sŒ3t        d|› dt1        | j2                  «      › d|j                  «       d   › d�«      ‚ t5        | j2                  «      D ]Ý  \  }}|r||fz  }| j                   r%t7        j8                  g «      }|| j:                  k  rŒ?|�||   nd}| j(                  r?| j                   r3| j=                  |j>                  |||||�||   nd|�||   ndd|
|	«
      }n ||||||�||   nd|�||   nd||
|	¬«	      }|d   }|	r|||
rdnd   fz  }|
sŒÉ||d   fz  }|€ŒÕ||d   fz  }Œß |r||fz  }|	r|nd}|stA        d„ |||||fD «       «      S tC        |||||¬«      S )a  
        Args:
            input_ids (`torch.LongTensor` of shape `(batch_size, sequence_length)`):
                Indices of input sequence tokens in the vocabulary. Padding will be ignored by default should you
                provide it.

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

                [What are input IDs?](../glossary#input-ids)
            attention_mask (`torch.Tensor` of shape `(batch_size, sequence_length)`, *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)
            encoder_hidden_states (`torch.FloatTensor` of shape `(batch_size, encoder_sequence_length, hidden_size)`, *optional*):
                Sequence of hidden-states at the output of the last layer of the encoder. Used in the cross-attention
                of the decoder.
            encoder_attention_mask (`torch.LongTensor` of shape `(batch_size, encoder_sequence_length)`, *optional*):
                Mask to avoid performing cross-attention on padding tokens indices of encoder input_ids. 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)
            head_mask (`torch.Tensor` of shape `(decoder_layers, decoder_attention_heads)`, *optional*):
                Mask to nullify selected heads of the attention modules. Mask values selected in `[0, 1]`:

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

            cross_attn_head_mask (`torch.Tensor` of shape `(decoder_layers, decoder_attention_heads)`, *optional*):
                Mask to nullify selected heads of the attention modules in encoder to avoid performing cross-attention
                on hidden heads. Mask values selected in `[0, 1]`:

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

            past_key_values (`tuple(tuple(torch.FloatTensor))`, *optional*, returned when `use_cache=True` is passed or when `config.use_cache=True`):
                Tuple of `tuple(torch.FloatTensor)` of length `config.n_layers`, with each tuple having 2 tensors of
                shape `(batch_size, num_heads, sequence_length, embed_size_per_head)`) and 2 additional tensors of
                shape `(batch_size, num_heads, encoder_sequence_length, embed_size_per_head)`.

                Contains pre-computed hidden-states (key and values in the self-attention blocks and in the
                cross-attention blocks) that can be used (see `past_key_values` input) to speed up sequential decoding.

                If `past_key_values` are used, the user can optionally input only the last `decoder_input_ids` (those
                that don't have their past key value states given to this model) of shape `(batch_size, 1)` instead of
                all `decoder_input_ids` of shape `(batch_size, sequence_length)`.
            inputs_embeds (`torch.FloatTensor` of shape `(batch_size, sequence_length, 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.
        NzTYou cannot specify both decoder_input_ids and decoder_inputs_embeds at the same timer'   zEYou have to specify either decoder_input_ids or decoder_inputs_embedsr   r   )r#   r�   )r—   z^`use_cache = True` is incompatible with gradient checkpointing. Setting `use_cache = False`...FrØ   Ú	head_maskÚcross_attn_head_maskzThe `z` should be specified for z layers, but it is for ú.)r‹   r·   r¸   rŒ   r¹   rŠ   r�   rº   r   r   c              3   ó$   K  — | ]  }|�|–— Œ
 y ­wr@   rØ   )Ú.0Úvs     r    ú	<genexpr>z'TrOCRDecoder.forward.<locals>.<genexpr>¿  s   è ø€ ò àØ�=ô ñùs   ‚)Úlast_hidden_stateÚpast_key_valuesrˆ   Ú
attentionsÚcross_attentions)"r‚   r�   Úoutput_hidden_statesrº   Úuse_return_dictr{   rX   r(   r_   râ   rã   rå   ræ   r   r”   rt   r’   r   r   r%   rë   ÚloggerÚwarning_onceÚzipÚlenrê   Ú	enumerater)   ÚrandrÝ   Ú_gradient_checkpointing_funcÚ__call__Útupler   )r   r"   r‹   r·   r¸   r÷   rø   rÿ   Úinputs_embedsrº   r�   r  Úreturn_dictÚinputÚinput_shaper#   Ú	embed_posrˆ   Úall_hidden_statesÚall_self_attnsÚall_cross_attentionsÚnext_decoder_cacheÚ	attn_maskÚ	mask_nameÚidxÚdecoder_layerÚdropout_probabilityrŠ   Úlayer_outputsÚ
next_caches                                 r    r.   zTrOCRDecoder.forwardñ  s”  € ð` 2CÐ1NÑ-ÐTX×T_ÑT_×TqÑTqÐà$8Ð$DÑ È$Ï+É+×JjÑJjð 	ð "+Ð!6‘I¸D¿K¹K×<QÑ<Qˆ	Ø%0Ð%<‘kÀ$Ç+Á+×B]ÑB]ˆð Ð  ]Ð%>ÜÐsÓtÐtØÐ"ØˆEØ!Ÿ™ r¨5¯;©;°r©?Ó;‰IØÐ&Ø'×,Ñ,Ó.¨s°Ð3ˆKØ!¢!¢Q¨ (Ñ+‰EäÐdÓeÐeð DSÐC^ °Ñ!3°AÑ!6×!<Ñ!<¸QÒ!?ÐdeÐàÐ Ø ×-Ñ-¨iÓ8ˆMà�;‰;×6Ò6Ø×,Ñ,¨UÐKaÐ,Ób‰Ià×,Ñ,¨YÐOeÐ,ÓfˆIà%¨	Ñ1ˆà×#Ñ#Ð/Ø ×4Ñ4°]ÓCˆMäŸ™×-Ñ-¨m¸t¿|¹|ÐVZ×VcÑVcÐ-Ódˆà—k‘kˆä:Ø˜K¨Ð8Nó
ˆð
 !Ð,Ð1GÐ1Sä%?Ø&¨×(;Ñ(;À[ÐQSÁ_ô&Ð"ð ×&Ò&¨4¯=ª=ÙÜ×#Ñ#Øtôð "�	ñ #7™B¸DÐÙ0™°dˆÙ&7Ð<QÐ<]™rÐdhÐÙ#,™R°$Ðô %(¨Ð4HÐ(IÈKÐYoÐKpÓ$qò 	Ñ ˆI�yØÑ$Ø—>‘>Ó# AÑ&¬3¨t¯{©{Ó+;Ó<Ü$Ø 	˜{Ð*DÄSÈÏÉÓEUÐDVð WØ%ŸN™NÓ,¨QÑ/Ð0°ð3óð ð	ô #,¨D¯K©KÓ"8ò /	@ÑˆC�á#Ø! mÐ%5Ñ5Ð!Ø�}Š}Ü&+§j¡j°£nÐ#Ø&¨¯©Ò7Øà5DÐ5P˜_¨SÒ1ÐVZˆNà×*Ò*¨t¯}ª}Ø $× AÑ AØ!×*Ñ*Ø!Ø"Ø)Ø*Ø&/Ð&;�I˜c’NÀØ1EÐ1QÐ(¨Ò-ÐW[ØØ%Øó!‘ñ !.Ø!Ø#1Ø*?Ø+AØ7@Ð7L Y¨s¢^ÐRVà5IÐ5UÐ,¨SÒ1Ð[_à#1Ø&7Ø'ô!�ð *¨!Ñ,ˆMáØ" }Ñ:K±QÐQRÑ'SÐ&UÑUÐ"â Ø =°Ñ#3Ð"5Ñ5�à(Ñ4Ø(¨]¸1Ñ-=Ð,?Ñ?Ñ(ð_/	@ñd  Ø -Ð!1Ñ1Ðá+4Ñ'¸$ˆ
ÙÜñ à'¨Ð5FÈÐXlÐmôó ð ô
 9Ø+Ø&Ø+Ø%Ø1ô
ð 	
r!   )NNNNNNNNNNNN)
r3   r4   r5   r6   r   r   rñ   rõ   r.   r9   r:   s   @r    rÚ   rÚ   Ä  sJ   ø„ ñð˜{õ ò>!ò"ð
 ØØ"Ø#ØØ!ØØØØØ!Ø÷Y
r!   rÚ   zMThe TrOCR Model with a language modeling head. Can be used for summarization.c                   ó(   ‡ — e Zd ZdZˆ fd„Zd„ Zˆ xZS )ÚTrOCRDecoderWrapperz½
    This wrapper class is a helper class to correctly load pretrained checkpoints when the causal language model is
    used in combination with the [`EncoderDecoderModel`] framework.
    c                 óD   •— t         ‰| �  |«       t        |«      | _        y r@   )r   r   rÚ   Údecoderr¶   s     €r    r   zTrOCRDecoderWrapper.__init__×  s   ø€ Ü‰Ñ˜Ô Ü# FÓ+ˆ�r!   c                 ó&   —  | j                   |i |¤ŽS r@   )r   )r   ÚargsÚkwargss      r    r.   zTrOCRDecoderWrapper.forwardÛ  s   € Øˆt�|‰|˜TÐ, VÑ,Ð,r!   )r3   r4   r5   r6   r   r.   r9   r:   s   @r    r  r  Í  s   ø„ ñ
ô
,ö-r!   r  z‰The TrOCR Decoder with a language modeling head. Can be used as the decoder part of [`EncoderDecoderModel`] and [`VisionEncoderDecoder`].c                    óæ  ‡ — e Zd ZdgZˆ fd„Zd„ Zd„ Zd„ Zd„ Zd„ Z	d„ Z
 ee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eej$                           deej$                     deej                      dee   dee   dee   dee   deeef   fd„«       Zed„ «       Zˆ xZS )ÚTrOCRForCausalLMzoutput_projection.weightc                 ó  •— t        j                  |«      }d|_        d|_        t        ‰| �  |«       t        |«      | _        t        j                  |j                  |j                  d¬«      | _        | j                  «        y )NTFry   )ÚcopyÚdeepcopyru   Úis_encoder_decoderr   r   r  rÇ   r   r}   r¦   rá   Úoutput_projectionrì   r¶   s     €r    r   zTrOCRForCausalLM.__init__ç  sh   ø€ Ü—‘˜vÓ&ˆØ ˆÔØ$)ˆÔ!Ü‰Ñ˜Ô Ü(¨Ó0ˆŒ
ä!#§¡¨6×+=Ñ+=¸v×?PÑ?PÐW\Ô!]ˆÔð 	�‰Õr!   c                 óB   — | j                   j                  j                  S r@   ©rÇ   r   râ   rð   s    r    rñ   z%TrOCRForCausalLM.get_input_embeddingsó  s   € Ø�z‰z×!Ñ!×.Ñ.Ð.r!   c                 ó:   — || j                   j                  _        y r@   r,  ró   s     r    rõ   z%TrOCRForCausalLM.set_input_embeddingsö  s   € Ø*/ˆ�
‰
×ÑÕ'r!   c                 ó   — | j                   S r@   ©r*  rð   s    r    Úget_output_embeddingsz&TrOCRForCausalLM.get_output_embeddingsù  s   € Ø×%Ñ%Ð%r!   c                 ó   — || _         y r@   r/  )r   Únew_embeddingss     r    Úset_output_embeddingsz&TrOCRForCausalLM.set_output_embeddingsü  s
   € Ø!/ˆÕr!   c                 ó&   — || j                   _        y r@   ©rÇ   r   )r   r   s     r    Úset_decoderzTrOCRForCausalLM.set_decoderÿ  s   € Ø$ˆ�
‰
Õr!   c                 ó.   — | j                   j                  S r@   r5  rð   s    r    Úget_decoderzTrOCRForCausalLM.get_decoder  s   € Ø�z‰z×!Ñ!Ð!r!   )Úoutput_typerÔ   r"   r‹   r·   r¸   r÷   rø   rÿ   r  Úlabelsrº   r�   r  r  rŽ   c                 óD  — |�|n| j                   j                  }|�|n| j                   j                  }|�|n| j                   j                  }| j                  j                  |||||||||
|||¬«      }| j                  |d   «      }d}|	�Ft        «       } ||j                  d| j                   j                  «      |	j                  d«      «      }|s|f|dd z   }|�|f|z   S |S t        |||j                  |j                  |j                  |j                  ¬«      S )aO  
        Args:
            input_ids (`torch.LongTensor` of shape `(batch_size, sequence_length)`):
                Indices of input sequence tokens in the vocabulary. Padding will be ignored by default should you
                provide it.

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

                [What are input IDs?](../glossary#input-ids)
            attention_mask (`torch.Tensor` of shape `(batch_size, sequence_length)`, *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)
            encoder_hidden_states  (`torch.FloatTensor` of shape `(batch_size, sequence_length, hidden_size)`, *optional*):
                Sequence of hidden-states at the output of the last layer of the encoder. Used in the cross-attention
                if the model is configured as a decoder.
            encoder_attention_mask (`torch.FloatTensor` of shape `(batch_size, sequence_length)`, *optional*):
                Mask to avoid performing attention on the padding token indices of the encoder input. This mask is used
                in the cross-attention if the model is configured as a decoder. Mask values selected in `[0, 1]`:
            head_mask (`torch.Tensor` of shape `(decoder_layers, decoder_attention_heads)`, *optional*):
                Mask to nullify selected heads of the attention modules. Mask values selected in `[0, 1]`:

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

            cross_attn_head_mask (`torch.Tensor` of shape `(decoder_layers, decoder_attention_heads)`, *optional*):
                Mask to nullify selected heads of the cross-attention modules. Mask values selected in `[0, 1]`:

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

            past_key_values (`tuple(tuple(torch.FloatTensor))`, *optional*, returned when `use_cache=True` is passed or when `config.use_cache=True`):
                Tuple of `tuple(torch.FloatTensor)` of length `config.n_layers`, with each tuple having 2 tensors of
                shape `(batch_size, num_heads, sequence_length, embed_size_per_head)`) and 2 additional tensors of
                shape `(batch_size, num_heads, encoder_sequence_length, embed_size_per_head)`. The two additional
                tensors are only required when the model is used as a decoder in a Sequence to Sequence model.

                Contains pre-computed hidden-states (key and values in the self-attention blocks and in the
                cross-attention blocks) that can be used (see `past_key_values` input) to speed up sequential decoding.

                If `past_key_values` are used, the user can optionally input only the last `decoder_input_ids` (those
                that don't have their past key value states given to this model) of shape `(batch_size, 1)` instead of
                all `decoder_input_ids` of shape `(batch_size, sequence_length)`.
            labels (`torch.LongTensor` of shape `(batch_size, sequence_length)`, *optional*):
                Labels for computing the masked language modeling loss. Indices should either be in `[0, ...,
                config.vocab_size]` or -100 (see `input_ids` docstring). Tokens with indices set to `-100` are ignored
                (masked), the loss is only computed for the tokens with labels in `[0, ..., config.vocab_size]`.
            use_cache (`bool`, *optional*):
                If set to `True`, `past_key_values` key value states are returned and can be used to speed up decoding
                (see `past_key_values`).

                - 1 for tokens that are **not masked**,
                - 0 for tokens that are **masked**.
            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.

        Returns:

        Example:

        ```python
        >>> from transformers import (
        ...     TrOCRConfig,
        ...     TrOCRProcessor,
        ...     TrOCRForCausalLM,
        ...     ViTConfig,
        ...     ViTModel,
        ...     VisionEncoderDecoderModel,
        ... )
        >>> import requests
        >>> from PIL import Image

        >>> # TrOCR is a decoder model and should be used within a VisionEncoderDecoderModel
        >>> # init vision2text model with random weights
        >>> encoder = ViTModel(ViTConfig())
        >>> decoder = TrOCRForCausalLM(TrOCRConfig())
        >>> model = VisionEncoderDecoderModel(encoder=encoder, decoder=decoder)

        >>> # If you want to start from the pretrained model, load the checkpoint with `VisionEncoderDecoderModel`
        >>> processor = TrOCRProcessor.from_pretrained("microsoft/trocr-base-handwritten")
        >>> model = VisionEncoderDecoderModel.from_pretrained("microsoft/trocr-base-handwritten")

        >>> # load image from the IAM dataset
        >>> url = "https://fki.tic.heia-fr.ch/static/img/a01-122-02.jpg"
        >>> image = Image.open(requests.get(url, stream=True).raw).convert("RGB")
        >>> pixel_values = processor(image, return_tensors="pt").pixel_values
        >>> text = "industry, ' Mr. Brown commented icily. ' Let us have a"

        >>> # training
        >>> model.config.decoder_start_token_id = processor.tokenizer.eos_token_id
        >>> model.config.pad_token_id = processor.tokenizer.pad_token_id
        >>> model.config.vocab_size = model.config.decoder.vocab_size

        >>> labels = processor.tokenizer(text, return_tensors="pt").input_ids
        >>> outputs = model(pixel_values, labels=labels)
        >>> loss = outputs.loss
        >>> round(loss.item(), 2)
        5.30

        >>> # inference
        >>> generated_ids = model.generate(pixel_values)
        >>> generated_text = processor.batch_decode(generated_ids, skip_special_tokens=True)[0]
        >>> generated_text
        'industry, " Mr. Brown commented icily. " Let us have a'
        ```N)r"   r‹   r·   r¸   r÷   rø   rÿ   r  rº   r�   r  r  r   r'   r   )ÚlossÚlogitsrÿ   rˆ   r   r  )r‚   r�   r  r  rÇ   r   r*  r   rX   rá   r   rÿ   rˆ   r   r  )r   r"   r‹   r·   r¸   r÷   rø   rÿ   r  r:  rº   r�   r  r  rÄ   r=  r<  Úloss_fctÚoutputs                      r    r.   zTrOCRForCausalLM.forward  sH  € ðJ 2CÐ1NÑ-ÐTX×T_ÑT_×TqÑTqÐà$8Ð$DÑ È$Ï+É+×JjÑJjð 	ð &1Ð%<‘kÀ$Ç+Á+×B]ÑB]ˆð —*‘*×$Ñ$ØØ)Ø"7Ø#9ØØ!5Ø+Ø'ØØ/Ø!5Ø#ð %ó 
ˆð ×'Ñ'¨°©
Ó3ˆàˆØÐÜ'Ó)ˆHÙ˜FŸK™K¨¨D¯K©K×,BÑ,BÓCÀVÇ[Á[ÐQSÃ_ÓUˆDáØ�Y ¨¨ Ñ,ˆFØ'+Ð'7�D�7˜VÑ#ÐC¸VÐCä0ØØØ#×3Ñ3Ø!×/Ñ/Ø×)Ñ)Ø$×5Ñ5ô
ð 	
r!   c                 óJ   ‡— d}| D ]  }|t        ˆfd„|D «       «      fz  }Œ |S )NrØ   c              3   ót   •K  — | ]/  }|j                  d ‰j                  |j                  «      «      –— Œ1 y­w)r   N)ra   rZ   r&   )rû   Ú
past_stateÚbeam_idxs     €r    rý   z2TrOCRForCausalLM._reorder_cache.<locals>.<genexpr>¹  s.   øè ø€ ÒnÐU_�j×-Ñ-¨a°·±¸Z×=NÑ=NÓ1O×PÑnùs   ƒ58)r  )rÿ   rC  Úreordered_pastÚ
layer_pasts    `  r    Ú_reorder_cachezTrOCRForCausalLM._reorder_cache´  s=   ø€ àˆØ)ò 	ˆJØÜÓnÐcmÔnÓnðñ ‰Nð	ð Ðr!   )NNNNNNNNNNNNN)r3   r4   r5   Ú_tied_weights_keysr   rñ   rõ   r0  r3  r6  r8  r   r   Ú_CONFIG_FOR_DOCr   r)   Ú
LongTensorr8   rL   r   r¢   r   r.   rl   rF  r9   r:   s   @r    r%  r%  ß  s©  ø„ ð 5Ð5Ðô
ò/ò0ò&ò0ò%ò"ñ Ð+LÐ[jÔkð 15Ø15Ø=AØ=AØ,0Ø7;ØEIØ59Ø-1Ø$(Ø,0Ø/3Ø&*ñl
à˜E×,Ñ,Ñ-ðl
ð ! §¡Ñ.ðl
ð  (¨×(9Ñ(9Ñ:ð	l
ð
 !)¨×)9Ñ)9Ñ :ðl
ð ˜EŸL™LÑ)ðl
ð ' u§|¡|Ñ4ðl
ð " %¨¨e×.?Ñ.?Ñ(@Ñ"AÑBðl
ð   × 1Ñ 1Ñ2ðl
ð ˜×)Ñ)Ñ*ðl
ð ˜D‘>ðl
ð $ D™>ðl
ð ' t™nðl
ð ˜d‘^ðl
ð 
ˆuÐ7Ð7Ñ	8òl
ó lðl
ð\ ñó ôr!   r%  )/r6   r'  rP   Útypingr   r   r   r)   r   Útorch.nnr   Úactivationsr	   Ú
generationr
   Úmodeling_attn_mask_utilsr   r   Úmodeling_outputsr   r   Úmodeling_utilsr   Úutilsr   r   r   Úconfiguration_trocrr   Ú
get_loggerr3   r  rH  Ú_CHECKPOINT_FOR_DOCrÑ   r   r<   ÚModulerE   ro   r¤   rÆ   ÚTROCR_START_DOCSTRINGrÚ   r  r%  Ú__all__rØ   r!   r    ú<module>rX     s6  ðñ 6ã Û ß )Ñ )ã Ý Ý %å !Ý )ß eß lÝ -ß MÑ MÝ ,ð 
ˆ×	Ñ	˜HÓ	%€à€Ø8Ð ô8 b§l¡lô 8ô.
=˜rŸ|™|ô 
=ô;8¨¯©ô ;8ô|RB�R—Y‘Yô RBôj~˜Ÿ	™	ô ~ôB?˜?ô ?ð$Ð ô"F
Ð'ô F
ñR ØSØóô-Ð.ó -ó	ð-ñ ð!àóô
WÐ+¨_ó Wóð
Wðt Ð5Ð
6�r!   