Ë
    ëÓ^j°è  ã                   ó  — d Z ddlZddlZddlmZmZmZmZm	Z	m
Z
 ddlZddlmZ ddlmZmZmZ ddlmZmZ ddlmZ ddlmZ dd	lmZmZmZmZ dd
lmZ ddlm Z  ddl!m"Z"m#Z#m$Z$m%Z%m&Z&  e$jN                  e(«      Z)dee*   de*de*dee*   de	ee*   ejV                  f   f
d„Z,deee-      dee
ee*   e	e*df   f      dee-   de	ee-   ee*   f   fd„Z.deee-      dee
ee*   e	e*df   f      dee-   de	ee-   ee*   f   fd„Z/dZ0 G d„ dee«      Z1 G d„ dejd                  «      Z3 G d„ dejd                  «      Z4 G d„ d ejd                  «      Z5 G d!„ d"e5«      Z6 G d#„ d$ejd                  «      Z7 G d%„ d&ejd                  «      Z8 G d'„ d(e8«      Z9 G d)„ d*ejd                  «      Z:dId+ejv                  d,e<d-e=dejv                  fd.„Z> G d/„ d0ejd                  «      Z? G d1„ d2ejd                  «      Z@ G d3„ d4ejd                  «      ZAe8e9d5œZB G d6„ d7ejd                  «      ZC G d8„ d9ejd                  «      ZD G d:„ d;e«      ZEd<ZFd=ZG e"d>eF«       G d?„ d@eE«      «       ZHdAZI e"dBeF«       G dC„ dDeE«      «       ZJ e"dEeF«       G dF„ dGeEe«      «       ZKg dH¢ZLy)Jaº  DINOv2-with-Registers backbone with windowed self-attention.

This module is a local copy of the HuggingFace Transformers DINOv2-with-Registers implementation, extended with windowed
attention support for RF-DETR.  It targets the transformers v5 API (``transformers>=5.0.0``).

Transformers v5 API changes vs v4
----------------------------------
``head_mask`` removed:
    The ``head_mask`` parameter that appeared on every ``forward()`` in v4 has been
    dropped in v5.  It defaulted to ``None`` throughout the call chain and callers universally passed ``None``, so
    removing it produces **identical numerics**. Permanent head pruning is still available via ``model._prune_heads()``.

``BackboneMixin._init_transformers_backbone`` signature:
    In v4 this method accepted ``(self, config)``.  In v5 it accepts only ``(self)``;
    the config is accessed via ``self.config`` internally.

Helper functions copied locally:
    ``get_aligned_output_features_output_indices`` and ``find_pruneable_heads_and_indices`` were removed
    from the transformers v5 public API.  Private copies (``_get_aligned_output_features_output_indices``
    and ``_find_pruneable_heads_and_indices``) are kept in this module.
é    N)ÚDictÚListÚOptionalÚSetÚTupleÚUnion)Únn)ÚBCEWithLogitsLossÚCrossEntropyLossÚMSELoss)ÚBackboneConfigMixinÚBackboneMixin)ÚACT2FN)ÚPretrainedConfig)ÚBackboneOutputÚBaseModelOutputÚBaseModelOutputWithPoolingÚImageClassifierOutput)ÚPreTrainedModel)Úprune_linear_layer)Úadd_start_docstringsÚ%add_start_docstrings_to_model_forwardÚloggingÚreplace_return_docstringsÚ	torch_intÚheadsÚn_headsÚ	head_sizeÚalready_pruned_headsÚreturnc                 óT  ‡— t        j                  ||«      }t        | «      |z
  } | D ]  Š‰t        ˆfd„|D «       «      z  Šd|‰<   Œ  |j	                  d«      j                  «       j                  d«      }t        j                  t        |«      «      |   j                  «       }| |fS )al  Return the set of pruneable heads and their index mask for weight pruning.

    Copied from transformers.pytorch_utils.find_pruneable_heads_and_indices (removed from public API in transformers
    v5.0).
    Source: https://github.com/huggingface/transformers/blob/v4.49.0/src/transformers/pytorch_utils.py#L127
    MAINTENANCE: if this function is moved to another module or deleted, update the
    "Copyright 2022 The HuggingFace Team" line in the file header accordingly.

    Args:
        heads: Indices of heads to prune.
        n_heads: Total number of heads in the layer.
        head_size: Size of each attention head.
        already_pruned_heads: Heads that have already been pruned.

    Returns:
        A tuple of (heads, index) where heads is the adjusted set of head indices and index is a LongTensor boolean mask
        selecting the remaining weights.
    c              3   ó0   •K  — | ]  }|‰k  rd nd–— Œ y­w)é   r   N© )Ú.0ÚhÚheads     €ú{/var/www/ramen.bs-engineer-server.com/venv/lib/python3.12/site-packages/rfdetr/models/backbone/dinov2_with_windowed_attn.pyú	<genexpr>z4_find_pruneable_heads_and_indices.<locals>.<genexpr>W   s   øè ø€ ÒG¨Q˜˜Tš‘A qÓ(ÑGùs   ƒr   éÿÿÿÿr#   )
ÚtorchÚonesÚsetÚsumÚviewÚ
contiguousÚeqÚarangeÚlenÚlong)r   r   r   r   ÚmaskÚindexr'   s         @r(   Ú!_find_pruneable_heads_and_indicesr7   ?   sŸ   ø€ ô* �:‰:�g˜yÓ)€DÜ�‹JÐ-Ñ-€EØò ˆØ”ÓGÐ2FÔGÓGÑGˆØˆˆTŠ
ðð �9‰9�R‹=×#Ñ#Ó%×(Ñ(¨Ó+€DÜ�L‰Lœ˜T›Ó# DÑ)×.Ñ.Ó0€EØ�%ˆ<Ðó    Úout_featuresÚout_indices.Ústage_namesc                 óÐ   — |€| €t        |«      dz
  g}|d   g} | |fS |€$| �"| D �cg c]  }|j                  |«      ‘Œ }}| |fS | €|�|D �cg c]  }||   ‘Œ	 } }| |fS c c}w c c}w )Nr#   r*   )r3   r6   )r9   r:   r;   ÚlayerÚidxs        r(   Ú%_align_output_features_output_indicesr?   ^   s«   € ð
 Ð˜|Ð3Ü˜;Ó'¨!Ñ+Ð,ˆØ# B™Ð(ˆð
 ˜Ð$Ð$ð	 
Ð	 Ð!9Ø=IÖJ°E�{×(Ñ(¨Õ/ÐJˆÐJð ˜Ð$Ð$ð 
Ð	 +Ð"9Ø4?Ö@¨S˜ CÓ(Ð@ˆÐ@Ø˜Ð$Ð$ùò Kùâ@s   ¦AÁA#c                 óJ   — |�t        |«      nd}t        | ||¬«      \  } }| |fS )a¸  Align out_features and out_indices against stage_names, filling in defaults when either is None.

    Copied from transformers.utils.backbone_utils.get_aligned_output_features_output_indices (removed from public API in
    transformers v5.0).
    Source: https://github.com/huggingface/transformers/blob/v4.49.0/src/transformers/utils/backbone_utils.py#L30
    MAINTENANCE: if this function is moved to another module or deleted, update the
    "Copyright 2023 The HuggingFace Inc. team" line in the file header accordingly.

    Args:
        out_features: Names of the backbone stages to return features from, or None to derive from out_indices.
        out_indices: Integer indices of the stages to return features from, or None to derive from out_features.
        stage_names: Ordered list of all stage names defined by the backbone config.

    Returns:
        A tuple of (out_features, out_indices) with both fields populated consistently.
    N©r9   r:   r;   )Úlistr?   rA   s      r(   Ú+_get_aligned_output_features_output_indicesrC   m   s8   € ð* (3Ð'>”$�{Ô#ÀD€KÜ EØ!¨{Èô!Ñ€L�+ð ˜Ð$Ð$r8   Ú!WindowedDinov2WithRegistersConfigc                   óX   ‡ — e Zd ZdZdZ	 	 	 	 	 	 	 	 	 	 	 	 	 	 	 	 	 	 	 	 	 	 	 	 dˆ fd„	Zˆ xZS )rD   aS  
    This is the configuration class to store the configuration of a [`Dinov2WithRegistersModel`].
    It is used to instantiate a Dinov2WithRegisters model according to the specified arguments,
    defining the model architecture. Instantiating a configuration with the defaults will yield a
    similar configuration to that of the DINOv2 with Registers
    [facebook/dinov2-with-registers-base](https://huggingface.co/facebook/dinov2-with-registers-base) architecture.

    Configuration objects inherit from [`PretrainedConfig`] and can be used to control the model outputs. Read the
    documentation from [`PretrainedConfig`] for more information.

    Args:
        hidden_size (`int`, *optional*, defaults to 768):
            Dimensionality of the encoder layers and the pooler layer.
        num_hidden_layers (`int`, *optional*, defaults to 12):
            Number of hidden layers in the Transformer encoder.
        num_attention_heads (`int`, *optional*, defaults to 12):
            Number of attention heads for each attention layer in the Transformer encoder.
        mlp_ratio (`int`, *optional*, defaults to 4):
            Ratio of the hidden size of the MLPs relative to the `hidden_size`.
        hidden_act (`str` or `function`, *optional*, defaults to `"gelu"`):
            The non-linear activation function (function or string) in the encoder and pooler. If string, `"gelu"`,
            `"relu"`, `"selu"` and `"gelu_new"` are supported.
        hidden_dropout_prob (`float`, *optional*, defaults to 0.0):
            The dropout probability for all fully connected layers in the embeddings, encoder, and pooler.
        attention_probs_dropout_prob (`float`, *optional*, defaults to 0.0):
            The dropout ratio for the attention probabilities.
        initializer_range (`float`, *optional*, defaults to 0.02):
            The standard deviation of the truncated_normal_initializer for initializing all weight matrices.
        layer_norm_eps (`float`, *optional*, defaults to 1e-06):
            The epsilon used by the layer normalization layers.
        image_size (`int`, *optional*, defaults to 224):
            The size (resolution) of each image.
        patch_size (`int`, *optional*, defaults to 16):
            The size (resolution) of each patch.
        num_channels (`int`, *optional*, defaults to 3):
            The number of input channels.
        qkv_bias (`bool`, *optional*, defaults to `True`):
            Whether to add a bias to the queries, keys and values.
        layerscale_value (`float`, *optional*, defaults to 1.0):
           Initial value to use for layer scale.
        drop_path_rate (`float`, *optional*, defaults to 0.0):
            Stochastic depth rate per sample (when applied in the main path of residual layers).
        use_swiglu_ffn (`bool`, *optional*, defaults to `False`):
            Whether to use the SwiGLU feedforward neural network.
        num_register_tokens (`int`, *optional*, defaults to 4):
            Number of register tokens to use.
        out_features (`List[str]`, *optional*):
            If used as backbone, list of features to output. Can be any of `"stem"`, `"stage1"`, `"stage2"`, etc.
            (depending on how many stages the model has). If unset and `out_indices` is set, will default to the
            corresponding stages. If unset and `out_indices` is unset, will default to the last stage. Must be in the
            same order as defined in the `stage_names` attribute.
        out_indices (`List[int]`, *optional*):
            If used as backbone, list of indices of features to output. Can be any of 0, 1, 2, etc. (depending on how
            many stages the model has). If unset and `out_features` is set, will default to the corresponding stages.
            If unset and `out_features` is unset, will default to the last stage. Must be in the
            same order as defined in the `stage_names` attribute.
        apply_layernorm (`bool`, *optional*, defaults to `True`):
            Whether to apply layer normalization to the feature maps in case the model is used as backbone.
        reshape_hidden_states (`bool`, *optional*, defaults to `True`):
            Whether to reshape the feature maps to 4D tensors of shape `(batch_size, hidden_size, height, width)` in
            case the model is used as backbone. If `False`, the feature maps will be 3D tensors of shape `(batch_size,
            seq_len, hidden_size)`.

    Example:

    >>> from rfdetr.models.backbone.dinov2_with_windowed_attn import WindowedDinov2WithRegistersConfig

    >>> # Initializing a tiny configuration suitable for doctests
    >>> configuration = WindowedDinov2WithRegistersConfig(
    ...     image_size=32,
    ...     patch_size=16,
    ...     hidden_size=32,
    ...     num_hidden_layers=2,
    ...     num_attention_heads=4,
    ...     num_register_tokens=2,
    ... )

    >>> configuration.hidden_size
    32

    Údinov2_with_registersc                 ó*  •— t        ‰| �  di |¤Ž || _        || _        || _        || _        || _        || _        || _        || _	        |	| _
        |
| _        || _        || _        || _        || _        || _        || _        || _        dgt'        d|dz   «      D �cg c]  }d|› �‘Œ	 c}z   | _        t+        ||| j(                  ¬«      \  | _        | _        || _        || _        || _        |€t7        t'        |«      «      n|| _        || _        y c c}w )NÚstemr#   ÚstagerA   r$   )ÚsuperÚ__init__Úhidden_sizeÚnum_hidden_layersÚnum_attention_headsÚ	mlp_ratioÚ
hidden_actÚhidden_dropout_probÚattention_probs_dropout_probÚinitializer_rangeÚlayer_norm_epsÚ
image_sizeÚ
patch_sizeÚnum_channelsÚqkv_biasÚlayerscale_valueÚdrop_path_rateÚuse_swiglu_ffnÚnum_register_tokensÚranger;   rC   Ú_out_featuresÚ_out_indicesÚapply_layernormÚreshape_hidden_statesÚnum_windowsrB   Úwindow_block_indexesÚgradient_checkpointing)ÚselfrL   rM   rN   rO   rP   rQ   rR   rS   rT   rU   rV   rW   rX   rY   rZ   r[   r\   r9   r:   r`   ra   rb   rc   rd   Úkwargsr>   Ú	__class__s                              €r(   rK   z*WindowedDinov2WithRegistersConfig.__init__â   s0  ø€ ô8 	‰ÑÑ"˜6Ò"à&ˆÔØ!2ˆÔØ#6ˆÔ Ø"ˆŒØ$ˆŒØ#6ˆÔ Ø,HˆÔ)Ø!2ˆÔØ,ˆÔØ$ˆŒØ$ˆŒØ(ˆÔØ ˆŒØ 0ˆÔØ,ˆÔØ,ˆÔØ#6ˆÔ Ø"˜8ÄÀaÐIZÐ]^ÑI^Ó@_Ö&`¸¨¨s¨e¢}Ò&`Ñ`ˆÔÜ0[Ø%°;ÈD×L\ÑL\ô1
Ñ-ˆÔ˜DÔ-ð  /ˆÔØ%:ˆÔ"Ø&ˆÔà.BÐ.JŒD”Ð(Ó)Ô*ÐPdð 	Ô!ð '=ˆÕ#ùò 'as   ÂD)i   é   rh   é   Úgeluç        rk   g{®Gáz”?g�íµ ÷Æ°>éà   é   é   Tç      ð?rk   Fri   NNTTr#   NF)Ú__name__Ú
__module__Ú__qualname__Ú__doc__Ú
model_typerK   Ú__classcell__©rg   s   @r(   rD   rD   �   se   ø„ ñPðd )€Jð ØØØØØØ%(ØØØØØØØØØØØØØØ"ØØ!Ø$÷39=ñ 9=r8   c                   óZ   ‡ — e Zd ZdZˆ fd„Zdej                  dej                  fd„Zˆ xZS )Ú"Dinov2WithRegistersPatchEmbeddingszâ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  }|| _        || _        || _        || _
        t        j                  ||||¬«      | _        y )Nr#   r   )Úkernel_sizeÚstride)rJ   rK   rU   rV   rW   rL   Ú
isinstanceÚcollectionsÚabcÚIterableÚnum_patchesr	   ÚConv2dÚ
projection)re   ÚconfigrU   rV   rW   rL   r€   rg   s          €r(   rK   z+Dinov2WithRegistersPatchEmbeddings.__init__#  sÔ   ø€ Ü‰ÑÔØ!'×!2Ñ!2°F×4EÑ4E�Jˆ
Ø$*×$7Ñ$7¸×9KÑ9K�kˆä#-¨j¼+¿/¹/×:RÑ:RÔ#S‘ZÐZdÐfpÐYqˆ
Ü#-¨j¼+¿/¹/×:RÑ:RÔ#S‘ZÐZdÐfpÐYqˆ
Ø! !‘}¨
°1©Ñ5¸*ÀQ¹-È:ÐVWÉ=Ñ:XÑYˆØ$ˆŒØ$ˆŒØ(ˆÔØ&ˆÔäŸ)™) L°+È:Ð^hÔiˆ�r8   Úpixel_valuesr    c                 óÚ   — |j                   d   }|| j                  k7  rt        d| j                  › d|› d�«      ‚| j                  |«      j	                  d«      j                  dd«      }|S )Nr#   zoMake sure that the channel dimension of the pixel values match with the one set in the configuration. Expected z	 but got ú.é   )ÚshaperW   Ú
ValueErrorr‚   ÚflattenÚ	transpose)re   r„   rW   Ú
embeddingss       r(   Úforwardz*Dinov2WithRegistersPatchEmbeddings.forward2  sz   € Ø#×)Ñ)¨!Ñ,ˆØ˜4×,Ñ,Ò,ÜðØ!×.Ñ.Ð/¨y¸¸ÀaðIóð ð —_‘_ \Ó2×:Ñ:¸1Ó=×GÑGÈÈ1ÓMˆ
ØÐr8   )	rp   rq   rr   rs   rK   r+   ÚTensorr�   ru   rv   s   @r(   rx   rx     s)   ø„ ñôjð E§L¡Lð °U·\±\÷ r8   rx   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d
ej                  de
ej                     dej                  fd„Zˆ xZS )Ú%WindowedDinov2WithRegistersEmbeddingszTConstruct the CLS token, mask token, register tokens, position and patch embeddings.rƒ   r    Nc                 óè  •— t         ‰| �  «        t        j                  t	        j
                  dd|j                  «      «      | _        t        j                  t	        j                  d|j                  «      «      | _	        |j                  dkD  r>t        j                  t	        j                  d|j                  |j                  «      «      nd | _        t        |«      | _        | j                  j                  }t        j                  t	        j
                  d|dz   |j                  «      «      | _        t        j                   |j"                  «      | _        |j&                  | _        || _        y )Nr#   r   )rJ   rK   r	   Ú	Parameterr+   ÚrandnrL   Ú	cls_tokenÚzerosÚ
mask_tokenr\   Úregister_tokensrx   Úpatch_embeddingsr€   Úposition_embeddingsÚDropoutrQ   ÚdropoutrV   rƒ   )re   rƒ   r€   rg   s      €r(   rK   z.WindowedDinov2WithRegistersEmbeddings.__init__@  s  ø€ Ü‰ÑÔäŸ™¤e§k¡k°!°Q¸×8JÑ8JÓ&KÓLˆŒÜŸ,™,¤u§{¡{°1°f×6HÑ6HÓ'IÓJˆŒð ×)Ñ)¨AÒ-ô �L‰LœŸ™ Q¨×(BÑ(BÀF×DVÑDVÓWÔXàð 	Ôô
 !CÀ6Ó JˆÔØ×+Ñ+×7Ñ7ˆÜ#%§<¡<´·±¸A¸{ÈQ¹ÐPV×PbÑPbÓ0cÓ#dˆÔ Ü—z‘z &×"<Ñ"<Ó=ˆŒØ ×+Ñ+ˆŒØˆ�r8   rŒ   ÚheightÚwidthc                 ón  — |j                   d   dz
  }| j                  j                   d   dz
  }t        j                  j	                  «       s||k(  r||k(  r| j                  S | j                  dd…df   }| j                  dd…dd…f   }|j                   d   }|| j
                  j                  z  }|| j
                  j                  z  }t        |dz  «      }	|j                  d|	|	|«      }|j                  dddd«      }|j                  }
t        j                  j                  |j                  t        j                  ¬«      t        |«      t        |«      fd	d
|j                   j"                  dk7  ¬«      j                  |
¬«      }t        j                  j	                  «       sAt%        |«      |j                   d   k7  st%        |«      |j                   d   k7  rt'        d«      ‚|j                  dddd«      j)                  dd|«      }t        j*                  |j-                  d«      |fd¬«      S )aß  This method allows to interpolate the pre-trained position encodings, to be able to use the model on higher
        resolution images. This implementation supports torch.jit tracing while maintaining backwards compatibility with
        the original implementation.

        Adapted from:
        - https://github.com/facebookresearch/dino/blob/main/vision_transformer.py
        - https://github.com/facebookresearch/dinov2/blob/main/dinov2/models/vision_transformer.py
        r#   Nr   r*   g      à?rn   r‡   ©ÚdtypeÚbicubicFÚmps)ÚsizeÚmodeÚalign_cornersÚ	antialiaséþÿÿÿzHWidth or height does not match with the interpolated position embeddings©Údim)rˆ   r™   r+   ÚjitÚ
is_tracingrƒ   rV   r   ÚreshapeÚpermuter    r	   Ú
functionalÚinterpolateÚtoÚfloat32ÚdeviceÚtypeÚintr‰   r/   ÚcatÚ	unsqueeze)re   rŒ   rœ   r�   r€   Únum_positionsÚclass_pos_embedÚpatch_pos_embedr©   Úsqrt_num_positionsÚtarget_dtypes              r(   Úinterpolate_pos_encodingz>WindowedDinov2WithRegistersEmbeddings.interpolate_pos_encodingQ  s  € ð !×&Ñ& qÑ)¨AÑ-ˆØ×0Ñ0×6Ñ6°qÑ9¸AÑ=ˆô �y‰y×#Ñ#Ô%¨+¸Ò*FÈ6ÐUZÊ?Ø×+Ñ+Ð+ð ×2Ñ2²1°a°4Ñ8ˆØ×2Ñ2²1°a±b°5Ñ9ˆØ×Ñ˜rÑ"ˆð ˜4Ÿ;™;×1Ñ1Ñ1ˆØ˜Ÿ™×/Ñ/Ñ/ˆô ' }°cÑ'9Ó:ÐØ)×1Ñ1°!Ð5GÐI[Ð]`ÓaˆØ)×1Ñ1°!°Q¸¸1Ó=ˆð '×,Ñ,ˆô Ÿ-™-×3Ñ3Ø×Ñ¤U§]¡]ÐÓ3Ü˜FÓ#¤Y¨uÓ%5Ð6ØØØ%×,Ñ,×1Ñ1°UÑ:ð 4ó 
÷ ‰"�<ˆ"Ó
 ð 	ô �y‰y×#Ñ#Ô%Ü�6‹{˜o×3Ñ3°BÑ7Ò7¼3¸u»:È×I^ÑI^Ð_aÑIbÒ;bÜ Ð!kÓlÐlð *×1Ñ1°!°Q¸¸1Ó=×BÑBÀ1ÀbÈ#ÓNˆô �y‰y˜/×3Ñ3°AÓ6¸ÐHÈaÔPÐPr8   r„   Úbool_masked_posc                 óN  — |j                   \  }}}}| j                  | j                  j                  z  }||z  dk7  s||z  dk7  r9t	        d| j                  › d| j                  j                  › d|› d|› d|› d�«      ‚| j
                  j                  j                  j                  }| j                  |j                  |¬«      «      }	|�Xt        j                  |j                  d
«      | j                  j                  |	j                  «      j                  d«      |	«      }	| j                  j                  |d
d
«      }
t        j                   |
|	fd¬«      }	|	| j#                  |	||«      z   }	| j                  j                  dkD  �r|| j                  j                  z  }|| j                  j                  z  }|	d	d	…d	d…f   }|	d	d	…dd	…f   }|j%                  |||d
«      }|| j                  j                  z  }|| j                  j                  z  }| j                  j                  }|j'                  ||z  |||d
«      }|j)                  ddddd«      }|j'                  ||dz  z  ||z  d
«      }|j+                  |dz  dd«      }t        j                   ||fd¬«      }	| j                  j,                  dkD  rTt        j                   |	d	d	…d	d…f   | j.                  j                  |	j                   d   d
d
«      |	d	d	…dd	…f   fd¬«      n|	}	| j1                  |	«      }	|	S )a"  Compute windowed patch embeddings for the given pixel values.

        Args:
            pixel_values: Image tensor of shape ``(B, C, H, W)``. Both ``H`` and
                ``W`` must be divisible by ``patch_size * num_windows``.
            bool_masked_pos: Optional boolean mask of shape ``(B, num_patches)``.
                Masked positions are replaced with the learnable ``mask_token``.

        Returns:
            Patch embedding tensor. When ``num_windows > 1`` the batch dimension is expanded to ``B * num_windows ** 2``
            and the sequence length corresponds to patches within a single window (plus CLS token and any register
            tokens).

        Raises:
            ValueError: If ``H`` or ``W`` is not divisible by
                ``patch_size * num_windows``.
        r   zHInput spatial dimensions must be divisible by patch_size * num_windows (z * z = z), but got height=z, width=r†   rŸ   Nr*   r#   r¨   r‡   rn   ri   )rˆ   rV   rƒ   rb   r‰   r˜   r‚   Úweightr    r°   r+   Úwherer¶   r–   r”   Úexpandrµ   r¼   r/   r¬   r­   Úrepeatr\   r—   r›   )re   r„   r½   Ú
batch_sizeÚ_rœ   r�   Údivisorr»   rŒ   Ú
cls_tokensÚnum_h_patchesÚnum_w_patchesÚcls_token_with_pos_embedÚpixel_tokens_with_pos_embedÚnum_w_patches_per_windowÚnum_h_patches_per_windowrb   Úwindowed_pixel_tokensÚ!windowed_cls_token_with_pos_embeds                       r(   r�   z-WindowedDinov2WithRegistersEmbeddings.forward†  sA  € ð$ (4×'9Ñ'9Ñ$ˆ
�A�v˜uØ—/‘/ D§K¡K×$;Ñ$;Ñ;ˆØ�GÑ˜qÒ  E¨G¡O°qÒ$8ÜðØ—O‘OÐ$ C¨¯©×(?Ñ(?Ð'@ÀÀGÀ9ð M"Ø"( ¨°%°¸ð;óð ð
 ×,Ñ,×7Ñ7×>Ñ>×DÑDˆØ×*Ñ*¨<¯?©?À¨?Ó+NÓOˆ
àÐ&ÜŸ™Ø×)Ñ)¨"Ó-¨t¯©×/AÑ/AÀ*×BRÑBRÓ/S×/]Ñ/]Ð^_Ó/`ÐblóˆJð
 —^‘^×*Ñ*¨:°r¸2Ó>ˆ
Ü—Y‘Y 
¨JÐ7¸QÔ?ˆ
ð   $×"?Ñ"?À
ÈFÐTYÓ"ZÑZˆ
à�;‰;×"Ñ" QÓ&à" d§k¡k×&<Ñ&<Ñ<ˆMØ! T§[¡[×%;Ñ%;Ñ;ˆMØ'1²!°R°a°R°%Ñ'8Ð$Ø*4²Q¸¹°UÑ*;Ð'Ø*E×*JÑ*JÈ:ÐWdÐfsÐuwÓ*xÐ'Ø'4¸¿¹×8OÑ8OÑ'OÐ$Ø'4¸¿¹×8OÑ8OÑ'OÐ$ØŸ+™+×1Ñ1ˆKØ$?×$GÑ$GØ˜[Ñ(Ð*BÀKÐQiÐkmó%Ð!ð %:×$AÑ$AÀ!ÀQÈÈ1ÈaÓ$PÐ!Ø$9×$AÑ$AØ˜[¨!™^Ñ+Ð-EÐH`Ñ-`Ðbdó%Ð!ð 1I×0OÑ0OÐP[Ð]^ÑP^Ð`aÐcdÓ0eÐ-ÜŸ™Ð$EÐG\Ð#]ÐcdÔeˆJð �{‰{×.Ñ.°Ò2ô �I‰IØšA˜r ˜r˜EÑ" D×$8Ñ$8×$?Ñ$?À
×@PÑ@PÐQRÑ@SÐUWÐY[Ó$\Ð^hÒijÐlmÑlnÐinÑ^oÐpÐvwõð ð 	ð —\‘\ *Ó-ˆ
àÐr8   ©N)rp   rq   rr   rs   rD   rK   r+   rŽ   r´   r¼   r   r�   ru   rv   s   @r(   r�   r�   =  s   ø„ Ù^ðÐ@ð ÀTõ ð"3Q°5·<±<ð 3QÈð 3QÐUXð 3QÐ]b×]iÑ]ió 3QñjH E§L¡Lð HÀ8ÈEÏLÉLÑCYð HÐej×eqÑeq÷ Hr8   r�   c            
       óâ   ‡ — e Zd Zdeddfˆ fd„Zdej                  dej                  fd„Z	 d
dej                  dede	e
ej                  ej                  f   e
ej                     f   fd	„Zˆ xZS )Ú Dinov2WithRegistersSelfAttentionrƒ   r    Nc                 ó  •— t         ‰| �  «        |j                  |j                  z  dk7  r3t	        |d«      s't        d|j                  f› d|j                  › d�«      ‚|j                  | _        t        |j                  |j                  z  «      | _        | j                  | j                  z  | _        t        j                  |j                  | j                  |j                  ¬«      | _        t        j                  |j                  | j                  |j                  ¬«      | _        t        j                  |j                  | j                  |j                  ¬«      | _        t        j                  |j                   «      | _        y )Nr   Úembedding_sizezThe hidden size z4 is not a multiple of the number of attention heads r†   ©Úbias)rJ   rK   rL   rN   Úhasattrr‰   r´   Úattention_head_sizeÚall_head_sizer	   ÚLinearrX   ÚqueryÚkeyÚvaluerš   rR   r›   ©re   rƒ   rg   s     €r(   rK   z)Dinov2WithRegistersSelfAttention.__init__Ò  s1  ø€ Ü‰ÑÔØ×Ñ × :Ñ :Ñ:¸aÒ?ÌÐPVÐXhÔHiÜØ" F×$6Ñ$6Ð#8Ð"9ð :Ø×3Ñ3Ð4°Að7óð ð
 $*×#=Ñ#=ˆÔ Ü#& v×'9Ñ'9¸F×<VÑ<VÑ'VÓ#WˆÔ Ø!×5Ñ5¸×8PÑ8PÑPˆÔä—Y‘Y˜v×1Ñ1°4×3EÑ3EÈFÏOÉOÔ\ˆŒ
Ü—9‘9˜V×/Ñ/°×1CÑ1CÈ&Ï/É/ÔZˆŒÜ—Y‘Y˜v×1Ñ1°4×3EÑ3EÈFÏOÉOÔ\ˆŒ
ä—z‘z &×"EÑ"EÓFˆ�r8   Úxc                 ó¤   — |j                  «       d d | j                  | j                  fz   }|j                  |«      }|j	                  dddd«      S )Nr*   r   r‡   r#   rn   )r£   rN   r×   r/   r­   )re   rÞ   Únew_x_shapes      r(   Útranspose_for_scoresz5Dinov2WithRegistersSelfAttention.transpose_for_scoresä  sL   € Ø—f‘f“h˜s �m t×'?Ñ'?À×AYÑAYÐ&ZÑZˆØ�F‰F�;ÓˆØ�y‰y˜˜A˜q !Ó$Ð$r8   Úhidden_statesÚoutput_attentionsc                 ó¨  — | j                  |«      }| j                  | j                  |«      «      }| j                  | j                  |«      «      }| j                  |«      }t	        j
                  ||j                  dd«      «      }|t        j                  | j                  «      z  }t        j                  j                  |d¬«      }| j                  |«      }t	        j
                  ||«      }	|	j                  dddd«      j                  «       }	|	j!                  «       d d | j"                  fz   }
|	j%                  |
«      }	|r|	|f}|S |	f}|S )Nr*   r§   r¨   r   r‡   r#   rn   )rÚ   rá   rÛ   rÜ   r+   Úmatmulr‹   ÚmathÚsqrtr×   r	   r®   Úsoftmaxr›   r­   r0   r£   rØ   r/   )re   râ   rã   Úmixed_query_layerÚ	key_layerÚvalue_layerÚquery_layerÚattention_scoresÚattention_probsÚcontext_layerÚnew_context_layer_shapeÚoutputss               r(   r�   z(Dinov2WithRegistersSelfAttention.forwardé  sB  € ð !ŸJ™J }Ó5Ðà×-Ñ-¨d¯h©h°}Ó.EÓFˆ	Ø×/Ñ/°·
±
¸=Ó0IÓJˆØ×/Ñ/Ð0AÓBˆô !Ÿ<™<¨°Y×5HÑ5HÈÈRÓ5PÓQÐà+¬d¯i©i¸×8PÑ8PÓ.QÑQÐô Ÿ-™-×/Ñ/Ð0@ÀbÐ/ÓIˆð Ÿ,™, Ó7ˆäŸ™ _°kÓBˆà%×-Ñ-¨a°°A°qÓ9×DÑDÓFˆØ"/×"4Ñ"4Ó"6°s¸Ð";¸t×?QÑ?QÐ>SÑ"SÐØ%×*Ñ*Ð+BÓCˆá6G�= /Ð2ˆàˆð O\ÐM]ˆàˆr8   ©F)rp   rq   rr   rD   rK   r+   rŽ   rá   Úboolr   r   r�   ru   rv   s   @r(   rÑ   rÑ   Ñ  s‚   ø„ ðGÐ@ð GÀTõ Gð$% e§l¡lð %°u·|±|ó %ð FKñ!Ø"Ÿ\™\ð!Ø>Bð!à	ˆu�U—\‘\ 5§<¡<Ð/Ñ0°%¸¿¹Ñ2EÐEÑ	F÷!r8   rÑ   c            
       ó®   ‡ — e Zd Zdeddfˆ fd„Z	 ddej                  dedee	ej                  ej                  f   e	ej                     f   fˆ fd„Z
ˆ xZS )	Ú$Dinov2WithRegistersSdpaSelfAttentionrƒ   r    Nc                 óF   •— t         ‰| �  |«       |j                  | _        y rÏ   )rJ   rK   rR   rÝ   s     €r(   rK   z-Dinov2WithRegistersSdpaSelfAttention.__init__  s   ø€ Ü‰Ñ˜Ô Ø,2×,OÑ,OˆÕ)r8   râ   rã   c           	      óX  •— |r&t         j                  d«       t        ‰	| �  ||¬«      S | j	                  |«      }| j                  | j                  |«      «      }| j                  | j                  |«      «      }| j                  |«      }t        j                  j                  j                  |||d | j                  r| j                  nddd ¬«      }|j                  dddd	«      j                  «       }|j!                  «       d d
 | j"                  fz   }|j%                  |«      }|d fS )Nah  Dinov2WithRegistersModel is using Dinov2WithRegistersSdpaSelfAttention, but `torch.nn.functional.scaled_dot_product_attention` does not support `output_attentions=True`. Falling back to the manual attention implementation. To avoid this fallback, call `model.set_attn_implementation('eager')` or pass `attn_implementation="eager"` when instantiating the model.)râ   rã   rk   F)Ú	is_causalÚscaler   r‡   r#   rn   r§   )ÚloggerÚwarning_oncerJ   r�   rÚ   rá   rÛ   rÜ   r+   r	   r®   Úscaled_dot_product_attentionÚtrainingrR   r­   r0   r£   rØ   r/   )
re   râ   rã   ré   rê   rë   rì   rï   rð   rg   s
            €r(   r�   z,Dinov2WithRegistersSdpaSelfAttention.forward  s(  ø€ ñ Ü×ÑðVôô ‘7‘?°ÐRc�?ÓdÐdà ŸJ™J }Ó5Ðà×-Ñ-¨d¯h©h°}Ó.EÓFˆ	Ø×/Ñ/°·
±
¸=Ó0IÓJˆØ×/Ñ/Ð0AÓBˆäŸ™×+Ñ+×HÑHØØØØØ15·²ˆD×-Ò-ÀCØØð Ió 
ˆð &×-Ñ-¨a°°A°qÓ9×DÑDÓFˆØ"/×"4Ñ"4Ó"6°s¸Ð";¸t×?QÑ?QÐ>SÑ"SÐØ%×*Ñ*Ð+BÓCˆà˜dÐ"Ð"r8   rò   )rp   rq   rr   rD   rK   r+   rŽ   ró   r   r   r�   ru   rv   s   @r(   rõ   rõ     sl   ø„ ðPÐ@ð PÀTõ Pð
 FKñ!#Ø"Ÿ\™\ð!#Ø>Bð!#à	ˆu�U—\‘\ 5§<¡<Ð/Ñ0°%¸¿¹Ñ2EÐEÑ	F÷!#ñ !#r8   rõ   c                   ó|   ‡ — e Zd ZdZdeddfˆ fd„Zdej                  dej                  dej                  fd„Zˆ xZ	S )	ÚDinov2WithRegistersSelfOutputz¦The residual connection is defined in Dinov2WithRegistersLayer instead of here (as is the case with other
    models), due to the layernorm applied before each block.rƒ   r    Nc                 óÈ   •— t         ‰| �  «        t        j                  |j                  |j                  «      | _        t        j                  |j                  «      | _        y rÏ   )	rJ   rK   r	   rÙ   rL   Údenserš   rQ   r›   rÝ   s     €r(   rK   z&Dinov2WithRegistersSelfOutput.__init__:  sB   ø€ Ü‰ÑÔÜ—Y‘Y˜v×1Ñ1°6×3EÑ3EÓFˆŒ
Ü—z‘z &×"<Ñ"<Ó=ˆ�r8   râ   Úinput_tensorc                 óJ   — | j                  |«      }| j                  |«      }|S rÏ   )r  r›   )re   râ   r  s      r(   r�   z%Dinov2WithRegistersSelfOutput.forward?  s$   € ØŸ
™
 =Ó1ˆØŸ™ ]Ó3ˆàÐr8   )
rp   rq   rr   rs   rD   rK   r+   rŽ   r�   ru   rv   s   @r(   rÿ   rÿ   6  sF   ø„ ñ@ð>Ð@ð >ÀTõ >ð
 U§\¡\ð ÀÇÁð ÐRW×R^ÑR^÷ r8   rÿ   c            
       óÀ   ‡ — e Zd Zdeddfˆ fd„Zdee   ddfd„Z	 d
dej                  de
deeej                  ej                  f   eej                     f   fd	„Zˆ xZS )ÚDinov2WithRegistersAttentionrƒ   r    Nc                 ó€   •— t         ‰| �  «        t        |«      | _        t	        |«      | _        t        «       | _        y rÏ   )rJ   rK   rÑ   Ú	attentionrÿ   Úoutputr-   Úpruned_headsrÝ   s     €r(   rK   z%Dinov2WithRegistersAttention.__init__G  s0   ø€ Ü‰ÑÔÜ9¸&ÓAˆŒÜ3°FÓ;ˆŒÜ›EˆÕr8   r   c                 ó>  — t        |«      dk(  ry t        || j                  j                  | j                  j                  | j
                  «      \  }}t        | j                  j                  |«      | j                  _        t        | j                  j                  |«      | j                  _        t        | j                  j                  |«      | j                  _	        t        | j                  j                  |d¬«      | j                  _        | j                  j                  t        |«      z
  | j                  _        | j                  j                  | j                  j                  z  | j                  _        | j
                  j                  |«      | _        y )Nr   r#   r¨   )r3   r7   r  rN   r×   r	  r   rÚ   rÛ   rÜ   r  r  rØ   Úunion)re   r   r6   s      r(   Úprune_headsz(Dinov2WithRegistersAttention.prune_headsM  s  € Üˆu‹:˜Š?ØÜ8Ø�4—>‘>×5Ñ5°t·~±~×7YÑ7YÐ[_×[lÑ[ló
‰ˆˆuô
  2°$·.±.×2FÑ2FÈÓNˆ�‰ÔÜ/°·±×0BÑ0BÀEÓJˆ�‰ÔÜ1°$·.±.×2FÑ2FÈÓNˆ�‰ÔÜ.¨t¯{©{×/@Ñ/@À%ÈQÔOˆ�‰Ôð .2¯^©^×-OÑ-OÔRUÐV[ÓR\Ñ-\ˆ�‰Ô*Ø'+§~¡~×'IÑ'IÈDÏNÉN×LnÑLnÑ'nˆ�‰Ô$Ø ×-Ñ-×3Ñ3°EÓ:ˆÕr8   râ   rã   c                 óf   — | j                  ||«      }| j                  |d   |«      }|f|dd  z   }|S )Nr   r#   )r  r  )re   râ   rã   Úself_outputsÚattention_outputrñ   s         r(   r�   z$Dinov2WithRegistersAttention.forward_  sC   € ð
 —~‘~ mÐ5FÓGˆàŸ;™; |°A¡¸ÓFÐà#Ð%¨°Q°RÐ(8Ñ8ˆØˆr8   rò   )rp   rq   rr   rD   rK   r   r´   r  r+   rŽ   ró   r   r   r�   ru   rv   s   @r(   r  r  F  s}   ø„ ð"Ð@ð "ÀTõ "ð;  S¡ð ;¨dó ;ð* #(ñ
à—|‘|ð
ð  ð
ð 
ˆu�U—\‘\ 5§<¡<Ð/Ñ0°%¸¿¹Ñ2EÐEÑ	F÷	
r8   r  c                   ó(   ‡ — e Zd Zdeddfˆ fd„Zˆ xZS )Ú Dinov2WithRegistersSdpaAttentionrƒ   r    Nc                 óD   •— t         ‰| �  |«       t        |«      | _        y rÏ   )rJ   rK   rõ   r  rÝ   s     €r(   rK   z)Dinov2WithRegistersSdpaAttention.__init__m  s   ø€ Ü‰Ñ˜Ô Ü=¸fÓEˆ�r8   )rp   rq   rr   rD   rK   ru   rv   s   @r(   r  r  l  s    ø„ ðFÐ@ð FÀT÷ Fñ Fr8   r  c                   óX   ‡ — e Zd Zdˆ fd„Zdej
                  dej
                  fd„Zˆ xZS )ÚDinov2WithRegistersLayerScaler    c                 óª   •— t         ‰| �  «        t        j                  |j                  t        j                  |j                  «      z  «      | _        y rÏ   )	rJ   rK   r	   r’   rY   r+   r,   rL   Úlambda1rÝ   s     €r(   rK   z&Dinov2WithRegistersLayerScale.__init__s  s8   ø€ Ü‰ÑÔÜ—|‘| F×$;Ñ$;¼e¿j¹jÈ×I[ÑI[Ó>\Ñ$\Ó]ˆ�r8   Úhidden_statec                 ó    — || j                   z  S rÏ   )r  ©re   r  s     r(   r�   z%Dinov2WithRegistersLayerScale.forwardw  s   € Ø˜dŸl™lÑ*Ð*r8   ©r    N©rp   rq   rr   rK   r+   rŽ   r�   ru   rv   s   @r(   r  r  r  s$   ø„ õ^ð+ E§L¡Lð +°U·\±\÷ +r8   r  ÚinputÚ	drop_probrý   c                 ó  — |dk(  s|s| S d|z
  }| j                   d   fd| j                  dz
  z  z   }|t        j                  || j                  | j
                  ¬«      z   }|j                  «        | j                  |«      |z  }|S )aA  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.
    rk   r#   r   )r#   )r    r²   )rˆ   Úndimr+   Úrandr    r²   Úfloor_Údiv)r  r  rý   Ú	keep_probrˆ   Úrandom_tensorr  s          r(   Ú	drop_pathr%  {  s�   € ð �CÒ™xØˆØ�I‘€IØ�[‰[˜‰^Ð ¨¯
©
°Q©Ñ 7Ñ7€EØ¤§
¡
¨5¸¿¹ÈEÏLÉLÔ YÑY€MØ×ÑÔØ�Y‰Y�yÓ! MÑ1€FØ€Mr8   c                   óx   ‡ — e Zd ZdZd	dee   ddfˆ fd„Zdej                  dej                  fd„Z	de
fd„Zˆ xZS )
ÚDinov2WithRegistersDropPathzXDrop paths (Stochastic Depth) per sample (when applied in main path of residual blocks).Nr  r    c                 ó0   •— t         ‰| �  «        || _        y rÏ   )rJ   rK   r  )re   r  rg   s     €r(   rK   z$Dinov2WithRegistersDropPath.__init__‘  s   ø€ Ü‰ÑÔØ"ˆ�r8   râ   c                 óD   — t        || j                  | j                  «      S rÏ   )r%  r  rý   )re   râ   s     r(   r�   z#Dinov2WithRegistersDropPath.forward•  s   € Ü˜¨¯©¸¿¹ÓFÐFr8   c                 ó8   — dj                  | j                  «      S )Nzp={})Úformatr  ©re   s    r(   Ú
extra_reprz&Dinov2WithRegistersDropPath.extra_repr˜  s   € Ø�}‰}˜TŸ^™^Ó,Ð,r8   rÏ   )rp   rq   rr   rs   r   ÚfloatrK   r+   rŽ   r�   Ústrr-  ru   rv   s   @r(   r'  r'  Ž  sG   ø„ Ùbñ# (¨5¡/ð #¸Tõ #ðG U§\¡\ð G°e·l±ló Gð-˜C÷ -r8   r'  c                   óX   ‡ — e Zd Zdˆ fd„Zdej
                  dej
                  fd„Zˆ xZS )ÚDinov2WithRegistersMLPr    c                 ó~  •— t         ‰| �  «        |j                  x}}t        |j                  |j                  z  «      }t        j                  ||d¬«      | _        t        |j                  t        «      rt        |j                     | _        n|j                  | _        t        j                  ||d¬«      | _        y )NTrÔ   )rJ   rK   rL   r´   rO   r	   rÙ   Úfc1r|   rP   r/  r   Ú
activationÚfc2©re   rƒ   Úin_featuresr9   Úhidden_featuresrg   s        €r(   rK   zDinov2WithRegistersMLP.__init__�  s�   ø€ Ü‰ÑÔØ%+×%7Ñ%7Ð7ˆ�lÜ˜f×0Ñ0°6×3CÑ3CÑCÓDˆÜ—9‘9˜[¨/ÀÔEˆŒÜ�f×'Ñ'¬Ô-Ü$ V×%6Ñ%6Ñ7ˆD�Oà$×/Ñ/ˆDŒOÜ—9‘9˜_¨lÀÔFˆ�r8   r  c                 ól   — | j                  |«      }| j                  |«      }| j                  |«      }|S rÏ   )r3  r4  r5  r  s     r(   r�   zDinov2WithRegistersMLP.forward¨  s2   € Ø—x‘x Ó-ˆØ—‘ |Ó4ˆØ—x‘x Ó-ˆØÐr8   r  r  rv   s   @r(   r1  r1  œ  s$   ø„ õ	Gð E§L¡Lð °U·\±\÷ r8   r1  c                   óX   ‡ — e Zd Zdˆ fd„Zdej
                  dej
                  fd„Zˆ xZS )ÚDinov2WithRegistersSwiGLUFFNr    c                 ó0  •— t         ‰| �  «        |j                  x}}t        |j                  |j                  z  «      }t        |dz  dz  «      dz   dz  dz  }t        j                  |d|z  d¬«      | _        t        j                  ||d¬«      | _        y )Nr‡   rn   é   é   TrÔ   )	rJ   rK   rL   r´   rO   r	   rÙ   Ú
weights_inÚweights_outr6  s        €r(   rK   z%Dinov2WithRegistersSwiGLUFFN.__init__°  sŠ   ø€ Ü‰ÑÔØ%+×%7Ñ%7Ð7ˆ�lÜ˜f×0Ñ0°6×3CÑ3CÑCÓDˆÜ˜°Ñ2°QÑ6Ó7¸!Ñ;ÀÑAÀAÑEˆäŸ)™) K°°_Ñ1DÈ4ÔPˆŒÜŸ9™9 _°lÈÔNˆÕr8   r  c                 ó¶   — | j                  |«      }|j                  dd¬«      \  }}t        j                  j	                  |«      |z  }| j                  |«      S )Nr‡   r*   r¨   )r?  Úchunkr	   r®   Úsilur@  )re   r  Úx1Úx2Úhiddens        r(   r�   z$Dinov2WithRegistersSwiGLUFFN.forward¹  sS   € Ø—‘ |Ó4ˆØ×#Ñ# A¨2Ð#Ó.‰ˆˆBÜ—‘×#Ñ# BÓ'¨"Ñ,ˆØ×Ñ Ó'Ð'r8   r  r  rv   s   @r(   r;  r;  ¯  s$   ø„ õOð( E§L¡Lð (°U·\±\÷ (r8   r;  )ÚeagerÚsdpac                   ó´   ‡ — e Zd ZdZdeddfˆ fd„Z	 	 d
dej                  dedede	e
ej                  ej                  f   e
ej                     f   fd	„Zˆ xZS )Ú WindowedDinov2WithRegistersLayerzCThis corresponds to the Block class in the original implementation.rƒ   r    Nc                 óR  •— t         ‰| �  «        |j                  | _        t        j                  |j
                  |j                  ¬«      | _        t        |j                     |«      | _
        t        |«      | _        |j                  dkD  rt        |j                  «      nt        j                  «       | _        t        j                  |j
                  |j                  ¬«      | _        |j$                  rt'        |«      | _        nt+        |«      | _        t        |«      | _        y )N©Úepsrk   )rJ   rK   rb   r	   Ú	LayerNormrL   rT   Únorm1Ú'DINOV2_WITH_REGISTERS_ATTENTION_CLASSESÚ_attn_implementationr  r  Úlayer_scale1rZ   r'  ÚIdentityr%  Únorm2r[   r;  Úmlpr1  Úlayer_scale2rÝ   s     €r(   rK   z)WindowedDinov2WithRegistersLayer.__init__É  sÝ   ø€ Ü‰ÑÔà!×-Ñ-ˆÔä—\‘\ &×"4Ñ"4¸&×:OÑ:OÔPˆŒ
Ü@À×A\ÑA\Ñ]Ð^dÓeˆŒÜ9¸&ÓAˆÔàBH×BWÑBWÐZ]ÒB]Ô'¨×(=Ñ(=Ô>Ôce×cnÑcnÓcpð 	Œô —\‘\ &×"4Ñ"4¸&×:OÑ:OÔPˆŒ
à× Ò Ü3°FÓ;ˆD�Hä-¨fÓ5ˆDŒHÜ9¸&ÓAˆÕr8   râ   rã   Úrun_full_attentionc                 ó@  — |rJ d«       ‚|}|r8|j                   \  }}}| j                  dz  }|j                  ||z  ||z  |«      }| j                  | j	                  |«      |¬«      }	|	d   }
|r8|j                   \  }}}| j                  dz  }|
j                  ||z  ||z  |«      }
| j                  |
«      }
|	dd  }| j                  |
«      |z   }| j                  |«      }| j                  |«      }| j                  |«      }| j                  |«      |z   }|f|z   }|S )Nz9output_attentions is not supported for windowed attentionr‡   )rã   r   r#   )
rˆ   rb   r/   r  rO  rR  r%  rT  rU  rV  )re   râ   rã   rW  ÚshortcutÚbatch_windowsÚtokens_per_windowÚchannelsÚnum_windows_squaredÚself_attention_outputsr  rñ   Úlayer_outputs                r(   r�   z(WindowedDinov2WithRegistersLayer.forwardÝ  sm  € ñ %ÐaÐ&aÓaÐ$Ø ˆÙà9F×9LÑ9LÑ6ˆMÐ,¨hØ"&×"2Ñ"2°AÑ"5ÐØ)×.Ñ.ØÐ!4Ñ4Ð6IÐL]Ñ6]Ð_góˆMð "&§¡Ø�J‰J�}Ó%Ø/ð "0ó "
Ðð 2°!Ñ4Ðáà9F×9LÑ9LÑ6ˆMÐ,¨hØ"&×"2Ñ"2°AÑ"5Ðà/×4Ñ4ØÐ 3Ñ3Ð5FÐJ]Ñ5]Ð_gó Ðð  ×,Ñ,Ð-=Ó>ÐØ(¨¨Ð,ˆð Ÿ™Ð'7Ó8¸8ÑCˆð —z‘z -Ó0ˆØ—x‘x Ó-ˆØ×(Ñ(¨Ó6ˆð —~‘~ lÓ3°mÑCˆà�/ GÑ+ˆàˆr8   )FF)rp   rq   rr   rs   rD   rK   r+   rŽ   ró   r   r   r�   ru   rv   s   @r(   rJ  rJ  Æ  sy   ø„ ÙMðBÐ@ð BÀTõ Bð. #(Ø#(ñ	/à—|‘|ð/ð  ð/ð !ð	/ð
 
ˆu�U—\‘\ 5§<¡<Ð/Ñ0°%¸¿¹Ñ2EÐEÑ	F÷/r8   rJ  c                   ój   ‡ — e Zd Zdeddfˆ fd„Z	 	 	 d
dej                  dedededee	e
f   f
d	„Zˆ xZS )Ú"WindowedDinov2WithRegistersEncoderrƒ   r    Nc                 óä   •— t         ‰| �  «        || _        t        j                  t        |j                  «      D �cg c]  }t        |«      ‘Œ c}«      | _        |j                  | _	        y c c}w rÏ   )
rJ   rK   rƒ   r	   Ú
ModuleListr]   rM   rJ  r=   rd   ©re   rƒ   rÄ   rg   s      €r(   rK   z+WindowedDinov2WithRegistersEncoder.__init__  sX   ø€ Ü‰ÑÔØˆŒÜ—]‘]ÔV[Ð\b×\tÑ\tÓVuÖ#vÐQRÔ$DÀVÕ$LÒ#vÓwˆŒ
Ø&,×&CÑ&CˆÕ#ùò $ws   ½A-râ   rã   Úoutput_hidden_statesÚreturn_dictc                 óæ  — |rdnd }|rdnd }t        | j                  «      D ]¡  \  }}|r||fz   }|t        | j                  j                  d   dd  «      kD  r nl|| j                  j
                  v}	| j                  r+| j                  r| j                  |j                  |||	«      }
n
 ||||	«      }
|
d   }|sŒ™||
d   fz   }Œ£ |r||fz   }|st        d„ |||fD «       «      S t        |||¬«      S )Nr$   r*   é   r   r#   c              3   ó&   K  — | ]	  }|€Œ|–— Œ y ­wrÏ   r$   )r%   Úvs     r(   r)   z=WindowedDinov2WithRegistersEncoder.forward.<locals>.<genexpr>=  s   è ø€ Òm˜qÐ_`Ñ_lœÑmùs   ‚Š)Úlast_hidden_staterâ   Ú
attentions)Ú	enumerater=   r´   rƒ   r9   rc   rd   rý   Ú_gradient_checkpointing_funcÚ__call__Útupler   )re   râ   rã   re  rf  Úall_hidden_statesÚall_self_attentionsÚiÚlayer_modulerW  Úlayer_outputss              r(   r�   z*WindowedDinov2WithRegistersEncoder.forward  s+  € ñ #7™B¸DÐÙ$5™b¸4Ðä(¨¯©Ó4ò 	P‰OˆAˆ|Ù#Ø$5¸Ð8HÑ$HÐ!à”3�t—{‘{×/Ñ/°Ñ3°A°BÐ7Ó8Ò8áà!"¨$¯+©+×*JÑ*JÐ!JÐà×*Ò*¨t¯}ª}Ø $× AÑ AØ ×)Ñ)Ø!Ø%Ø&ó	!‘ñ !-¨]Ð<MÐOaÓ b�à)¨!Ñ,ˆMâ Ø&9¸]È1Ñ=MÐ<OÑ&OÑ#ð/	Pñ2  Ø 1°]Ð4DÑ DÐáÜÑm ]Ð4EÐGZÐ$[ÔmÓmÐmÜØ+Ø+Ø*ô
ð 	
r8   )FFT)rp   rq   rr   rD   rK   r+   rŽ   ró   r   rp  r   r�   ru   rv   s   @r(   ra  ra    sh   ø„ ðDÐ@ð DÀTõ Dð #(Ø%*Ø ñ,
à—|‘|ð,
ð  ð,
ð #ð	,
ð
 ð,
ð 
ˆu�oÐ%Ñ	&÷,
r8   ra  c                   ó‚   — e Zd ZdZeZdZdZdZdgZ	dZ
deej                  ej                  ej                  f   ddfd	„Zy)
Ú*WindowedDinov2WithRegistersPreTrainedModelz|An abstract class to handle weights initialization and a simple interface for downloading and loading pretrained
    models.rF   r„   Tr;  Úmoduler    Nc                 ó>  — t        |t        j                  t        j                  f«      rËt        j                  j                  |j                  j                  j                  t        j                  «      d| j                  j                  ¬«      j                  |j                  j                  «      |j                  _        |j                  �%|j                  j                  j                  «        yyt        |t        j                   «      rJ|j                  j                  j                  «        |j                  j                  j#                  d«       yt        |t$        «      �r3t        j                  j                  |j&                  j                  j                  t        j                  «      d| j                  j                  ¬«      j                  |j&                  j                  «      |j&                  _        t        j                  j                  |j(                  j                  j                  t        j                  «      d| j                  j                  ¬«      j                  |j(                  j                  «      |j(                  _        yy)zInitialize the weights.rk   )ÚmeanÚstdNro   )r|   r	   rÙ   r�   ÚinitÚtrunc_normal_r¿   Údatar°   r+   r±   rƒ   rS   r    rÕ   Úzero_rN  Úfill_r�   r™   r”   )re   rx  s     r(   Ú_init_weightsz8WindowedDinov2WithRegistersPreTrainedModel._init_weightsP  sÉ  € ä�fœrŸy™y¬"¯)©)Ð4Ô5ô "$§¡×!6Ñ!6Ø—‘×"Ñ"×%Ñ%¤e§m¡mÓ4¸3ÀDÇKÁK×DaÑDað "7ó "ç‰b�—‘×$Ñ$Ó%ð �M‰MÔð �{‰{Ð&Ø—‘× Ñ ×&Ñ&Õ(ð 'ä˜¤§¡Ô-Ø�K‰K×Ñ×"Ñ"Ô$Ø�M‰M×Ñ×$Ñ$ SÕ)Ü˜Ô EÕFÜ.0¯g©g×.CÑ.CØ×*Ñ*×/Ñ/×2Ñ2´5·=±=ÓAØØ—K‘K×1Ñ1ð /Dó /÷ ‰b�×+Ñ+×1Ñ1Ó2ð	 ×&Ñ&Ô+ô %'§G¡G×$9Ñ$9Ø× Ñ ×%Ñ%×(Ñ(¬¯©Ó7ØØ—K‘K×1Ñ1ð %:ó %÷ ‰b�×!Ñ!×'Ñ'Ó(ð	 ×ÑÕ!ð Gr8   )rp   rq   rr   rs   rD   Úconfig_classÚbase_model_prefixÚmain_input_nameÚsupports_gradient_checkpointingÚ_no_split_modulesÚ_supports_sdpar   r	   rÙ   r�   rN  r�  r$   r8   r(   rw  rw  E  sY   „ ñð 5€LØ/ÐØ$€OØ&*Ð#Ø7Ð8ÐØ€Nð) E¨"¯)©)°R·Y±YÀÇÁÐ*LÑ$Mð )ÐRVô )r8   rw  aU  
    This model is a PyTorch [torch.nn.Module](https://pytorch.org/docs/stable/nn.html#torch.nn.Module) subclass. Use it
    as a regular PyTorch Module and refer to the PyTorch documentation for all matter related to general usage and
    behavior.

    Parameters:
        config ([`Dinov2WithRegistersConfig`]): Model configuration class with all the parameters of the model.
            Initializing with a config file does not load the weights associated with the model, only the
            configuration. Check out the [`~PreTrainedModel.from_pretrained`] method to load the model weights.
aô  
    Args:
        pixel_values (`torch.FloatTensor` of shape `(batch_size, num_channels, height, width)`):
            Pixel values. Pixel values can be obtained using [`AutoImageProcessor`]. See
            [`BitImageProcessor.preprocess`] for details.

        bool_masked_pos (`torch.BoolTensor` of shape `(batch_size, sequence_length)`):
            Boolean masked positions. Indicates which patches are masked (1) and which aren't (0). Only relevant for
            pre-training.

        output_attentions (`bool`, *optional*):
            Whether or not to return the attentions tensors of all attention layers. See `attentions` under returned
            tensors for more detail.
        output_hidden_states (`bool`, *optional*):
            Whether or not to return the hidden states of all layers. See `hidden_states` under returned tensors for
            more detail.
        return_dict (`bool`, *optional*):
            Whether or not to return a [`~utils.ModelOutput`] instead of a plain tuple.
zmThe bare Dinov2WithRegisters Model transformer outputting raw hidden-states without any specific head on top.c                   ó  ‡ — e Zd Zdefˆ fd„Zdefd„Zdeee	e   f   ddfd„Z
deddfd	„Z ee«       eee¬
«      	 	 	 	 	 ddeej(                     deej(                     dee   dee   dee   deeef   fd„«       «       Zˆ xZS )Ú WindowedDinov2WithRegistersModelrƒ   c                 óò   •— t         ‰| �  |«       || _        t        |«      | _        t        |«      | _        t        j                  |j                  |j                  ¬«      | _        | j                  «        y )NrL  )rJ   rK   rƒ   r�   rŒ   ra  Úencoderr	   rN  rL   rT   Ú	layernormÚ	post_initrÝ   s     €r(   rK   z)WindowedDinov2WithRegistersModel.__init__�  sY   ø€ Ü‰Ñ˜Ô ØˆŒä?ÀÓGˆŒÜ9¸&ÓAˆŒäŸ™ f×&8Ñ&8¸f×>SÑ>SÔTˆŒð 	�‰Õr8   r    c                 ó.   — | j                   j                  S rÏ   ©rŒ   r˜   r,  s    r(   Úget_input_embeddingsz5WindowedDinov2WithRegistersModel.get_input_embeddingsœ  ó   € Ø�‰×/Ñ/Ð/r8   Úheads_to_pruneNc                 ó˜   — |j                  «       D ]7  \  }}| j                  j                  |   j                  j	                  |«       Œ9 y)z�Prunes heads of the model.

        heads_to_prune: dict of {layer_num: list of heads to prune in this layer} See base
        class PreTrainedModel
        N)Úitemsr‹  r=   r  r  )re   r’  r=   r   s       r(   Ú_prune_headsz-WindowedDinov2WithRegistersModel._prune_headsŸ  sE   € ð +×0Ñ0Ó2ò 	C‰LˆE�5Ø�L‰L×Ñ˜uÑ%×/Ñ/×;Ñ;¸EÕBñ	Cr8   Úattn_implementationc                 óä   — |t         vrt        d|›dt        t         «      › d�«      ‚|| j                  _        | j
                  j                  D ]  }t        |   | j                  «      |_        Œ! y)uD  Switch the attention implementation without reloading the model.

        This is useful when you want to change the attention implementation after the model has been instantiated â€” for
        example, to use ``"eager"`` (manual) attention when inspecting attention weights, without having to reconstruct
        the entire model from scratch.

        Args:
            attn_implementation: One of ``"eager"`` (manual attention) or ``"sdpa"``
                (:func:`torch.nn.functional.scaled_dot_product_attention`).

        Raises:
            ValueError: If *attn_implementation* is not a supported key.

        Example::

            >>> from rfdetr.models.backbone.dinov2_with_windowed_attn import (
            ...     WindowedDinov2WithRegistersConfig,
            ...     WindowedDinov2WithRegistersModel,
            ... )
            >>> config = WindowedDinov2WithRegistersConfig(
            ...     image_size=32,
            ...     patch_size=16,
            ...     hidden_size=32,
            ...     num_hidden_layers=1,
            ...     num_attention_heads=4,
            ...     num_register_tokens=2,
            ... )
            >>> model = WindowedDinov2WithRegistersModel(config)
            >>> model.set_attn_implementation("eager")
            >>> model.config._attn_implementation
            'eager'
        zUnknown attn_implementation z. Choose from r†   N)rP  r‰   Úsortedrƒ   rQ  r‹  r=   r  )re   r–  r=   s      r(   Úset_attn_implementationz8WindowedDinov2WithRegistersModel.set_attn_implementation¨  s€   € ðB Ô&MÑMÜØ.Ð/BÐ.Eð FÜ%Ô&MÓNÐOÈqðRóð ð ,?ˆ�‰Ô(Ø—\‘\×'Ñ'ò 	hˆEÜEÐFYÑZÐ[_×[fÑ[fÓgˆE�Oñ	hr8   ©Úoutput_typer‚  r„   r½   rã   re  rf  c                 ó®  — |�|n| j                   j                  }|�|n| j                   j                  }|�|n| j                   j                  }|€t	        d«      ‚| j                  ||¬«      }| j                  ||||¬«      }|d   }| j                  |«      }|dd…ddd…f   }	|s||	f}
|
|dd z   S t        ||	|j                  |j                  ¬«      S )aý  
        Returns:

        Examples:

        >>> import torch
        >>> from rfdetr.models.backbone.dinov2_with_windowed_attn import (
        ...     WindowedDinov2WithRegistersConfig,
        ...     WindowedDinov2WithRegistersModel,
        ... )
        >>> config = WindowedDinov2WithRegistersConfig(
        ...     image_size=32,
        ...     patch_size=16,
        ...     hidden_size=32,
        ...     num_hidden_layers=2,
        ...     num_attention_heads=4,
        ...     num_register_tokens=2,
        ... )
        >>> model = WindowedDinov2WithRegistersModel(config)
        >>> pixel_values = torch.randn(1, 3, 32, 32)
        >>> outputs = model(pixel_values)
        >>> list(outputs.last_hidden_state.shape)
        [1, 7, 32]
        Nz You have to specify pixel_values)r½   ©rã   re  rf  r   r#   )rk  Úpooler_outputrâ   rl  )rƒ   rã   re  rf  r‰   rŒ   r‹  rŒ  r   râ   rl  )re   r„   r½   rã   re  rf  Úembedding_outputÚencoder_outputsÚsequence_outputÚpooled_outputÚhead_outputss              r(   r�   z(WindowedDinov2WithRegistersModel.forwardÒ  s  € ðD 2CÐ1NÑ-ÐTX×T_ÑT_×TqÑTqÐà$8Ð$DÑ È$Ï+É+×JjÑJjð 	ð &1Ð%<‘kÀ$Ç+Á+×BYÑBYˆàÐÜÐ?Ó@Ð@àŸ?™?¨<È˜?ÓYÐàŸ,™,ØØ/Ø!5Ø#ð	 'ó 
ˆð *¨!Ñ,ˆØŸ.™.¨Ó9ˆØ'ª¨1ªa¨Ñ0ˆáØ+¨]Ð;ˆLØ /°!°"Ð"5Ñ5Ð5ä)Ø-Ø'Ø)×7Ñ7Ø&×1Ñ1ô	
ð 	
r8   ©NNNNN)rp   rq   rr   rD   rK   rx   r�  r   r´   r   r•  r/  r™  r   Ú+DINOV2_WITH_REGISTERS_BASE_INPUTS_DOCSTRINGr   r   Ú_CONFIG_FOR_DOCr   r+   rŽ   ró   r   r   r�   ru   rv   s   @r(   r‰  r‰  ‹  sø   ø„ ð

Ð@õ 
ð0Ð&Hó 0ðC¨4°°T¸#±Y°Ñ+?ð CÀDó Cð(h¸3ð (hÀ4ó (hñT +Ð+VÓWÙÐ+EÐTcÔdð 04Ø26Ø,0Ø/3Ø&*ñ>
à˜uŸ|™|Ñ,ð>
ð " %§,¡,Ñ/ð>
ð $ D™>ð	>
ð
 ' t™nð>
ð ˜d‘^ð>
ð 
ˆuÐ0Ð0Ñ	1ò>
ó eó Xô>
r8   r‰  a  
    Args:
        pixel_values (`torch.FloatTensor` of shape `(batch_size, num_channels, height, width)`):
            Pixel values. Pixel values can be obtained using [`AutoImageProcessor`]. See
            [`BitImageProcessor.preprocess`] for details.

        output_attentions (`bool`, *optional*):
            Whether or not to return the attentions tensors of all attention layers. See `attentions` under returned
            tensors for more detail.
        output_hidden_states (`bool`, *optional*):
            Whether or not to return the hidden states of all layers. See `hidden_states` under returned tensors for
            more detail.
        return_dict (`bool`, *optional*):
            Whether or not to return a [`~utils.ModelOutput`] instead of a plain tuple.
z¦Dinov2WithRegisters 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.c                   óÔ   ‡ — e Zd Zdeddfˆ fd„Z ee«       eee	¬«      	 	 	 	 	 dde
ej                     de
ej                     de
e   d	e
e   d
e
e   deeef   fd„«       «       Zˆ xZS )Ú1WindowedDinov2WithRegistersForImageClassificationrƒ   r    Nc                 ó0  •— t         ‰| �  |«       |j                  | _        t        |«      | _        |j                  dkD  r-t        j                  |j                  dz  |j                  «      nt        j                  «       | _	        | j                  «        y )Nr   r‡   )rJ   rK   Ú
num_labelsr‰  rF   r	   rÙ   rL   rS  Ú
classifierr�  rÝ   s     €r(   rK   z:WindowedDinov2WithRegistersForImageClassification.__init__.  sz   ø€ Ü‰Ñ˜Ô à ×+Ñ+ˆŒÜ%EÀfÓ%MˆÔ"ð EK×DUÑDUÐXYÒDYŒB�I‰I�f×(Ñ(¨1Ñ,¨f×.?Ñ.?Ô@Ô_a×_jÑ_jÓ_lð 	Œð
 	�‰Õr8   rš  r„   Úlabelsrã   re  rf  c                 óÄ  — |�|n| j                   j                  }| j                  ||||¬«      }|d   }|dd…df   }|dd…dd…f   }	t        j                  ||	j                  d¬«      gd¬«      }
| j                  |
«      }d}|��¢|j                  |j                  «      }| j                   j                  €�| j                  dk(  rd| j                   _	        nl| j                  dkD  rL|j                  t        j                  k(  s|j                  t        j                  k(  rd| j                   _	        nd| j                   _	        | j                   j                  dk(  rIt        «       }| j                  dk(  r& ||j                  «       |j                  «       «      }nŒ |||«      }n‚| j                   j                  dk(  r=t!        «       } ||j#                  d	| j                  «      |j#                  d	«      «      }n,| j                   j                  dk(  rt%        «       } |||«      }|s|f|d
d z   }|�|f|z   S |S t'        |||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).

        Returns:

        Example:

        >>> import torch
        >>> from rfdetr.models.backbone.dinov2_with_windowed_attn import (
        ...     WindowedDinov2WithRegistersConfig,
        ...     WindowedDinov2WithRegistersForImageClassification,
        ... )
        >>> config = WindowedDinov2WithRegistersConfig(
        ...     image_size=32,
        ...     patch_size=16,
        ...     hidden_size=32,
        ...     num_hidden_layers=2,
        ...     num_attention_heads=4,
        ...     num_register_tokens=2,
        ...     num_labels=3,
        ... )
        >>> model = WindowedDinov2WithRegistersForImageClassification(config)
        >>> pixel_values = torch.randn(1, 3, 32, 32)
        >>> outputs = model(pixel_values)
        >>> list(outputs.logits.shape)
        [1, 3]
        Nr�  r   r#   r¨   Ú
regressionÚsingle_label_classificationÚmulti_label_classificationr*   r‡   )ÚlossÚlogitsrâ   rl  )rƒ   rf  rF   r+   rµ   rz  r«  r°   r²   Úproblem_typerª  r    r4   r´   r   Úsqueezer   r/   r
   r   râ   rl  )re   r„   r¬  rã   re  rf  rñ   r¡  r”   Úpatch_tokensÚlinear_inputr²  r±  Úloss_fctr  s                  r(   r�   z9WindowedDinov2WithRegistersForImageClassification.forward<  s!  € ðV &1Ð%<‘kÀ$Ç+Á+×BYÑBYˆà×,Ñ,ØØ/Ø!5Ø#ð	 -ó 
ˆð " !™*ˆà#¢A q DÑ)ˆ	Ø&¢q¨!©" uÑ-ˆä—y‘y )¨\×->Ñ->À1Ð->Ó-EÐ!FÈAÔNˆà—‘ Ó.ˆàˆØÑà—Y‘Y˜vŸ}™}Ó-ˆFØ�{‰{×'Ñ'Ð/Ø—?‘? aÒ'Ø/;�D—K‘KÕ,Ø—_‘_ qÒ(¨f¯l©l¼e¿j¹jÒ.HÈFÏLÉLÔ\a×\eÑ\eÒLeØ/L�D—K‘KÕ,à/K�D—K‘KÔ,à�{‰{×'Ñ'¨<Ò7Ü"›9�Ø—?‘? aÒ'Ù# F§N¡NÓ$4°f·n±nÓ6FÓG‘Dá# F¨FÓ3‘DØ—‘×)Ñ)Ð-JÒJÜ+Ó-�Ù §¡¨B°·±Ó @À&Ç+Á+ÈbÃ/ÓR‘Ø—‘×)Ñ)Ð-IÒIÜ,Ó.�Ù ¨Ó/�áØ�Y ¨¨ Ñ,ˆFØ)-Ð)9�T�G˜fÑ$ÐE¸vÐEä$ØØØ!×/Ñ/Ø×)Ñ)ô	
ð 	
r8   r¤  )rp   rq   rr   rD   rK   r   Ú&DINOV2_WITH_REGISTERS_INPUTS_DOCSTRINGr   r   r¦  r   r+   rŽ   ró   r   rp  r�   ru   rv   s   @r(   r¨  r¨  &  sÁ   ø„ ðÐ@ð ÀTõ ñ +Ð+QÓRÙØ)Ø$ôð 04Ø)-Ø,0Ø/3Ø&*ñZ
à˜uŸ|™|Ñ,ðZ
ð ˜Ÿ™Ñ&ðZ
ð $ D™>ð	Z
ð
 ' t™nðZ
ð ˜d‘^ðZ
ð 
ˆuÐ+Ð+Ñ	,òZ
ó	ó Sô
Z
r8   r¨  zRDinov2WithRegisters backbone, to be used with frameworks like DETR and MaskFormer.c                   óª   ‡ — e Zd Zdefˆ fd„Zdefd„Z ee«       e	e
e¬«      	 	 	 ddej                  dee   dee   d	ee   de
f
d
„«       «       Zˆ xZS )Ú#WindowedDinov2WithRegistersBackbonerƒ   c                 óš  •— t         ‰| �  |«       | j                  «        t        |j                  dz   «      D �cg c]  }|j
                  ‘Œ c}| _        t        |«      | _        t        |«      | _
        t        j                  |j
                  |j                  ¬«      | _        |j                  | _        | j!                  «        y c c}w )Nr#   rL  )rJ   rK   Ú_init_transformers_backboner]   rM   rL   Únum_featuresr�   rŒ   ra  r‹  r	   rN  rT   rŒ  r\   r�  rd  s      €r(   rK   z,WindowedDinov2WithRegistersBackbone.__init__£  sœ   ø€ Ü‰Ñ˜Ô Ø×(Ñ(Ô*Ü9>¸v×?WÑ?WÐZ[Ñ?[Ó9\Ö]°A˜V×/Ó/Ò]ˆÔÜ?ÀÓGˆŒÜ9¸&ÓAˆŒäŸ™ f×&8Ñ&8¸f×>SÑ>SÔTˆŒà#)×#=Ñ#=ˆÔ ð 	�‰Õùò ^s   »Cr    c                 ó.   — | j                   j                  S rÏ   r�  r,  s    r(   r�  z8WindowedDinov2WithRegistersBackbone.get_input_embeddings±  r‘  r8   rš  r„   re  rã   rf  c                 óT  — |�|n| j                   j                  }|�|n| j                   j                  }|�|n| j                   j                  }| j	                  |«      }| j                  |d||¬«      }|r|j                  n|d   }d}t        | j                  |«      D �]½  \  }	}
|	| j                  v sŒ| j                   j                  r| j                  |
«      }
| j                   j                  �rd|
dd…| j                  dz   d…f   }
|j                  \  }}}}| j                   j                  }||z  }||z  }| j                   j                   dkD  rÌ| j                   j                   dz  }|
j                  \  }}}|| j                   j                   z  }|| j                   j                   z  }|
j#                  ||z  ||z  |«      }
|
j#                  ||z  | j                   j                   z  | j                   j                   |||«      }
|
j%                  ddddd	«      }
|
j#                  |||d
«      }
|
j%                  dddd«      j'                  «       }
||
fz  }�ŒÀ |s|r|f|dd z   }|S |f|dd z   }|S t)        ||r|j                  nd|r|j*                  ¬«      S d¬«      S )aV  
        Returns:

        Examples:

        >>> import torch
        >>> from rfdetr.models.backbone.dinov2_with_windowed_attn import (
        ...     WindowedDinov2WithRegistersBackbone,
        ...     WindowedDinov2WithRegistersConfig,
        ... )
        >>> config = WindowedDinov2WithRegistersConfig(
        ...     image_size=32,
        ...     patch_size=16,
        ...     hidden_size=32,
        ...     num_hidden_layers=2,
        ...     num_attention_heads=4,
        ...     num_register_tokens=2,
        ...     out_indices=[2],
        ... )
        >>> model = WindowedDinov2WithRegistersBackbone(config)
        >>> pixel_values = torch.randn(1, 3, 32, 32)
        >>> outputs = model(pixel_values)
        >>> len(outputs.feature_maps)
        1
        >>> list(outputs.feature_maps[0].shape)
        [1, 32, 2, 2]

        NT)re  rã   rf  r#   r$   r‡   r   rn   ri   r*   )Úfeature_mapsrâ   rl  )rƒ   rf  re  rã   rŒ   r‹  râ   Úzipr;   r9   r`   rŒ  ra   r\   rˆ   rV   rb   r¬   r­   r0   r   rl  )re   r„   re  rã   rf  rŸ  rñ   râ   rÀ  rI   r  rÃ   rÄ   rœ   r�   rV   rÇ   rÈ   r]  rZ  r[  r\  rÌ   rË   r  s                            r(   r�   z+WindowedDinov2WithRegistersBackbone.forward´  sã  € ðJ &1Ð%<‘kÀ$Ç+Á+×BYÑBYˆà$8Ð$DÑ È$Ï+É+×JjÑJjð 	ð 2CÐ1NÑ-ÐTX×T_ÑT_×TqÑTqÐàŸ?™?¨<Ó8Ðà—,‘,Ø°4ÐK\Ðjuð ó 
ˆñ 2=˜×-Ò-À'È!Á*ˆàˆÜ#& t×'7Ñ'7¸Ó#Gó %	0ÑˆE�<Ø˜×)Ñ)Ò)Ø—;‘;×.Ò.Ø#'§>¡>°,Ó#?�LØ—;‘;×4Ó4Ø#/²°4×3KÑ3KÈaÑ3OÑ3QÐ0QÑ#R�Lð 4@×3EÑ3EÑ0�J  6¨5Ø!%§¡×!7Ñ!7�Jà$*¨jÑ$8�MØ$)¨ZÑ$7�Mà—{‘{×.Ñ.°Ò2à.2¯k©k×.EÑ.EÀqÑ.HÐ+ØEQ×EWÑEWÑB˜Ð'8¸(Ø3@ÀDÇKÁK×D[ÑD[Ñ3[Ð0Ø3@ÀDÇKÁK×D[ÑD[Ñ3[Ð0Ø'3×';Ñ';Ø)Ð-@Ñ@Ø/Ð2CÑCØ$ó(˜ð
 (4×';Ñ';Ø*Ð.AÑAÀTÇ[Á[×E\ÑE\Ñ\Ø ŸK™K×3Ñ3Ø4Ø4Ø$ó(˜ð (4×';Ñ';¸A¸qÀ!ÀQÈÓ'J˜à#/×#7Ñ#7¸
ÀMÐS`ÐbdÓ#e�LØ#/×#7Ñ#7¸¸1¸aÀÓ#C×#NÑ#NÓ#P�Là  Ñ/’ðK%	0ñN Ù#Ø&˜¨7°1°2¨;Ñ6�ð ˆMð '˜¨7°1°2¨;Ñ6�ØˆMäØ%Ù3G˜'×/Ò/ÈTÙ->�w×)Ñ)ô
ð 	
ð EIô
ð 	
r8   )NNN)rp   rq   rr   rD   rK   rx   r�  r   r¸  r   r   r¦  r+   rŽ   r   ró   r�   ru   rv   s   @r(   rº  rº  ž  sš   ø„ ð
Ð@õ ð0Ð&Hó 0ñ +Ð+QÓRÙ¨>ÈÔXð 04Ø,0Ø&*ñd
à—l‘lðd
ð ' t™nðd
ð $ D™>ð	d
ð
 ˜d‘^ðd
ð 
òd
ó Yó Sôd
r8   rº  )rw  r‰  r¨  rº  )rk   F)Mrs   Úcollections.abcr}   ræ   Útypingr   r   r   r   r   r   r+   r	   Útorch.nnr
   r   r   Útransformersr   r   Útransformers.activationsr   Ú transformers.configuration_utilsr   Útransformers.modeling_outputsr   r   r   r   Útransformers.modeling_utilsr   Útransformers.pytorch_utilsr   Útransformers.utilsr   r   r   r   r   Ú
get_loggerrp   rú   r´   Ú
LongTensorr7   r/  r?   rC   r¦  rD   ÚModulerx   r�   rÑ   rõ   rÿ   r  r  r  rŽ   r.  ró   r%  r'  r1  r;  rP  rJ  ra  rw  Ú%DINOV2_WITH_REGISTERS_START_DOCSTRINGr¥  r‰  r¸  r¨  rº  Ú__all__r$   r8   r(   ú<module>rÑ     sM  ðñó, Û ß :× :ã Ý ß AÑ Aß ;Ý +Ý =÷ó õ 8Ý 9÷õ ð 
ˆ×	Ñ	˜HÓ	%€ðØˆs‰8ðØ!ðØ.1ðØILÈSÉðà
ˆ3ˆs‰8�U×%Ñ%Ð%Ñ&óð>%Ø˜4 ™9Ñ%ð%à˜%  S¡	¨5°°c°©?Ð :Ñ;Ñ<ð%ð �c‘ð%ð ˆ4�‰9�d˜3‘iÐÑ ó	%ð%Ø˜4 ™9Ñ%ð%à˜%  S¡	¨5°°c°©?Ð :Ñ;Ñ<ð%ð �c‘ð%ð ˆ4�‰9�d˜3‘iÐÑ ó	%ð: 6€ôN=Ð(;Ð=Mô N=ôb¨¯©ô ô>Q¨B¯I©Iô Qôh9 r§y¡yô 9ôx&#Ð+Kô &#ôR B§I¡Iô ô # 2§9¡9ô #ôLFÐ'Cô Fô+ B§I¡Iô +ñ�U—\‘\ð ¨eð ÀTð ÐV[×VbÑVbó ô&- "§)¡)ô -ô˜RŸY™Yô ô&( 2§9¡9ô (ð$ *Ø,ñ+Ð 'ôF r§y¡yô FôR3
¨¯©ô 3
ôl#)°ô #)ðL	)Ð %ð/Ð +ñ* ØsØ)óôC
Ð'Qó C
ó	ðC
ðL*Ð &ñ" ð	bð *óôn
Ð8bó n
óðn
ñb ØXØ)óôx
Ð*TÐVcó x
ó	ðx
òv�r8   