
    cCix              	          S r SSKrSSKrSSKJr  SSKJrJr  SSK	r	SSK	J
r
  SSKJr  SSKJr  SS	KJr  SS
KJrJrJr  SSKJrJrJrJr  SSKJr  \R8                  " \5      r\\" SS9 " S S\5      5       5       r\\" SS9 " S S\5      5       5       r \\" SS9 " S S\5      5       5       r!S r"S r# " S S\
RH                  5      r% " S S\
RH                  5      r& " S S\
RH                  5      r'S?S \	RP                  S!\)S"\*S#\	RP                  4S$ jjr+ " S% S&\
RH                  5      r, " S' S(\
RH                  5      r- " S) S*\
RH                  5      r. " S+ S,\
RH                  5      r/ " S- S.\
RH                  5      r0 " S/ S0\
RH                  5      r1 " S1 S2\
RH                  5      r2 " S3 S4\5      r3 " S5 S6\
RH                  5      r4\ " S7 S8\5      5       r5\ " S9 S:\55      5       r6\" S;S9 " S< S=\55      5       r7/ S>Qr8g)@zPyTorch Donut Swin Transformer model.

This implementation is identical to a regular Swin Transformer, without final layer norm on top of the final hidden
states.    N)	dataclass)OptionalUnion)nn   )ACT2FN)GradientCheckpointingLayer)PreTrainedModel) find_pruneable_heads_and_indicesmeshgridprune_linear_layer)ModelOutputauto_docstringlogging	torch_int   )DonutSwinConfigzS
    DonutSwin encoder's outputs, with potential hidden states and attentions.
    )custom_introc                       \ rS rSr% SrSr\\R                     \	S'   Sr
\\\R                  S4      \	S'   Sr\\\R                  S4      \	S'   Sr\\\R                  S4      \	S'   S	rg)
DonutSwinEncoderOutput'   a  
reshaped_hidden_states (`tuple(torch.FloatTensor)`, *optional*, returned when `output_hidden_states=True` is passed or when `config.output_hidden_states=True`):
    Tuple of `torch.FloatTensor` (one for the output of the embeddings + one for the output of each stage) of
    shape `(batch_size, hidden_size, height, width)`.

    Hidden-states of the model at the output of each layer plus the initial embedding outputs reshaped to
    include the spatial dimensions.
Nlast_hidden_state.hidden_states
attentionsreshaped_hidden_states )__name__
__module____qualname____firstlineno____doc__r   r   torchFloatTensor__annotations__r   tupler   r   __static_attributes__r       g/home/james-whalen/.local/lib/python3.13/site-packages/transformers/models/donut/modeling_donut_swin.pyr   r   '   s}     6:x 1 129=AM8E%"3"3S"89:A:>Ju00#567>FJHU5+<+<c+A%BCJr'   r   z[
    DonutSwin model's outputs that also contains a pooling of the last hidden states.
    c                       \ rS rSr% SrSr\\R                     \	S'   Sr
\\R                     \	S'   Sr\\\R                  S4      \	S'   Sr\\\R                  S4      \	S'   Sr\\\R                  S4      \	S	'   S
rg)DonutSwinModelOutput>   a  
pooler_output (`torch.FloatTensor` of shape `(batch_size, hidden_size)`, *optional*, returned when `add_pooling_layer=True` is passed):
    Average pooling of the last layer hidden-state.
reshaped_hidden_states (`tuple(torch.FloatTensor)`, *optional*, returned when `output_hidden_states=True` is passed or when `config.output_hidden_states=True`):
    Tuple of `torch.FloatTensor` (one for the output of the embeddings + one for the output of each stage) of
    shape `(batch_size, hidden_size, height, width)`.

    Hidden-states of the model at the output of each layer plus the initial embedding outputs reshaped to
    include the spatial dimensions.
Nr   pooler_output.r   r   r   r   )r   r   r   r    r!   r   r   r"   r#   r$   r,   r   r%   r   r   r&   r   r'   r(   r*   r*   >   s    	 6:x 1 12915M8E--.5=AM8E%"3"3S"89:A:>Ju00#567>FJHU5+<+<c+A%BCJr'   r*   z5
    DonutSwin outputs for image classification.
    c                       \ rS rSr% SrSr\\R                     \	S'   Sr
\\R                     \	S'   Sr\\\R                  S4      \	S'   Sr\\\R                  S4      \	S'   Sr\\\R                  S4      \	S	'   S
rg)DonutSwinImageClassifierOutputX   a  
loss (`torch.FloatTensor` of shape `(1,)`, *optional*, returned when `labels` is provided):
    Classification (or regression if config.num_labels==1) loss.
logits (`torch.FloatTensor` of shape `(batch_size, config.num_labels)`):
    Classification (or regression if config.num_labels==1) scores (before SoftMax).
reshaped_hidden_states (`tuple(torch.FloatTensor)`, *optional*, returned when `output_hidden_states=True` is passed or when `config.output_hidden_states=True`):
    Tuple of `torch.FloatTensor` (one for the output of the embeddings + one for the output of each stage) of
    shape `(batch_size, hidden_size, height, width)`.

    Hidden-states of the model at the output of each layer plus the initial embedding outputs reshaped to
    include the spatial dimensions.
Nlosslogits.r   r   r   r   )r   r   r   r    r!   r0   r   r"   r#   r$   r1   r   r%   r   r   r&   r   r'   r(   r.   r.   X   s     )-D(5$$
%,*.FHU&&'.=AM8E%"3"3S"89:A:>Ju00#567>FJHU5+<+<c+A%BCJr'   r.   c                     U R                   u  p#pEU R                  X#U-  XU-  X5      n U R                  SSSSSS5      R                  5       R                  SXU5      nU$ )z*
Partitions the given input into windows.
r   r   r            shapeviewpermute
contiguous)input_featurewindow_size
batch_sizeheightwidthnum_channelswindowss          r(   window_partitionrC   u   so     /<.A.A+J!&&k);8LkM ##Aq!Q15@@BGGKfrsGNr'   c                     U R                   S   nU R                  SX!-  X1-  XU5      n U R                  SSSSSS5      R                  5       R                  SX#U5      n U $ )z7
Merges windows to produce higher resolution features.
r6   r   r   r   r3   r4   r5   r7   )rB   r=   r?   r@   rA   s        r(   window_reverserE      se     ==$Lll2v4e6JKfrsGooaAq!Q/::<AA"fUabGNr'   c            
          ^  \ rS rSrSrSU 4S jjrS\R                  S\S\S\R                  4S jr	  SS	\
\R                     S
\
\R                     S\S\\R                     4S jjrSrU =r$ )DonutSwinEmbeddings   zO
Construct the patch and position embeddings. Optionally, also the mask token.
c                   > [         TU ]  5         [        U5      U l        U R                  R                  nU R                  R
                  U l        U(       a6  [        R                  " [        R                  " SSUR                  5      5      OS U l        UR                  (       a?  [        R                  " [        R                  " SUS-   UR                  5      5      U l        OS U l        [        R                  " UR                  5      U l        [        R"                  " UR$                  5      U l        UR(                  U l        Xl        g )Nr   )super__init__DonutSwinPatchEmbeddingspatch_embeddingsnum_patches	grid_size
patch_gridr   	Parameterr"   zeros	embed_dim
mask_tokenuse_absolute_embeddingsposition_embeddings	LayerNormnormDropouthidden_dropout_probdropout
patch_sizeconfig)selfr]   use_mask_tokenrN   	__class__s       r(   rK   DonutSwinEmbeddings.__init__   s     8 @++77//99O]",,u{{1a9I9I'JKcg))')||EKK;QR?TZTdTd4e'fD$'+D$LL!1!12	zz&"<"<= ++r'   
embeddingsr?   r@   returnc                    UR                   S   S-
  nU R                  R                   S   S-
  n[        R                  R	                  5       (       d  XE:X  a  X#:X  a  U R                  $ U R                  SS2SS24   nU R                  SS2SS24   nUR                   S   nX R
                  -  n	X0R
                  -  n
[        US-  5      nUR                  SXU5      nUR                  SSSS5      n[        R                  R                  UX4SS	S
9nUR                  SSSS5      R                  SSU5      n[        R                  " Xg4SS9$ )a  
This method allows to interpolate the pre-trained position encodings, to be able to use the model on higher resolution
images. This method is also adapted to support torch.jit tracing.

Adapted from:
- https://github.com/facebookresearch/dino/blob/de9ee3df6cf39fac952ab558447af1fa1365362a/vision_transformer.py#L174-L194, and
- https://github.com/facebookresearch/dinov2/blob/e1277af2ba9496fbadf7aec6eba56e8d882d1e35/dinov2/models/vision_transformer.py#L179-L211
r   Nr6   g      ?r   r   r3   bicubicF)sizemodealign_cornersdim)r8   rV   r"   jit
is_tracingr\   r   reshaper:   r   
functionalinterpolater9   cat)r^   rb   r?   r@   rN   num_positionsclass_pos_embedpatch_pos_embedrj   
new_height	new_widthsqrt_num_positionss               r(   interpolate_pos_encoding,DonutSwinEmbeddings.interpolate_pos_encoding   sS    !&&q)A-0066q9A= yy##%%+*F6?+++221bqb59221ab59r".
__,	&}c'9:)11!5G]`a)11!Q1=--33(	 4 
 *11!Q1=BB1b#Nyy/;CCr'   pixel_valuesbool_masked_posrw   c                    UR                   u  pEpgU R                  U5      u  pU R                  U5      nUR                  5       u  pnUbI  U R                  R                  XS5      nUR                  S5      R                  U5      nUSU-
  -  X-  -   nU R                  b*  U(       a  XR                  XU5      -   nOXR                  -   nU R                  U5      nX4$ )Nr6         ?)r8   rM   rX   rf   rT   expand	unsqueezetype_asrV   rw   r[   )r^   ry   rz   rw   _rA   r?   r@   rb   output_dimensionsr>   seq_lenmask_tokensmasks                 r(   forwardDonutSwinEmbeddings.forward   s     *6););&(,(=(=l(K%
YYz*
!+!2
Q&//00bIK",,R088ED#sTz2[5GGJ##/''*G*G
\a*bb
'*B*BB
\\*-
,,r'   )r]   r[   rT   rX   rM   rP   r\   rV   )F)NF)r   r   r   r    r!   rK   r"   Tensorintrw   r   r#   
BoolTensorboolr%   r   r&   __classcell__r`   s   @r(   rG   rG      s    &&D5<< &D &DUX &D]b]i]i &DV 7;).	-u001- "%"2"23- #'	-
 
u||	- -r'   rG   c                      ^  \ rS rSrSrU 4S jrS rS\\R                     S\
\R                  \
\   4   4S jrSrU =r$ )	rL      z
This class turns `pixel_values` of shape `(batch_size, num_channels, height, width)` into the initial
`hidden_states` (patch embeddings) of shape `(batch_size, seq_length, hidden_size)` to be consumed by a
Transformer.
c                   > [         TU ]  5         UR                  UR                  p2UR                  UR
                  pT[        U[        R                  R                  5      (       a  UOX"4n[        U[        R                  R                  5      (       a  UOX34nUS   US   -  US   US   -  -  nX l        X0l        X@l        X`l
        US   US   -  US   US   -  4U l        [        R                  " XEX3S9U l        g )Nr   r   )kernel_sizestride)rJ   rK   
image_sizer\   rA   rS   
isinstancecollectionsabcIterablerN   rO   r   Conv2d
projection)r^   r]   r   r\   rA   hidden_sizerN   r`   s          r(   rK   !DonutSwinPatchEmbeddings.__init__   s    !'!2!2F4E4EJ$*$7$79I9Ik#-j+//:R:R#S#SZZdYq
#-j+//:R:R#S#SZZdYq
!!}
15*Q-:VW=:XY$$(&$Q-:a=8*Q-:VW=:XY))L:ir'   c                 f   X0R                   S   -  S:w  aB  SU R                   S   X0R                   S   -  -
  4n[        R                  R                  X5      nX R                   S   -  S:w  aD  SSSU R                   S   X R                   S   -  -
  4n[        R                  R                  X5      nU$ )Nr   r   )r\   r   rn   pad)r^   ry   r?   r@   
pad_valuess        r(   	maybe_pad"DonutSwinPatchEmbeddings.maybe_pad   s    ??1%%*T__Q/%//!:L2LLMJ==,,\FLOOA&&!+Q4??1#5QRAS8S#STJ==,,\FLr'   ry   rc   c                     UR                   u  p#pEU R                  XU5      nU R                  U5      nUR                   u    p$nXE4nUR                  S5      R	                  SS5      nXg4$ )Nr3   r   )r8   r   r   flatten	transpose)r^   ry   r   rA   r?   r@   rb   r   s           r(   r    DonutSwinPatchEmbeddings.forward	  sp    )5););&~~lEB__\2
(..1e#O''*44Q:
,,r'   )rO   r   rA   rN   r\   r   )r   r   r   r    r!   rK   r   r   r"   r#   r%   r   r   r   r&   r   r   s   @r(   rL   rL      sK    j	-HU->->$? 	-E%,,X]^aXbJbDc 	- 	-r'   rL   c            	          ^  \ rS rSrSr\R                  4S\\   S\S\R                  SS4U 4S jjjr
S	 rS
\R                  S\\\4   S\R                  4S jrSrU =r$ )DonutSwinPatchMergingi  a  
Patch Merging Layer.

Args:
    input_resolution (`tuple[int]`):
        Resolution of input feature.
    dim (`int`):
        Number of input channels.
    norm_layer (`nn.Module`, *optional*, defaults to `nn.LayerNorm`):
        Normalization layer class.
input_resolutionrj   
norm_layerrc   Nc                    > [         TU ]  5         Xl        X l        [        R
                  " SU-  SU-  SS9U l        U" SU-  5      U l        g )Nr4   r3   Fbias)rJ   rK   r   rj   r   Linear	reductionrX   )r^   r   rj   r   r`   s       r(   rK   DonutSwinPatchMerging.__init__#  sE     01s7AG%@q3w'	r'   c                     US-  S:H  =(       d    US-  S:H  nU(       a-  SSSUS-  SUS-  4n[         R                  R                  X5      nU$ )Nr3   r   r   )r   rn   r   )r^   r<   r?   r@   
should_padr   s         r(   r   DonutSwinPatchMerging.maybe_pad*  sS    qjAo:519>
Q519a!<JMM--mHMr'   r<   input_dimensionsc                    Uu  p4UR                   u  pVnUR                  XSXG5      nU R                  XU5      nUS S 2SS S2SS S2S S 24   nUS S 2SS S2SS S2S S 24   n	US S 2SS S2SS S2S S 24   n
US S 2SS S2SS S2S S 24   n[        R                  " XX/S5      nUR                  USSU-  5      nU R                  U5      nU R                  U5      nU$ )Nr   r3   r   r6   r4   )r8   r9   r   r"   rp   rX   r   )r^   r<   r   r?   r@   r>   rj   rA   input_feature_0input_feature_1input_feature_2input_feature_3s               r(   r   DonutSwinPatchMerging.forward2  s   ((5(;(;%
%**:uS}eD'14a4Aq(89'14a4Aq(89'14a4Aq(89'14a4Aq(89		?_"fhjk%**:r1|;KL		-0}5r'   )rj   r   rX   r   )r   r   r   r    r!   r   rW   r%   r   ModulerK   r   r"   r   r   r&   r   r   s   @r(   r   r     s|    
 XZWcWc (s (# (299 (hl ( (U\\ U3PS8_ Y^YeYe  r'   r   input	drop_probtrainingrc   c                    US:X  d  U(       d  U $ SU-
  nU R                   S   4SU R                  S-
  -  -   nU[        R                  " X@R                  U R
                  S9-   nUR                  5         U R                  U5      U-  nU$ )a*  
Drop paths (Stochastic Depth) per sample (when applied in main path of residual blocks).

Comment by Ross Wightman: This is the same as the DropConnect impl I created for EfficientNet, etc networks,
however, the original name is misleading as 'Drop Connect' is a different form of dropout in a separate paper...
See discussion: https://github.com/tensorflow/tpu/issues/494#issuecomment-532968956 ... I've opted for changing the
layer and argument names to 'drop path' rather than mix DropConnect as a layer name and use 'survival rate' as the
argument.
        r   r   )r   dtypedevice)r8   ndimr"   randr   r   floor_div)r   r   r   	keep_probr8   random_tensoroutputs          r(   	drop_pathr   M  s     CxII[[^

Q 77E

5ELL YYMYYy!M1FMr'   c                      ^  \ rS rSrSrSS\\   SS4U 4S jjjrS\R                  S\R                  4S jr
S\4S	 jrS
rU =r$ )DonutSwinDropPathib  zXDrop paths (Stochastic Depth) per sample (when applied in main path of residual blocks).Nr   rc   c                 .   > [         TU ]  5         Xl        g N)rJ   rK   r   )r^   r   r`   s     r(   rK   DonutSwinDropPath.__init__e  s    "r'   r   c                 B    [        XR                  U R                  5      $ r   )r   r   r   r^   r   s     r(   r   DonutSwinDropPath.forwardi  s    FFr'   c                      SU R                    3$ )Nzp=r   r^   s    r(   
extra_reprDonutSwinDropPath.extra_reprl  s    DNN#$$r'   r   r   )r   r   r   r    r!   r   floatrK   r"   r   r   strr   r&   r   r   s   @r(   r   r   b  sQ    b#(5/ #T # #GU\\ Gell G%C % %r'   r   c                      ^  \ rS rSrU 4S jr   S
S\R                  S\\R                     S\\R                     S\\	   S\
\R                     4
S jjrS	rU =r$ )DonutSwinSelfAttentioniq  c                 
  > [         TU ]  5         X#-  S:w  a  [        SU SU S35      eX0l        [	        X#-  5      U l        U R                  U R
                  -  U l        [        U[        R                  R                  5      (       a  UOXD4U l        [        R                  " [        R                  " SU R                  S   -  S-
  SU R                  S   -  S-
  -  U5      5      U l        [        R"                  " U R                  S   5      n[        R"                  " U R                  S   5      n[        R$                  " ['        XV/SS95      n[        R(                  " US5      nUS S 2S S 2S 4   US S 2S S S 24   -
  n	U	R+                  SSS5      R-                  5       n	U	S S 2S S 2S4==   U R                  S   S-
  -  ss'   U	S S 2S S 2S4==   U R                  S   S-
  -  ss'   U	S S 2S S 2S4==   SU R                  S   -  S-
  -  ss'   U	R/                  S	5      n
U R1                  S
U
5        [        R2                  " U R                  U R                  UR4                  S9U l        [        R2                  " U R                  U R                  UR4                  S9U l        [        R2                  " U R                  U R                  UR4                  S9U l        [        R<                  " UR>                  5      U l         g )Nr   zThe hidden size (z6) is not a multiple of the number of attention heads ()r3   r   ij)indexingr6   relative_position_indexr   )!rJ   rK   
ValueErrornum_attention_headsr   attention_head_sizeall_head_sizer   r   r   r   r=   r   rQ   r"   rR   relative_position_bias_tablearangestackr   r   r:   r;   sumregister_bufferr   qkv_biasquerykeyvaluerY   attention_probs_dropout_probr[   )r^   r]   rj   	num_headsr=   coords_hcoords_wcoordscoords_flattenrelative_coordsr   r`   s              r(   rK   DonutSwinSelfAttention.__init__r  s   ?a#C5(^_h^iijk  $- #&s#7 !558P8PP%k;??3K3KLLKS^Rl 	 -/LLKKT--a0014T=M=Ma=P9PST9TUW`a-
)
 << 0 0 34<< 0 0 34Xx&:TJKvq1(At4~aqj7QQ)11!Q:EEG1a D$4$4Q$7!$;; 1a D$4$4Q$7!$;; 1a A(8(8(;$;a$?? "1"5"5b"968OPYYt1143E3EFOO\
99T//1C1C&//ZYYt1143E3EFOO\
zz&"E"EFr'   r   attention_mask	head_maskoutput_attentionsrc   c                    UR                   u  pVnXVSU R                  4nU R                  U5      R                  U5      R	                  SS5      n	U R                  U5      R                  U5      R	                  SS5      n
U R                  U5      R                  U5      R	                  SS5      n[        R                  " XR	                  SS5      5      nU[        R                  " U R                  5      -  nU R                  U R                  R                  S5         nUR                  U R                  S   U R                  S   -  U R                  S   U R                  S   -  S5      nUR                  SSS5      R                  5       nXR!                  S5      -   nUbm  UR                   S   nUR                  X^-  XR"                  Xf5      nXR!                  S5      R!                  S5      -   nUR                  SU R"                  Xf5      n[$        R&                  R)                  USS9nU R+                  U5      nUb  X-  n[        R                  " X5      nUR                  SSSS5      R                  5       nUR-                  5       S S U R.                  4-   nUR                  U5      nU(       a  UU4nU$ U4nU$ )Nr6   r   r3   r   ri   r   )r8   r   r   r9   r   r   r   r"   matmulmathsqrtr   r   r=   r:   r;   r~   r   r   rn   softmaxr[   rf   r   )r^   r   r   r   r   r>   rj   rA   hidden_shapequery_layer	key_layervalue_layerattention_scoresrelative_position_bias
mask_shapeattention_probscontext_layernew_context_layer_shapeoutputss                      r(   r   DonutSwinSelfAttention.forward  s    )6(;(;%
"T-E-EFjj/44\BLLQPQRHH]+00>HHAN	jj/44\BLLQPQR !<<5H5HR5PQ+dii8P8P.QQ!%!B!B4C_C_CdCdegCh!i!7!<!<Q$"2"21"55t7G7G7JTM]M]^_M`7`bd"
 "8!?!?1a!H!S!S!U+.N.Nq.QQ%'--a0J/44(*6N6NPS   02J2J12M2W2WXY2ZZ/44R9Q9QSV\ --//0@b/I ,,7  -9O_B%--aAq9DDF"/"4"4"6s";t?Q?Q>S"S%**+BC6G=/2 O\M]r'   )	r   r   r[   r   r   r   r   r   r=   NNF)r   r   r   r    rK   r"   r   r   r#   r   r%   r   r&   r   r   s   @r(   r   r   q  sv    #GP 7;15,16||6 !!2!236 E--.	6
 $D>6 
u||	6 6r'   r   c                   z   ^  \ rS rSrU 4S jrS\R                  S\R                  S\R                  4S jrSrU =r	$ )DonutSwinSelfOutputi  c                    > [         TU ]  5         [        R                  " X"5      U l        [        R
                  " UR                  5      U l        g r   )rJ   rK   r   r   denserY   r   r[   r^   r]   rj   r`   s      r(   rK   DonutSwinSelfOutput.__init__  s4    YYs(
zz&"E"EFr'   r   input_tensorrc   c                 J    U R                  U5      nU R                  U5      nU$ r   r  r[   )r^   r   r  s      r(   r   DonutSwinSelfOutput.forward  s$    

=1]3r'   r  
r   r   r   r    rK   r"   r   r   r&   r   r   s   @r(   r  r    s7    G
U\\  RWR^R^  r'   r  c                      ^  \ rS rSrU 4S jrS r   SS\R                  S\\R                     S\\R                     S\\
   S\\R                     4
S	 jjrS
rU =r$ )DonutSwinAttentioni  c                    > [         TU ]  5         [        XX45      U l        [	        X5      U l        [        5       U l        g r   )rJ   rK   r   r^   r  r   setpruned_heads)r^   r]   rj   r   r=   r`   s        r(   rK   DonutSwinAttention.__init__  s2    *6	O	)&6Er'   c                 6   [        U5      S:X  a  g [        XR                  R                  U R                  R                  U R
                  5      u  p[        U R                  R                  U5      U R                  l        [        U R                  R                  U5      U R                  l        [        U R                  R                  U5      U R                  l	        [        U R                  R                  USS9U R                  l        U R                  R                  [        U5      -
  U R                  l        U R                  R                  U R                  R                  -  U R                  l        U R
                  R                  U5      U l        g )Nr   r   ri   )lenr   r^   r   r   r  r   r   r   r   r   r  r   union)r^   headsindexs      r(   prune_headsDonutSwinAttention.prune_heads  s   u:?79900$))2O2OQUQbQb

 -TYY__eD		*499==%@		,TYY__eD		.t{{/@/@%QO )-		(E(EE
(R		%"&))"?"?$))B_B_"_		 --33E:r'   r   r   r   r   rc   c                 f    U R                  XX45      nU R                  US   U5      nU4USS  -   nU$ )Nr   r   )r^   r   )r^   r   r   r   r   self_outputsattention_outputr  s           r(   r   DonutSwinAttention.forward  sB     yy	];;|AF#%QR(88r'   )r   r  r^   r	  )r   r   r   r    rK   r   r"   r   r   r#   r   r%   r   r&   r   r   s   @r(   r  r    sy    ";* 7;15,1
||
 !!2!23
 E--.	

 $D>
 
u||	
 
r'   r  c                   b   ^  \ rS rSrU 4S jrS\R                  S\R                  4S jrSrU =r	$ )DonutSwinIntermediatei  c                   > [         TU ]  5         [        R                  " U[	        UR
                  U-  5      5      U l        [        UR                  [        5      (       a  [        UR                     U l        g UR                  U l        g r   )rJ   rK   r   r   r   	mlp_ratior  r   
hidden_actr   r   intermediate_act_fnr  s      r(   rK   DonutSwinIntermediate.__init__  sd    YYsC(8(83(>$?@
f''--'-f.?.?'@D$'-'8'8D$r'   r   rc   c                 J    U R                  U5      nU R                  U5      nU$ r   r  r+  r   s     r(   r   DonutSwinIntermediate.forward  s&    

=100?r'   r.  r  r   s   @r(   r'  r'    s(    9U\\ ell  r'   r'  c                   b   ^  \ rS rSrU 4S jrS\R                  S\R                  4S jrSrU =r	$ )DonutSwinOutputi  c                    > [         TU ]  5         [        R                  " [	        UR
                  U-  5      U5      U l        [        R                  " UR                  5      U l	        g r   )
rJ   rK   r   r   r   r)  r  rY   rZ   r[   r  s      r(   rK   DonutSwinOutput.__init__  sF    YYs6#3#3c#9:C@
zz&"<"<=r'   r   rc   c                 J    U R                  U5      nU R                  U5      nU$ r   r  r   s     r(   r   DonutSwinOutput.forward  s$    

=1]3r'   r  r  r   s   @r(   r1  r1    s(    >
U\\ ell  r'   r1  c                      ^  \ rS rSrSU 4S jjrS rS rS r   SS\R                  S\
\\4   S\\R                     S	\\   S
\\   S\
\R                  \R                  4   4S jjrSrU =r$ )DonutSwinLayeri#  c                   > [         TU ]  5         UR                  U l        X`l        UR                  U l        X0l        [        R                  " X!R                  S9U l	        [        XX@R                  S9U l        US:  a  [        U5      O[        R                  " 5       U l        [        R                  " X!R                  S9U l        [!        X5      U l        [%        X5      U l        g )N)eps)r=   r   )rJ   rK   chunk_size_feed_forward
shift_sizer=   r   r   rW   layer_norm_epslayernorm_beforer  	attentionr   Identityr   layernorm_afterr'  intermediater1  r   )r^   r]   rj   r   r   drop_path_rater;  r`   s          r(   rK   DonutSwinLayer.__init__$  s    '-'E'E$$!-- 0 "S6K6K L+FP`P`a>Ls>R*>:XZXcXcXe!||C5J5JK1&>%f2r'   c                    [        U5      U R                  ::  an  [        S5      U l        [        R
                  R                  5       (       a*  [        R                   " [        R                  " U5      5      O
[        U5      U l        g g Nr   )minr=   r   r;  r"   rk   rl   tensor)r^   r   s     r(   set_shift_and_window_size(DonutSwinLayer.set_shift_and_window_size1  s_     D$4$44'lDO=BYY=Q=Q=S=S		%,,'789Y\]mYn  5r'   c           	         U R                   S:  Gae  [        R                  " SXS4X4S9n[        SU R                  * 5      [        U R                  * U R                   * 5      [        U R                   * S 5      4n[        SU R                  * 5      [        U R                  * U R                   * 5      [        U R                   * S 5      4nSnU H  n	U H  n
XS S 2XS S 24'   US-  nM     M     [        XPR                  5      nUR                  SU R                  U R                  -  5      nUR                  S5      UR                  S5      -
  nUR                  US:g  S5      R                  US:H  S5      nU$ S nU$ )Nr   r   r   r6   r3   g      Yr   )	r;  r"   rR   slicer=   rC   r9   r~   masked_fill)r^   r?   r@   r   r   img_maskheight_sliceswidth_slicescountheight_slicewidth_slicemask_windows	attn_masks                r(   get_attn_maskDonutSwinLayer.get_attn_mask9  sy   ??Q{{Ava#8UHa$***+t'''$//)9:t&-M a$***+t'''$//)9:t&-L
 E -#/K@EQ1<=QJE $0 !.
 ,H6F6FGL',,R1A1ADDTDT1TUL$..q1L4J4J14MMI!--i1nfEQQR[_`R`befI  Ir'   c                     U R                   X0R                   -  -
  U R                   -  nU R                   X R                   -  -
  U R                   -  nSSSUSU4n[        R                  R                  X5      nX4$ rE  )r=   r   rn   r   )r^   r   r?   r@   	pad_right
pad_bottomr   s          r(   r   DonutSwinLayer.maybe_padU  sy    %%0@0@(@@DDTDTT	&&2B2B)BBdFVFVV
Ay!Z8
))-D((r'   r   r   r   r   always_partitionrc   c                    U(       d  U R                  U5        O Uu  pgUR                  5       u  pn
UnU R                  U5      nUR                  XXz5      nU R	                  XU5      u  pUR
                  u  ppU R                  S:  a.  [        R                  " XR                  * U R                  * 4SS9nOUn[        XR                  5      nUR                  SU R                  U R                  -  U
5      nU R                  XUR                  UR                  S9nU R                  UUX4S9nUS   nUR                  SU R                  U R                  U
5      n[        UU R                  X5      nU R                  S:  a-  [        R                  " UU R                  U R                  4SS9nOUnUS   S:  =(       d    US   S:  nU(       a  US S 2S U2S U2S S 24   R!                  5       nUR                  XU-  U
5      nXR#                  U5      -   nU R%                  U5      nU R'                  U5      nXR)                  U5      -   nU(       a	  UUS	   4nU$ U4nU$ )
Nr   )r   r3   )shiftsdimsr6   r   )r   r   r5   r   )rH  rf   r=  r9   r   r8   r;  r"   rollrC   r=   rU  r   r   r>  rE   r;   r   r@  rA  r   )r^   r   r   r   r   r[  r?   r@   r>   r   channelsshortcutr   
height_pad	width_padshifted_hidden_stateshidden_states_windowsrT  attention_outputsr$  attention_windowsshifted_windows
was_paddedlayer_outputlayer_outputss                            r(   r   DonutSwinLayer.forward\  s     **+;<("/"4"4"6
x --m<%**:uO %)NN=%$P!&3&9&9#y??Q$)JJ}FVY]YhYhXhEipv$w!$1! !11FHXHX Y 5 : :2t?O?ORVRbRb?bdl m&&)<)<EZEaEa ' 
	 !NN!9i + 
 -Q/,11"d6F6FHXHXZbc():D<L<Ljd ??Q %

?DOOUYUdUdCelr s /]Q&;*Q-!*;
 1!WfWfufa2G H S S U-22:~xX >>2C#DD++M:((6${{<'@@@Q'8';< YeWfr'   )
r>  r:  r   r   rA  r@  r=  r   r;  r=   )r   r   NFF)r   r   r   r    rK   rH  rU  r   r"   r   r%   r   r   r#   r   r   r&   r   r   s   @r(   r7  r7  #  s    38) 26,1+0A||A  S/A E--.	A
 $D>A #4.A 
u||U\\)	*A Ar'   r7  c                      ^  \ rS rSrU 4S jr   SS\R                  S\\\4   S\	\R                     S\	\   S\	\   S\\R                     4S	 jjrS
rU =r$ )DonutSwinStagei  c                 R  > [         T	U ]  5         Xl        X l        [        R
                  " [        U5       Vs/ s H+  n[        UUUUXh   US-  S:X  a  SOUR                  S-  S9PM-     sn5      U l	        Ub  U" X2[        R                  S9U l        OS U l        SU l        g s  snf )Nr3   r   )r]   rj   r   r   rB  r;  )rj   r   F)rJ   rK   r]   rj   r   
ModuleListranger7  r=   blocksrW   
downsamplepointing)
r^   r]   rj   r   depthr   r   rt  ir`   s
            r(   rK   DonutSwinStage.__init__  s    mm u
 &A !%5'#,<%&UaZqf6H6HA6M &

 !()9r||\DO"DO'
s   2B$r   r   r   r   r[  rc   c                    Uu  pg[        U R                  5       H  u  pUb  X8   OS n
U	" XXU5      nUS   nM     UnU R                  b%  US-   S-  US-   S-  pXgX4nU R                  X5      nOXgXg4nXU4nU(       a  UWSS  -  nU$ )Nr   r   r3   )	enumeraters  rt  )r^   r   r   r   r   r[  r?   r@   rw  layer_modulelayer_head_maskrk  !hidden_states_before_downsamplingheight_downsampledwidth_downsampledr   stage_outputss                    r(   r   DonutSwinStage.forward  s     )(5OA.7.CilO(UeM *!,M  6 -:)??&5;aZA4EPQ	VWGW 1!'0B V OO,M`M!' >&K\]]12..Mr'   )rs  r]   rj   rt  ru  rm  )r   r   r   r    rK   r"   r   r%   r   r   r#   r   r   r&   r   r   s   @r(   ro  ro    s    < 26,1+0||  S/ E--.	
 $D> #4. 
u||	 r'   ro  c                      ^  \ rS rSrU 4S jr      SS\R                  S\\\4   S\	\R                     S\	\   S\	\   S\	\   S	\	\   S
\	\   S\\\4   4S jjrSrU =r$ )DonutSwinEncoderi  c                   > [         TU ]  5         [        UR                  5      U l        Xl        [        R                  " SUR                  [        UR                  5      SS9 Vs/ s H  o3R                  5       PM     nn[        R                  " [        U R                  5       Vs/ s H  n[        U[        UR                   SU-  -  5      US   SU-  -  US   SU-  -  4UR                  U   UR"                  U   U[        UR                  S U 5      [        UR                  S US-    5       XPR                  S-
  :  a  [$        OS S9PM     sn5      U l        SU l        g s  snf s  snf )Nr   cpu)r   r3   r   )r]   rj   r   rv  r   r   rt  F)rJ   rK   r  depths
num_layersr]   r"   linspacerB  r   itemr   rq  rr  ro  r   rS   r   r   layersgradient_checkpointing)r^   r]   rO   xdpri_layerr`   s         r(   rK   DonutSwinEncoder.__init__  sQ   fmm,!&63H3H#fmmJ\ej!kl!kAvvx!klmm  %T__5  6G !F,,q'z9:&/lq'z&BIaLUVX_U_D`%a --0$..w7!#fmmHW&=">V]]S`U\_`U`EaAbc9@??UVCV9V4]a  6
 ',#! ms   &E&(B*E+r   r   r   r   output_hidden_states(output_hidden_states_before_downsamplingr[  return_dictrc   c	                 2   U(       a  SOS n	U(       a  SOS n
U(       a  SOS nU(       aB  UR                   u  pnUR                  " U/UQUP76 nUR                  SSSS5      nX4-  n	X4-  n
[        U R                  5       H  u  nnUb  UU   OS nU" XUXG5      nUS   nUS   nUS   nUS   US   4nU(       aS  U(       aL  UR                   u  pnUR                  " U/US   US   4QUP76 nUR                  SSSS5      nU	U4-  n	X4-  n
OPU(       aI  U(       dB  UR                   u  pnUR                  " U/UQUP76 nUR                  SSSS5      nX4-  n	X4-  n
U(       d  M  UUSS  -  nM     U(       d  [        S XU4 5       5      $ [        UU	UU
S	9$ )
Nr   r   r   r   r3   r   r6   c              3   .   #    U  H  oc  M  Uv   M     g 7fr   r   ).0vs     r(   	<genexpr>+DonutSwinEncoder.forward.<locals>.<genexpr>/  s     m$[q$[s   	)r   r   r   r   )r8   r9   r:   rz  r  r%   r   )r^   r   r   r   r   r  r  r[  r  all_hidden_statesall_reshaped_hidden_statesall_self_attentionsr>   r   r   reshaped_hidden_staterw  r{  r|  rk  r}  r   s                         r(   r   DonutSwinEncoder.forward  s$    #7BD+?RT"$5b4)6)<)<&J;$1$6$6z$bDT$bVa$b!$9$A$A!Q1$M!!11&*BB&(5OA|.7.CilO(BSM *!,M0=a0@- -a 0 1" 57H7LM#(P-N-T-T*
{ )J(N(N)"3A"68I!8L!M)OZ)% )>(E(EaAq(Q%!&G%II!*.FF*%.V-:-@-@*
{(5(:(::(fHX(fZe(f%(=(E(EaAq(Q%!%55!*.FF*  #}QR'88#A  6D m]GZ$[mmm%++*#=	
 	
r'   )r]   r  r  r  )NFFFFT)r   r   r   r    rK   r"   r   r%   r   r   r#   r   r   r   r   r&   r   r   s   @r(   r  r    s    ,4 26,1/4CH+0&*A
||A
  S/A
 E--.	A

 $D>A
 'tnA
 3;4.A
 #4.A
 d^A
 
u,,	-A
 A
r'   r  c                   8    \ rS rSr% \\S'   SrSrSrS/r	S r
Srg	)
DonutSwinPreTrainedModeli9  r]   donutry   Tro  c                 p   [        U[        R                  [        R                  45      (       ak  UR                  R
                  R                  SU R                  R                  S9  UR                  b%  UR                  R
                  R                  5         gg[        U[        R                  5      (       aJ  UR                  R
                  R                  5         UR                  R
                  R                  S5        g[        U[        5      (       ad  UR                  b$  UR                  R
                  R                  5         UR                  b%  UR                  R
                  R                  5         gg[        U[         5      (       a%  UR"                  R
                  R                  5         gg)zInitialize the weightsr   )meanstdNr|   )r   r   r   r   weightdatanormal_r]   initializer_ranger   zero_rW   fill_rG   rT   rV   r   r   )r^   modules     r(   _init_weights&DonutSwinPreTrainedModel._init_weightsB  s/   fryy"))455 MM&&CT[[5R5R&S{{&  &&( '--KK""$MM$$S) 344  ,!!&&,,.))5**//557 6 677//44::< 8r'   r   N)r   r   r   r    r   r$   base_model_prefixmain_input_namesupports_gradient_checkpointing_no_split_modulesr  r&   r   r'   r(   r  r  9  s)     $O&*#)*=r'   r  c                      ^  \ rS rSrSU 4S jjrS rS r\       SS\\	R                     S\\	R                     S\\	R                     S\\   S	\\   S
\S\\   S\\\4   4S jj5       rSrU =r$ )DonutSwinModeliV  c                   > [         TU ]  U5        Xl        [        UR                  5      U l        [        UR                  SU R
                  S-
  -  -  5      U l        [        XS9U l
        [        XR                  R                  5      U l        U(       a  [        R                  " S5      OSU l        U R#                  5         g)z
add_pooling_layer (bool, *optional*, defaults to `True`):
    Whether to add a pooling layer
use_mask_token (`bool`, *optional*, defaults to `False`):
    Whether to use a mask token for masked image modeling.
r3   r   )r_   N)rJ   rK   r]   r  r  r  r   rS   num_featuresrG   rb   r  rP   encoderr   AdaptiveAvgPool1dpooler	post_init)r^   r]   add_pooling_layerr_   r`   s       r(   rK   DonutSwinModel.__init__X  s     	 fmm, 0 0119L3M MN-fT'0J0JK1Bb**1- 	r'   c                 .    U R                   R                  $ r   )rb   rM   r   s    r(   get_input_embeddings#DonutSwinModel.get_input_embeddingsl  s    ///r'   c                     UR                  5        H7  u  p#U R                  R                  U   R                  R	                  U5        M9     g)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  layerr>  r   )r^   heads_to_pruner  r  s       r(   _prune_headsDonutSwinModel._prune_headso  s<    
 +002LELLu%//;;EB 3r'   ry   rz   r   r   r  rw   r  rc   c           	      |   Ub  UOU R                   R                  nUb  UOU R                   R                  nUb  UOU R                   R                  nUc  [	        S5      eU R                  U[        U R                   R                  5      5      nU R                  XUS9u  pU R                  UU	UUUUS9n
U
S   nSnU R                  b8  U R                  UR                  SS5      5      n[        R                  " US5      nU(       d  X4U
SS -   nU$ [        UUU
R                  U
R                   U
R"                  S9$ )	z
bool_masked_pos (`torch.BoolTensor` of shape `(batch_size, num_patches)`):
    Boolean masked positions. Indicates which patches are masked (1) and which aren't (0).
Nz You have to specify pixel_values)rz   rw   )r   r   r  r  r   r   r3   )r   r,   r   r   r   )r]   r   r  use_return_dictr   get_head_maskr  r  rb   r  r  r   r"   r   r*   r   r   r   )r^   ry   rz   r   r   r  rw   r  embedding_outputr   encoder_outputssequence_outputpooled_outputr   s                 r(   r   DonutSwinModel.forwardw  s[    2C1N-TXT_T_TqTq$8$D $++JjJj 	 &1%<k$++B]B]?@@ &&y#dkk6H6H2IJ	-1__Tl .= .
* ,,/!5# ' 
 *!,;;" KK(A(A!Q(GHM!MM-;M%58KKFM#-')77&11#2#I#I
 	
r'   )r]   rb   r  r  r  r  )TFNNNNNFN)r   r   r   r    rK   r  r  r   r   r"   r#   r   r   r   r%   r*   r   r&   r   r   s   @r(   r  r  V  s    (0C  596:15,0/3).&*=
u001=
 "%"2"23=
 E--.	=

 $D>=
 'tn=
 #'=
 d^=
 
u**	+=
 =
r'   r  a  
    DonutSwin Model transformer with an image classification head on top (a linear layer on top of the final hidden state of
    the [CLS] token) e.g. for ImageNet.

    <Tip>

        Note that it's possible to fine-tune DonutSwin on higher resolution images than the ones it has been trained on, by
        setting `interpolate_pos_encoding` to `True` in the forward of the model. This will interpolate the pre-trained
        position embeddings to the higher resolution.

    </Tip>
    c                      ^  \ rS rSrU 4S jr\       SS\\R                     S\\R                     S\\R                     S\\
   S\\
   S\
S	\\
   S
\\\4   4S jj5       rSrU =r$ )DonutSwinForImageClassificationi  c                 D  > [         TU ]  U5        UR                  U l        [        U5      U l        UR                  S:  a5  [
        R                  " U R                  R                  UR                  5      O[
        R                  " 5       U l	        U R                  5         g rE  )rJ   rK   
num_labelsr  r  r   r   r  r?  
classifierr  )r^   r]   r`   s     r(   rK   (DonutSwinForImageClassification.__init__  sx      ++#F+
 FLEVEVYZEZBIIdjj--v/@/@A`b`k`k`m 	
 	r'   ry   r   labelsr   r  rw   r  rc   c           	      Z   Ub  UOU R                   R                  nU R                  UUUUUUS9nUS   n	U R                  U	5      n
SnUb  U R	                  X:U R                   5      nU(       d  U
4USS -   nUb  U4U-   $ U$ [        UU
UR                  UR                  UR                  S9$ )ab  
labels (`torch.LongTensor` of shape `(batch_size,)`, *optional*):
    Labels for computing the image 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).
N)r   r   r  rw   r  r   r3   )r0   r1   r   r   r   )	r]   r  r  r  loss_functionr.   r   r   r   )r^   ry   r   r  r   r  rw   r  r  r  r1   r0   r   s                r(   r   'DonutSwinForImageClassification.forward  s    " &1%<k$++B]B]**/!5%=#  
  
/%%fdkkBDY,F)-)9TGf$EvE-!//))#*#A#A
 	
r'   )r  r  r  r  )r   r   r   r    rK   r   r   r"   r#   
LongTensorr   r   r%   r.   r   r&   r   r   s   @r(   r  r    s       5915-1,0/3).&*-
u001-
 E--.-
 ))*	-

 $D>-
 'tn-
 #'-
 d^-
 
u44	5-
 -
r'   r  )r  r  r  )r   F)9r!   collections.abcr   r   dataclassesr   typingr   r   r"   r   activationsr   modeling_layersr	   modeling_utilsr
   pytorch_utilsr   r   r   utilsr   r   r   r   configuration_donut_swinr   
get_loggerr   loggerr   r*   r.   rC   rE   r   rG   rL   r   r   r   r   r   r   r   r  r  r'  r1  r7  ro  r  r  r  r  __all__r   r'   r(   <module>r     sE  
   ! "   ! 9 - [ [ D D 5 
		H	% K[ K K  K; K K& K[ K K,	Y-")) Y-z(-ryy (-X3BII 3nU\\ e T V[VbVb *%		 %\RYY \@
")) 
# #NBII  	bii 	zRYY z|9/ 9zX
ryy X
v = = =6 ^
- ^
 ^
B =
&> =
=
@ \r'   