
    ^j	                     (   d Z ddlZddlZddlmZ ddlmZ ddlZddlmZ ddl	m
Z ddlmZ dd	lmZm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mZmZmZ ddlm Z m!Z! ddl"m#Z#m$Z$ ddl%m&Z&m'Z'm(Z(m)Z)m*Z*m+Z+ ddl,m-Z-  ej\                  e/      Z0 G d dejb                        Z2 ed      e G d de                    Z3 ed      e G d de                    Z4 ed      e G d d e                    Z5 ed!      e G d" d#e                    Z6d$ Z7d% Z8 G d& d'ejb                        Z9 G d( d)ejb                        Z: G d* d+ejb                        Z; G d, d-ejb                        Z< G d. d/e'      Z= G d0 d1e)      Z> G d2 d3e(      Z? G d4 d5e      Z@e G d6 d7e*             ZA G d8 d9eA      ZBe G d: d;eA             ZC ed<       G d= d>eA             ZD ed?       G d@ dAeA             ZE edB       G dC dDeeA             ZFg dEZGy)FzPyTorch Swin Transformer model.    N)Callable)	dataclass)nn   )initialization)ACT2FN)BackboneMixinfilter_output_hidden_states)GradientCheckpointingLayer)BackboneOutput)ALL_ATTENTION_FUNCTIONS)Unpack)ModelOutputTransformersKwargsauto_docstringlogging	torch_int)can_return_tuplemerge_with_config_defaults)OutputRecordercapture_outputs   )PreTrainedModelViTAttentionViTLayerViTMLPViTPreTrainedModeleager_attention_forward   )
SwinConfigc                   r     e Zd ZdZd	deddf fdZdej                  dej                  fdZde	fdZ
 xZS )
SwinDropPathzStochastic depth (DropPath) per sample, for residual blocks.

    Identity when ``drop_prob`` is 0 or outside training. See `Deep Networks with Stochastic Depth
    <https://arxiv.org/abs/1603.09382>`_.
    	drop_probreturnNc                 0    t         |           || _        y N)super__init__r#   )selfr#   	__class__s     p/var/www/ramen.bs-engineer-server.com/venv/lib/python3.12/site-packages/transformers/models/swin/modular_swin.pyr(   zSwinDropPath.__init__7   s    "    hidden_statesc                 P   | j                   dk(  s| j                  s|S d| j                   z
  }|j                  d   fd|j                  dz
  z  z   }t	        j
                  ||j                  |j                        }t	        j                  ||z         }|j                  |      |z  S )N        r   r   )r   dtypedevice)
r#   trainingshapendimtorchrandr1   r2   floordiv)r)   r-   	keep_probr4   random_tensors        r+   forwardzSwinDropPath.forward;   s    >>S   &	$$Q')DM4F4F4J,KK

50C0CML`L`aMI$=>  +m;;r,   c                      d| j                    S )Nzp=)r#   )r)   s    r+   
extra_reprzSwinDropPath.extra_reprD   s    DNN#$$r,   )r/   )__name__
__module____qualname____doc__floatr(   r6   Tensorr<   strr>   __classcell__r*   s   @r+   r"   r"   0   sB    #% #$ #<U\\ <ell <%C %r,   r"   zN
    Swin encoder's outputs, with potential hidden states and attentions.
    )custom_introc                       e Zd ZU dZdZej                  dz  ed<   dZe	ej                  df   dz  ed<   dZ
e	ej                  df   dz  ed<   dZe	ej                  df   dz  ed<   y)SwinEncoderOutputa  
    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.r-   
attentionsreshaped_hidden_states)r?   r@   rA   rB   rK   r6   FloatTensor__annotations__r-   tuplerL   rM    r,   r+   rJ   rJ   H   s}     37u((4/6:>M5**C/047>7;Je'',-4;CGE%"3"3S"89D@Gr,   rJ   zV
    Swin model's outputs that also contains a pooling of the last hidden states.
    c                       e Zd ZU dZdZej                  dz  ed<   dZej                  dz  ed<   dZ	e
ej                  df   dz  ed<   dZe
ej                  df   dz  ed<   dZe
ej                  df   dz  ed<   y)	SwinModelOutputa  
    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.
    NrK   pooler_output.r-   rL   rM   )r?   r@   rA   rB   rK   r6   rN   rO   rT   r-   rP   rL   rM   rQ   r,   r+   rS   rS   ^   s    	 37u((4/6.2M5$$t+2:>M5**C/047>7;Je'',-4;CGE%"3"3S"89D@Gr,   rS   z*
    Swin masked image model outputs.
    c                       e Zd ZU dZdZej                  dz  ed<   dZej                  dz  ed<   dZ	e
ej                  df   dz  ed<   dZe
ej                  df   dz  ed<   dZe
ej                  df   dz  ed<   y)	SwinMaskedImageModelingOutputa  
    loss (`torch.FloatTensor` of shape `(1,)`, *optional*, returned when `bool_masked_pos` is provided):
        Masked image modeling (MLM) loss.
    reconstruction (`torch.FloatTensor` of shape `(batch_size, num_channels, height, width)`):
        Reconstructed pixel values.
    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reconstruction.r-   rL   rM   )r?   r@   rA   rB   rW   r6   rN   rO   rX   r-   rP   rL   rM   rQ   r,   r+   rV   rV   w   s     &*D%

d
")/3NE%%,3:>M5**C/047>7;Je'',-4;CGE%"3"3S"89D@Gr,   rV   z0
    Swin outputs for image classification.
    c                       e Zd ZU dZdZej                  dz  ed<   dZej                  dz  ed<   dZ	e
ej                  df   dz  ed<   dZe
ej                  df   dz  ed<   dZe
ej                  df   dz  ed<   y)	SwinImageClassifierOutputa7  
    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.
    NrW   logits.r-   rL   rM   )r?   r@   rA   rB   rW   r6   rN   rO   r[   r-   rP   rL   rM   rQ   r,   r+   rZ   rZ      s     &*D%

d
")'+FE$+:>M5**C/047>7;Je'',-4;CGE%"3"3S"89D@Gr,   rZ   c                     | j                   \  }}}}| j                  |||z  |||z  ||      } | j                  dd      j                         j                  d|||      }|S )z2
    Partitions the given input into windows.
    r   r   r4   view	transpose
contiguous)input_featurewindow_size
batch_sizeheightwidthnum_channelswindowss          r+   window_partitionri      st     /<.A.A+J|!&&Fk);8Lk[gM %%a+668==b+{\hiGNr,   c                     | j                   d   }| j                  d||z  ||z  |||      } | j                  dd      j                         j                  d|||      } | S )z?
    Merges windows to produce higher resolution features.
    r]   r   r   r^   )rh   rc   re   rf   rg   s        r+   window_reverserk      sg     ==$Lll2v4e{6JKYdfrsG1%00277FE<XGNr,   c            
            e Zd ZdZd fd	Zdej                  dededej                  fdZ	 	 dd	ej                  dz  d
ej                  dz  dedeej                     fdZ xZS )SwinEmbeddingszW
    Construct the patch and position embeddings. Optionally, also the mask token.
    c                 l   t         |           t        |      | _        | j                  j                  }| j                  j
                  | _        |r4t        j                  t        j                  dd|j                              nd | _        |j                  r4t        j                  t        j                  d||j                              nd | _        t        j                  |j                        | _        t        j"                  |j$                        | _        |j(                  | _        || _        y )Nr   )r'   r(   SwinPatchEmbeddingspatch_embeddingsnum_patches	grid_size
patch_gridr   	Parameterr6   zeros	embed_dim
mask_tokenuse_absolute_embeddingsposition_embeddings	LayerNormnormDropouthidden_dropout_probdropout
patch_sizeconfig)r)   r   use_mask_tokenrq   r*   s       r+   r(   zSwinEmbeddings.__init__   s     3F ;++77//99O]",,u{{1a9I9I'JKcg LRKiKiBLLQV5E5EFGos 	  LL!1!12	zz&"<"<= ++r,   
embeddingsre   rf   r$   c                 (   |j                   d   }| j                  j                   d   }t        j                  j	                         s||k(  r||k(  r| j                  S |j                   d   }|| j
                  z  }|| j
                  z  }t        |dz        }	| j                  j                  d|	|	|      }
|
j                  dddd      }
t        j                  j                  |
||fdd	      }
|
j                  dddd      j                  dd|      S )
z
        Interpolate pre-trained position encodings to support higher-resolution images at inference.
        Unlike ViT, Swin has no CLS token, so position embeddings cover patch positions only.
        r   r]         ?r   r   r   bicubicF)sizemodealign_corners)r4   ry   r6   jit
is_tracingr   r   reshapepermuter   
functionalinterpolater_   )r)   r   re   rf   rq   num_positionsdim
new_height	new_widthsqrt_num_positionspatch_pos_embeds              r+   interpolate_pos_encodingz'SwinEmbeddings.interpolate_pos_encoding   s   
 !&&q)0066q9 yy##%+*F6UZ?+++r"t.
T__,	&}c'9:22::1>PRdfij)11!Q1=--33i(	 4 
 &&q!Q2772sCCr,   Npixel_valuesbool_masked_posr   c                    |j                   \  }}}}| j                  |      \  }}	| j                  |      }|j                         \  }
}}|K| j                  j                  |
|d      }|j                  d      j                  |      }|d|z
  z  ||z  z   }| j                  (|r|| j                  |||      z   }n|| j                  z   }| j                  |      }||	fS )Nr]   g      ?)r4   rp   r{   r   rw   expand	unsqueezetype_asry   r   r~   )r)   r   r   r   _rg   re   rf   r   output_dimensionsrd   seq_lenmask_tokensmasks                 r+   r<   zSwinEmbeddings.forward   s     *6););&<(,(=(=l(K%
%YYz*
!+!2
GQ&//00WbIK",,R088ED#sTz2[45GGJ##/''$*G*G
TZ\a*bb
'$*B*BB
\\*-
,,,r,   F)NF)r?   r@   rA   rB   r(   r6   rD   intr   rN   
BoolTensorboolrP   r<   rF   rG   s   @r+   rm   rm      s    "D5<< D DUX D]b]i]i DB 48).	-''$.- ))D0- #'	-
 
u||	-r,   rm   c                   v     e Zd ZdZ fdZd Zdej                  dz  deej                  ee
   f   fdZ xZS )ro   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         |           |j                  |j                  }}|j                  |j
                  }}t        |t        j                  j                        r|n||f}t        |t        j                  j                        r|n||f}|d   |d   z  |d   |d   z  z  }|| _        || _
        |d   |d   z  |d   |d   z  f| _        t        j                  ||||      | _        y )Nr   r   )kernel_sizestride)r'   r(   
image_sizer   rg   rv   
isinstancecollectionsabcIterablerq   rr   r   Conv2d
projection)r)   r   r   r   rg   hidden_sizerq   r*   s          r+   r(   zSwinPatchEmbeddings.__init__  s    !'!2!2F4E4EJ
$*$7$79I9Ik#-j+//:R:R#SZZdfpYq
#-j+//:R:R#SZZdfpYq
!!}
15*Q-:VW=:XY$&$Q-:a=8*Q-:VW=:XY))L+:^hir,   c                 n   || j                   d   z  dk7  rDd| j                   d   || j                   d   z  z
  f}t        j                  j                  ||      }|| j                   d   z  dk7  rFddd| j                   d   || j                   d   z  z
  f}t        j                  j                  ||      }|S )z9Pad pixel_values to be divisible by patch_size if needed.r   r   )r   r   r   pad)r)   r   re   rf   
pad_valuess        r+   	maybe_padzSwinPatchEmbeddings.maybe_pad'  s    4??1%%*T__Q/%$//!:L2LLMJ==,,\:FLDOOA&&!+Q4??1#5QRAS8S#STJ==,,\:FLr,   r   Nr$   c                     |j                   \  }}}}| j                  |||      }| j                  |      }|j                   \  }}}}||f}|j                  d      j	                  dd      }||fS )Nr   r   )r4   r   r   flattenr`   )r)   r   r   rg   re   rf   r   r   s           r+   r<   zSwinPatchEmbeddings.forward1  s}    )5););&<~~lFEB__\2
(..1fe#UO''*44Q:
,,,r,   )r?   r@   rA   rB   r(   r   r6   rN   rP   rD   r   r<   rF   rG   s   @r+   ro   ro     sF    j	-E$5$5$< 	-u||UZ[^U_G_A` 	-r,   ro   c                        e Zd ZdZdeddf fdZdej                  dededej                  fd	Zdej                  d
e	eef   dej                  fdZ
 xZS )SwinPatchMergingzd
    Patch Merging Layer.

    Args:
        dim (`int`):
            Number of input channels.
    r   r$   Nc                     t         |           t        j                  d|z  d|z  d      | _        t        j
                  d|z        | _        y )N   r   Fbias)r'   r(   r   Linear	reductionrz   r{   )r)   r   r*   s     r+   r(   zSwinPatchMerging.__init__F  s>    1s7AG%@LLS)	r,   rb   re   rf   c           
      ~    |dz  dk(  s|dz  dk(  r,t         j                  j                  |ddd|dz  d|dz  f      }|S )zPPad input feature map to be divisible by 2 in both spatial dimensions if needed.r   r   r   )r   r   r   )r)   rb   re   rf   s       r+   r   zSwinPatchMerging.maybe_padK  sL    QJ!OaMM--maAuqyRSU[^_U_=`aMr,   input_dimensionsc                    |\  }}|j                   \  }}}|j                  ||||      }| j                  |||      }t        j                  t        d      D 	cg c]%  }t        d      D ]  }	|d d |	d d|d dd d f    ' c}	}d      }|j                  |dd|z        }| j                  |      }| j                  |      }|S c c}	}w )Nr   r]   r   r   )r4   r_   r   r6   catranger{   r   )
r)   rb   r   re   rf   rd   r   rg   colrows
             r+   r<   zSwinPatchMerging.forwardQ  s    ((5(;(;%
C%**:vulS}feD		<A!HYSPUVWPXY]1cf1fcf1fa/0Y0Y_a
 &**:r1|;KL		-0}5 Zs   *C
)r?   r@   rA   rB   r   r(   r6   rD   r   rP   r<   rF   rG   s   @r+   r   r   =  su    *C *D *
u|| S  QVQ]Q] U\\ U3PS8_ Y^YeYe r,   r   c                   v     e Zd ZdZdedeeef   f fdZdej                  fdZ	dej                  fdZ
 xZS )SwinRelativePositionBiasa  
    Relative position bias for Swin's window-based attention, following the style of BeitRelativePositionBias.

    Unlike BeiT, Swin has no CLS token, so the table covers exactly (2*ws_h-1)*(2*ws_w-1) unique
    relative positions. The lookup index is purely determined by window_size (static), so it is stored
    as a non-persistent buffer (recomputed from config on load, never serialised). The table values
    are learned parameters and must be re-read on every forward call.
    	num_headsrc   c                 8   t         |           || _        |d   |d   z  | _        t	        j
                  t        j                  d|d   z  dz
  d|d   z  dz
  z  |            | _        | j                  d| j                         j                  d      d       y )Nr   r   r   relative_position_indexr]   F)
persistent)r'   r(   rc   window_arear   rt   r6   ru   relative_position_bias_tableregister_buffer_create_relative_position_indexr_   )r)   r   rc   r*   s      r+   r(   z!SwinRelativePositionBias.__init__o  s    &&q>KN:,.LLKK[^+a/AA4F4JKYW-
)
 	%00277; 	 	
r,   r$   c                    t        j                  | j                  d         }t        j                  | j                  d         }t        j                  t        j                  ||gd            }t        j
                  |d      }|d d d d d f   |d d d d d f   z
  }|j                  ddd      j                         }|d d d d dfxx   | j                  d   dz
  z  cc<   |d d d d dfxx   | j                  d   dz
  z  cc<   |d d d d dfxx   d| j                  d   z  dz
  z  cc<   |j                  d      S )Nr   r   ij)indexingr   r]   )	r6   arangerc   stackmeshgridr   r   ra   sum)r)   coords_hcoords_wcoordscoords_flattenrelative_coordss         r+   r   z8SwinRelativePositionBias._create_relative_position_index~  s)   << 0 0 34<< 0 0 34U^^Xx,@4PQ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$?? ""2&&r,   c                     | j                   | j                     }|j                  | j                  | j                  d      }|j	                  ddd      j                         j                  d      S )Nr]   r   r   r   )r   r   r_   r   r   ra   r   )r)   relative_position_biass     r+   r<   z SwinRelativePositionBias.forward  sd    !%!B!B4C_C_!`!7!<!<T=M=MtO_O_ac!d%--aA6AACMMaPPr,   )r?   r@   rA   rB   r   rP   r(   r6   rD   r   r<   rF   rG   s   @r+   r   r   e  sE    
# 
E#s(O 
' '"Q Qr,   r   c                        e Zd Zdedededef fdZ	 ddej                  dej                  dz  d	e	e
   d
eej                  ej                  f   fdZ xZS )SwinAttentionr   r   num_attention_headsrc   c                    t         |   |       || _        ||z  | _        | j                  dz  | _        t        j                  |||j                        | _        t        j                  |||j                        | _	        t        j                  |||j                        | _
        t        j                  ||      | _        t        |||f      | _        y )Ng      r   )r'   r(   r   head_dimscalingr   r   qkv_biasq_projk_projv_projo_projr   r   )r)   r   r   r   rc   r*   s        r+   r(   zSwinAttention.__init__  s     #6 #'::}}d*ii[vOii[vOii[vOii[9&>?RU`bmTn&o#r,   Nr-   attention_maskkwargsr$   c                    |j                   d d }g |d| j                  }| j                  |      j                  |      j	                  dd      }| j                  |      j                  |      j	                  dd      }| j                  |      j                  |      j	                  dd      }| j                         }	|g|j                   d   }
|d   |
z  }|d   }|j                  d      j                  d      j                  |dddd      j                  dd||      }|	|z   }n|	}t        j                  | j                  j                  t              } || ||||f| j                   sdn| j"                  | j$                  d|\  }} |j                  g |d j'                         }| j)                  |      }||fS )Nr]   r   r   r   r/   )r~   r   )r4   r   r   r_   r`   r   r   r   r   r   r   r   get_interfacer   _attn_implementationr   r3   attention_dropoutr   ra   r   )r)   r-   r   r   input_shapehidden_shapequery_states
key_statesvalue_statesr   num_windowsrd   r   combined_maskattention_interfaceattn_outputattn_weightss                    r+   r<   zSwinAttention.forward  s    $))#2.88b8$--8{{=166|DNNqRST[[/44\BLLQPQR
{{=166|DNNqRST "&!<!<!>%(..q1K$Q;6J!!nG ((+1
BB3Q1	  3^CM2M(?(M(MKK,,.E)
 %8	%
  $}}C$2H2HLL	%
 	%
!\ *k));;;;FFHkk+.L((r,   r&   )r?   r@   rA   r    r   r(   r6   rD   rN   r   r   rP   r<   rF   rG   s   @r+   r   r     s    pz p pRU pdg p  482)||2) ))D02) +,	2)
 
u||U\\)	*2)r,   r   c                       e Zd ZdedefdZy)SwinMLPr   r   c                 6   t         j                  j                  |        t        |j                     | _        t        j                  |t        |j                  |z              | _	        t        j                  t        |j                  |z        |      | _
        y r&   )r   Moduler(   r   
hidden_actactivation_fnr   r   	mlp_ratiofc1fc2)r)   r   r   s      r+   r(   zSwinMLP.__init__  sk    
		4 #F$5$5699S#f&6&6&<"=>99S!1!1C!78#>r,   N)r?   r@   rA   r    r   r(   rQ   r,   r+   r   r     s    ?z ? ?r,   r   c                       e Zd Z	 	 ddededeeef   dededef fdZdeeef   dd	fd
Zdedede	j                  de	j                  de	j                  d	z  f
dZde	j                  dededee	j                  eedf   f   fdZdde	j                  dede	j                  fdZ	 dde	j                  deeef   dedee   de	j                  f
dZ xZS )	SwinLayerr   r   input_resolutionr   drop_path_rate
shift_sizec                    t         |           |j                  | _        t        ||||j                        | _        t        j                  ||j                        | _        t        j                  ||j                        | _	        t        ||      | _        || _        || _        |dkD  rt        |      | _        y t        j                         | _        y )N)rc   epsr/   )r'   r(   rc   r   	attentionr   rz   layer_norm_epslayernorm_beforelayernorm_afterr   mlpr  r  r"   Identity	drop_path)r)   r   r   r  r   r  r  r*   s          r+   r(   zSwinLayer.__init__  s     	!--&vsI6K]K]^ "Sf6K6K L!||CV5J5JK63'$ 09G#9Mn5SUS^S^S`r,   r$   Nc                    t        |      | j                  k  rgt        d      | _        t        j
                  j                         r(t	        j                   t	        j                  |            n
t        |      | _        yy)zQClamp window and shift sizes when the window is larger than the input resolution.r   N)minrc   r   r  r6   r   r   tensor)r)   r  s     r+   set_shift_and_window_sizez#SwinLayer.set_shift_and_window_size  s\     D$4$44'lDO=BYY=Q=Q=S		%,,'789Y\]mYn  5r,   re   rf   r1   r2   c                    | j                   dk  ryt        j                  ||      }t        j                  ||      }||| j                  z
  k\  j	                         ||| j                   z
  k\  j	                         z   }||| j                  z
  k\  j	                         ||| j                   z
  k\  j	                         z   }|dddddf   dz  |dddddf   z   j                  |      }	t        |	| j                        }
|
j                  d| j                  | j                  z        }
|
j                  d      |
j                  d      z
  }|j                  |dk7  d      j                  |dk(  d	      }|S )
u  Build the cyclic-shift attention mask for shifted-window MSA; returns None when shift_size is 0.

        Each (h, w) position belongs to one of 9 cyclic-shift regions (3 along each axis), encoded
        as ``h_region * 3 + w_region``. Regions per axis:
        - 0: indices ``[0, axis - window_size)``
        - 1: indices ``[axis - window_size, axis - shift_size)``
        - 2: indices ``[axis - shift_size, axis)``
        Implementation note: a single arithmetic pass on `torch.arange` (two comparisons +
        broadcast add) replaces the original 9-iteration nested-Python-loop slice-assignment —
        fully vectorised, no per-cell host-side scatter, no GPU↔host sync.
        r   N)r2   r   r]   r   r   g      Yr/   )
r  r6   r   rc   longtori   r_   r   masked_fill)r)   re   rf   r1   r2   h_idxw_idxh_regionw_regionimg_maskmask_windows	attn_masks               r+   get_attn_maskzSwinLayer.get_attn_mask  si    ??aVF3U62Vd&6&666<<>%6TXTcTcKcBcAiAiAkkUT%5%555;;=%RVRaRaJaAa@g@g@iiT1dD01A5tQPTAT8UUYYZ_`'$2B2BC#((T-=-=@P@P-PQ **1-0F0Fq0II	)))q.&AMMi[\n^ab	r,   r-   .c                     | j                   || j                   z  z
  | j                   z  }| j                   || j                   z  z
  | j                   z  }ddd|d|f}t        j                  j                  ||      }||fS )zHPad feature map so both spatial dimensions are divisible by window_size.r   )rc   r   r   r   )r)   r-   re   rf   	pad_right
pad_bottomr   s          r+   r   zSwinLayer.maybe_pad  s    %%0@0@(@@DDTDTT	&&$2B2B)BBdFVFVV
Ay!Z8
))-Dj((r,   reversec                     | j                   dkD  r:|rdnd}t        j                  ||| j                   z  || j                   z  fd      }|S )zOApply a cyclic shift along the spatial dimensions for shifted-window attention.r   r   r]   )r   r   )shiftsdims)r  r6   roll)r)   r-   r%  	directions       r+   cyclic_shiftzSwinLayer.cyclic_shift  sM    ??Q$"I!JJ!DOO3Y5PQM
 r,   r   always_partitionr   c                    |s| j                  |       |\  }}|j                         \  }}}	|}
| j                  |      }|j                  ||||	      }| j	                  |||      \  }}|j
                  \  }}}}t        | j                  |      | j                        }|j                  d| j                  | j                  z  |	      }| j                  |||j                  |j                        } | j                  ||fi |\  }}| j                  |      }|j                  d| j                  | j                  |	      }| j                  t        || j                  ||      d      }|d   dkD  s|d   dkD  r|d d d |d |d d f   j                         }|j                  |||z  |	      }|
| j!                  |      z   }|}| j#                  |      }| j%                  |      }| j                  |      |z   }||fS )Nr]   r0   T)r%  r   r      )r  r   r  r_   r   r4   ri   r+  rc   r!  r1   r2   r  r~   rk   ra   r  r  r  )r)   r-   r   r,  r   re   rf   rd   r   channelsshortcutr   
height_pad	width_padhidden_states_windowsr   attention_outputr   attention_windowsresiduals                       r+   r<   zSwinLayer.forward(  s-     **+;<("/"4"4"6
Ax --m<%**:vuhO %)NN=&%$P!z&3&9&9#:y! 01B1B=1QSWScSc d 5 : :2t?O?ORVRbRb?bdl m&&	)<)<EZEaEa ' 
	 *88My)c\b)c&,<<(89,11"d6F6FHXHXZbc --,d.>.>
IV`d . 
 a=1
1 1 1!WfWfufa2G H S S U-22:v~xX 4>>2C#DD ,,];/]3h>l**r,   )r/   r   r   )r?   r@   rA   r    r   rP   rC   r(   r  r6   r1   r2   rD   r!  r   r   r+  r   r   r<   rF   rG   s   @r+   r  r    sm    !$aa a  S/	a
 a a a&%S/ d C  EKK QVQ]Q] bgbnbnqubu 2)u|| )S ) )QVW\WcWcejknpsksetWtQu )	%,, 	 	RWR^R^ 	 "'	-+||-+  S/-+ 	-+
 +,-+ 
-+r,   r  c                   <    e Zd Zdededeeef   dededee   f fdZde	j                  d	e	j                  d
ededede	j                  fdZ	 	 dde	j                  deeef   dededee   dee	j                  e	j                  e	j                  dz  f   fdZ xZS )	SwinStager   r   r  depthr   r  c                    t         	|           || _        t        j                  t        |      D cg c]-  }t        ||||||   |dz  dk(  rdn|j                  dz        / c}      | _        | ||      | _	        y d | _	        y c c}w )Nr   r   )r   r   r  r   r  r  r   )
r'   r(   r   r   
ModuleListr   r  rc   blocks
downsample)
r)   r   r   r  r9  r   r  r=  ir*   s
            r+   r(   zSwinStage.__init__Y  s     	mm u
  !%5'#,Q<%&UaZqf6H6HA6M

 2<1G*-T
s   2B
r-   !hidden_states_before_downsamplingre   rf   (output_hidden_states_before_downsamplingr$   c                     |r|||}}}n%| j                   ||dz   dz  |dz   dz  }}}n|||}}}|j                  \  }	}
}|j                  |	|||      j                  dddd      j	                         S )u  
        Select the spatial hidden states for this stage and reshape from (B, L, C) to (B, C, H, W).

        The chosen state and its resolution depend on output_hidden_states_before_downsampling:
        - True  → pre-downsampling states at (height, width) — used by the backbone.
        - False → post-downsampling states at half the resolution (if a downsampler exists).
        r   r   r   r   )r=  r4   r_   r   ra   )r)   r-   r?  re   rf   r@  spatial_statehwrd   r   r   s               r+   get_reshaped_hidden_statesz$SwinStage.get_reshaped_hidden_statesu  s     4"CVUa1M__("/&1*1BUQYSTDTa1M"/a1M%2%8%8"
A{!!*aK@HHAqRST__aar,   r   r,  r   Nc                     |\  }}d }| j                   D ]  }	 |	||fd|i|\  }} |}
| j                  | j                  |
|      }| j                  ||
|||      }|||fS )Nr,  )r<  r=  rE  )r)   r-   r   r,  r@  r   re   rf   last_attn_weightslayer_moduler?  rM   s               r+   r<   zSwinStage.forward  s     )  KK 	L/;/0BR0V\0,M,	
 -:)??& OO,MO_`M!%!@!@<feMu"
 46GGGr,   )FF)r?   r@   rA   r    r   rP   listrC   r(   r6   rD   r   rE  r   r   r<   rF   rG   s   @r+   r8  r8  X  s$   RR R  S/	R
 R R ;R8b||b ,1<<b 	b
 b 37b 
b: "'9>H||H  S/H 	H
 37H +,H 
u||U\\5<<$+>>	?Hr,   r8  c                       e Zd ZU eed<   dgZdZdZddgZ e	e
dd       e	e
d	d      d
Z ej                         d        Zy)SwinPreTrainedModelr   r8  Fz(attention\.self\.relative_position_indexz:attention\.relative_position_bias\.relative_position_indexr   T)indexcapture_initial_hidden_stater   )r-   rL   c                    t        j                  | |       t        |t              rX|j                  t        j                  |j                         |j                   t        j                  |j                         yyt        |t              r]t        j                  |j                         t        j                  |j                  |j                         j                  d             yy)zInitialize the weightsNr]   )r   _init_weightsr   rm   rw   initzeros_ry   r   r   copy_r   r   r_   )r)   modules     r+   rO  z!SwinPreTrainedModel._init_weights  s     	%%dF3fn-  ,F--.))5F667 6 89KK;;<JJv55v7]7]7_7d7deg7hi :r,   N)r?   r@   rA   r    rO   _no_split_modules_supports_flash_attn_supports_flex_attn"_keys_to_ignore_on_load_unexpectedr   r8  _can_record_outputsr6   no_gradrO  rQ   r,   r+   rK  rK    sp    $  	4E*& (	Y]^
 %YaV[\	 U]]_
j 
jr,   rK  c                        e Zd Zdedeeef   f fdZe ed      e		 	 	 dde
j                  deeef   ded	ed
edee   defd                     Z xZS )SwinEncoderr   rr   c                    t         |   |       t        |j                        | _        || _        t        t        |j                              D cg c]4  }|j                  |z  t        t        |j                        dz
  d      z  6 }}t        j                  t        | j                        D cg c]  }t        |t        |j                  d|z  z        |d   d|z  z  |d   d|z  z  f|j                  |   |j                  |   |t        |j                  d |       t        |j                  d |dz           || j                  dz
  k  rt         nd        c}      | _        | j%                          y c c}w c c}w )Nr   r   r   )r   r   r  r9  r   r  r=  )r'   r(   lendepths
num_layersr   r   r   r  maxr   r;  r8  r   rv   r   r   layers	post_init)r)   r   rr   r>  dpr	layer_idxr*   s         r+   r(   zSwinEncoder.__init__  sd    fmm,SXY\]c]j]jYkSlmav$$q(3s6==/AA/Eq+IImmmm "'t!7  !F,,q)|;<&/lq)|&DiPQlWXZcWcFd%e --	2$..y9!#fmmJY&?"@3v}}UdW`cdWdGeCfg4=RS@S4S/Z^
 	 ns   9E:3B*E?F)tie_last_hidden_statesr-   r   r,  output_hidden_statesr@  r   r$   c                 N   d}|rH|j                   \  }}	}
 |j                  |g||
 j                  dddd      j                         }|f}| j                  D ]>  } |||f||d|\  }}}	|r||fz  }|j
                  )|d   dz   dz  |d   dz   dz  f}@ t        ||      S )a  
        input_dimensions (`tuple[int, int]`):
            Spatial `(height, width)` of the patch grid entering the encoder.
        always_partition (`bool`, *optional*, defaults to `False`):
            If `True`, always apply window partitioning regardless of input resolution.
        output_hidden_states_before_downsampling (`bool`, *optional*, defaults to `False`):
            If `True`, `reshaped_hidden_states` contains pre-downsampling feature maps.
        Nr   r   r   r   r,  r@  )rK   rM   )r4   r_   r   ra   ra  r=  rJ   )r)   r-   r   r,  rf  r@  r   all_reshaped_hidden_statesrd   r   r   stem_spatialrH  reshaped_hidden_states                 r+   r<   zSwinEncoder.forward  s   ( &*" *7)<)<&J;""":N0@N+NVVWXZ[]^`abmmo  +7& KK 	dL6B 7 "29a	7
 73M0! $*/D.FF*&&2%5a%81%<$BEUVWEX[\E\abDb#c 	d !+#=
 	
r,   )FFF)r?   r@   rA   r    rP   r   r(   r   r   r   r6   rD   r   r   r   rJ   r<   rF   rG   s   @r+   r[  r[    s    z eCHo *  E2
 "'%*9>+
||+
  S/+
 	+

 #+
 37+
 +,+
 
+
  3  +
r,   r[  c                        e Zd Zd	 fd	Zee	 	 	 d
dej                  dz  dej                  dz  de	de
e   def
d              Z xZS )	SwinModelc                    t         |   |       || _        t        |j                        | _        t        |j                  d| j
                  dz
  z  z        | _        t        ||      | _
        t        || j                  j                        | _        t        j                  | j                  |j                         | _        |rt        j$                  d      nd| _        | j)                          y)a  
        add_pooling_layer (`bool`, *optional*, defaults to `True`):
            Whether or not to apply pooling layer.
        use_mask_token (`bool`, *optional*, defaults to `False`):
            Whether or not to create and apply mask tokens in the embedding layer.
        r   r   )r   r	  N)r'   r(   r   r]  r^  r_  r   rv   num_featuresrm   r   r[  rs   encoderr   rz   r  	layernormAdaptiveAvgPool1dpoolerrb  )r)   r   add_pooling_layerr   r*   s       r+   r(   zSwinModel.__init__  s     	 fmm, 0 0119L3M MN(O"64??+E+EFd&7&7V=R=RS1Bb**1- 	r,   Nr   r   r   r   r$   c                    |j                  d| j                  j                        }| j                  |||      \  }} | j                  ||fd|i|}|j
                  }	| j                  |	      }	d}
| j                  7| j                  |	j                  dd            }
t        j                  |
d      }
t        |	|
|j                  |j                  |j                        S )z
        bool_masked_pos (`torch.BoolTensor` of shape `(batch_size, num_patches)`, *optional*):
            Boolean masked positions. Indicates which patches are masked (1) and which aren't (0).
        rf  r   r   Nr   r   )rK   rT   r-   rL   rM   )popr   rf  r   rp  rK   rq  rs  r`   r6   r   rS   r-   rL   rM   )r)   r   r   r   r   rf  embedding_outputr   encoder_outputssequence_outputpooled_outputs              r+   r<   zSwinModel.forward*  s      &zz*@$++BbBbc-1__/Tl .= .
** '$,,
 "6
 	
 *;;..9;;" KK(A(A!Q(GHM!MM-;M-')77&11#2#I#I
 	
r,   )TFNNF)r?   r@   rA   r(   r   r   r6   rN   r   r   r   r   rS   r<   rF   rG   s   @r+   rm  rm    s{    *  2637).	(
''$.(
 ))D0(
 #'	(

 +,(
 
(
  (
r,   rm  ad  
    Swin Model with a decoder on top for masked image modeling, as proposed in [SimMIM](https://huggingface.co/papers/2111.09886).

    <Tip>

    Note that we provide a script to pre-train this model on custom data in our [examples
    directory](https://github.com/huggingface/transformers/tree/main/examples/pytorch/image-pretraining).

    </Tip>
    c                        e Zd Z fdZee	 	 	 d	dej                  dz  dej                  dz  de	de
e   def
d              Z xZS )
SwinForMaskedImageModelingc                    t         |   |       t        |dd      | _        t	        |j
                  d|j                  dz
  z  z        }t        j                  t        j                  ||j                  dz  |j                  z  d      t        j                  |j                              | _        | j                          y )NFT)rt  r   r   r   )in_channelsout_channelsr   )r'   r(   rm  swinr   rv   r_  r   
Sequentialr   encoder_striderg   PixelShuffledecoderrb  )r)   r   ro  r*   s      r+   r(   z#SwinForMaskedImageModeling.__init__d  s     fdS	6++aF4E4E4I.JJK}}II(v7L7La7ORXReRe7est OOF112	
 	r,   Nr   r   r   r   r$   c                 |    | j                   |f||d|}|j                  }|j                  dd      }|j                  \  }}}	t	        j
                  |	dz        x}
}|j                  |||
|      }| j                  |      }d}|| j                  j                  | j                  j                  z  }|j                  d||      }|j                  | j                  j                  d      j                  | j                  j                  d      j                  d      j                         }t        j                  j!                  ||d      }||z  j#                         |j#                         d	z   z  | j                  j$                  z  }t'        |||j(                  |j*                  |j,                  
      S )a  
        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).

        Examples:
        ```python
        >>> from transformers import AutoImageProcessor, SwinForMaskedImageModeling
        >>> import torch
        >>> from PIL import Image
        >>> import httpx
        >>> from io import BytesIO

        >>> url = "http://images.cocodataset.org/val2017/000000039769.jpg"
        >>> with httpx.stream("GET", url) as response:
        ...     image = Image.open(BytesIO(response.read()))

        >>> image_processor = AutoImageProcessor.from_pretrained("microsoft/swin-base-simmim-window6-192")
        >>> model = SwinForMaskedImageModeling.from_pretrained("microsoft/swin-base-simmim-window6-192")

        >>> num_patches = (model.config.image_size // model.config.patch_size) ** 2
        >>> pixel_values = image_processor(images=image, return_tensors="pt").pixel_values
        >>> # create random boolean mask of shape (batch_size, num_patches)
        >>> bool_masked_pos = torch.randint(low=0, high=2, size=(1, num_patches)).bool()

        >>> outputs = model(pixel_values, bool_masked_pos=bool_masked_pos)
        >>> loss, reconstructed_pixel_values = outputs.loss, outputs.reconstruction
        >>> list(reconstructed_pixel_values.shape)
        [1, 3, 192, 192]
        ```rv  r   r   r   Nr]   none)r   gh㈵>)rW   rX   r-   rL   rM   )r  rK   r`   r4   mathr8   r   r  r   r   r   repeat_interleaver   ra   r   r   l1_lossr   rg   rV   r-   rL   rM   )r)   r   r   r   r   outputsrz  rd   rg   sequence_lengthre   rf   reconstructed_pixel_valuesmasked_im_lossr   r   reconstruction_losss                    r+   r<   z"SwinForMaskedImageModeling.forwardt  s   L $))
+%=
 	
 "33)33Aq94C4I4I1
L/OS$899)11*lFTYZ &*\\/%B"&;;))T[[-C-CCD-55b$EO11$++2H2H!L""4;;#9#91=1	  #%--"7"7F`lr"7"s1D8==?488:PTCTUX\XcXcXpXppN,5!//))#*#A#A
 	
r,   r|  )r?   r@   rA   r(   r   r   r6   rN   r   r   r   r   rV   r<   rF   rG   s   @r+   r~  r~  W  s       2637).	H
''$.H
 ))D0H
 #'	H

 +,H
 
'H
  H
r,   r~  a  
    Swin 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 Swin 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                        e Zd Z fdZee	 	 	 d	dej                  dz  dej                  dz  de	de
e   def
d              Z xZS )
SwinForImageClassificationc                 >   t         |   |       |j                  | _        t        |      | _        |j                  dkD  r4t        j                  | j                  j                  |j                        nt        j                         | _	        | j                          y )Nr   )r'   r(   
num_labelsrm  r  r   r   ro  r  
classifierrb  )r)   r   r*   s     r+   r(   z#SwinForImageClassification.__init__  sx      ++f%	 EKDUDUXYDYBIIdii,,f.?.?@_a_j_j_l 	
 	r,   Nr   labelsr   r   r$   c                     | j                   |fd|i|}|j                  }| j                  |      }d}| | j                  ||| j                  fi |}t        |||j                  |j                  |j                        S )a  
        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).
        r   N)rW   r[   r-   rL   rM   )	r  rT   r  loss_functionr   rZ   r-   rL   rM   )	r)   r   r  r   r   r  r{  r[   rW   s	            r+   r<   z"SwinForImageClassification.forward  s     $))
%=
 
  --/%4%%ffdkkLVLD(!//))#*#A#A
 	
r,   r|  )r?   r@   rA   r(   r   r   r6   rN   
LongTensorr   r   r   rZ   r<   rF   rG   s   @r+   r  r    s{      26*.).	!
''$.!
   4'!
 #'	!

 +,!
 
#!
  !
r,   r  zM
    Swin backbone, to be used with frameworks like DETR and MaskFormer.
    c            	       v     e Zd ZdgZdef fdZeeede	j                  dee   defd                     Z xZS )SwinBackbonezswin.layernorm.*r   c           	         t         |   |       |j                  gt        t	        |j
                              D cg c]  }t        |j                  d|z  z         c}z   | _        t        |d      | _	        i }t        | j                  | j                        D ]  \  }}t        j                  |      ||<    t        j                  |      | _        | j#                          y c c}w )Nr   F)rt  )r'   r(   rv   r   r]  r^  r   ro  rm  r  zipout_featuresr/  r   rz   
ModuleDicthidden_states_normsrb  )r)   r   r>  r  stagerg   r*   s         r+   r(   zSwinBackbone.__init__  s     #--.X]^abhbobo^pXq1rST#f6F6FA6M2N1rrf>	 !#&t'8'8$--#H 	DE<)+l)C&	D#%==1D#E  	 2ss   "C(r   r   r$   c                     | j                   |fddd|}d}t        | j                  |j                        D ]  \  }}|| j                  v s|j
                  \  }}}	}
|j                  dddd      j                         }|j                  ||	|
z  |      } | j                  |   |      }|j                  ||	|
|      }|j                  dddd      j                         }||fz  } t        ||j                  |j                        S )	a  
        Examples:

        ```python
        >>> from transformers import AutoImageProcessor, AutoBackbone
        >>> import torch
        >>> from PIL import Image
        >>> import httpx
        >>> from io import BytesIO

        >>> url = "http://images.cocodataset.org/val2017/000000039769.jpg"
        >>> with httpx.stream("GET", url) as response:
        ...     image = Image.open(BytesIO(response.read()))

        >>> processor = AutoImageProcessor.from_pretrained("shi-labs/nat-mini-in1k-224")
        >>> model = AutoBackbone.from_pretrained(
        ...     "microsoft/swin-tiny-patch4-window7-224", out_features=["stage1", "stage2", "stage3", "stage4"]
        ... )

        >>> inputs = processor(image, return_tensors="pt")
        >>> outputs = model(**inputs)
        >>> feature_maps = outputs.feature_maps
        >>> list(feature_maps[-1].shape)
        [1, 768, 7, 7]
        ```
        Trh  rQ   r   r   r   r   )feature_mapsr-   rL   )r  r  stage_namesrM   r  r4   r   ra   r_   r  r   rL   )r)   r   r   r  r  r  hidden_staterd   rg   re   rf   s              r+   r<   zSwinBackbone.forward  s0   H $))
!59
 	
 #&t'7'79W9W#X 	0E<))):F:L:L7
L&%+33Aq!Q?JJL+00Ve^\Z>t77>|L+00VULY+33Aq!Q?JJL/	0 %!88))
 	
r,   )r?   r@   rA   _keys_to_ignore_on_load_missingr    r(   r   r
   r   r6   rD   r   r   r   r<   rF   rG   s   @r+   r  r    sd     (;&;#z   7
ll7
 +,7
 
	7
  ! 7
r,   r  )r  r~  rm  rK  r  )HrB   collections.abcr   r  r   dataclassesr   r6   r    r   rP  activationsr   backbone_utilsr	   r
   modeling_layersr   modeling_outputsr   modeling_utilsr   processing_utilsr   utilsr   r   r   r   r   utils.genericr   r   utils.output_capturingr   r   vit.modeling_vitr   r   r   r   r   r   configuration_swinr    
get_loggerr?   loggerr   r"   rJ   rS   rV   rZ   ri   rk   rm   ro   r   r   r   r   r  r8  rK  r[  rm  r~  r  r  __all__rQ   r,   r+   <module>r     s   &   $ !   & ! H 9 . 5 & X X I E  + 
		H	%%299 %0 
 H H H  
 Hk H H& 
 HK H H* 
 H H H*	M-RYY M-`'-")) '-T%ryy %P-Qryy -Q`@)L @)F?f ?u+ u+pMH* MH`  j,  j  jFD
% D
N @
# @
 @
F 	[
!4 [
[
| 2
!4 2
2
j 
L
="5 L

L
^r,   