+
    åûj¨¾  ã                  ó@  € R t ^ RIHt ^ RIHtHtHtHt ^ RIt^ RI	H
u Ht ^ RIH
t
 ^ RIHt ^ RIHt ^ RIHt ^ RIHtHtHt ^ R	IHt  ! R
 R]
P2                  4      t ! R R]
P2                  4      t ! R R]
P2                  4      t ! R R]
P2                  4      tR# )aK  XFeat: Accelerated Features for Lightweight Image Matching.

This module is adapted from the original XFeat implementation:
    https://github.com/verlab/accelerated_features

Original work copyright (c) 2024 Verlab / UFMG, licensed under the Apache License 2.0.
Modifications copyright (c) 2024 Kornia Team, licensed under the Apache License 2.0.

Reference:
    Guilherme Potje, Felipe Cadar, Andre Araujo, Renato Martins, Erickson R. Nascimento.
    "XFeat: Accelerated Features for Lightweight Image Matching", CVPR 2024.
    https://www.verlab.dcc.ufmg.br/descriptors/xfeat_cvpr24/
)Úannotations)ÚDictÚListÚOptionalÚTupleN)Únn)ÚKORNIA_CHECK)Úload_state_dict_from_url)Ú_copied_literal)Ú_l2_normalizeÚ_samples_half_in_float32Ú_to_device_nonblocking)Únms2dc                  óB   a € ] tR t^/tRtRR V 3R llltR R ltRtV ;t# )Ú
BasicLayera¨  Basic convolutional layer: Conv2d -> BatchNorm2d (no affine) -> ReLU.

Args:
    in_channels: number of input channels.
    out_channels: number of output channels.
    kernel_size: convolution kernel size. Default: ``3``.
    stride: convolution stride. Default: ``1``.
    padding: convolution padding. Default: ``1``.
    dilation: convolution dilation. Default: ``1``.
    bias: whether to use bias. Default: ``False``.
c               ó8   € V ^8„  d   QhRRRRRRRRRRRRRR	R
R/# )é   Úin_channelsÚintÚout_channelsÚkernel_sizeÚstrideÚpaddingÚdilationÚbiasÚboolÚreturnÚNone© )Úformats   "ÚPC:\Ai_Coding\apps\studio\ComfyUI\.venv\Lib\site-packages\kornia\feature\xfeat.pyÚ__annotate__ÚBasicLayer.__annotate__<   sZ   € ÷ 
ñ 
àð
ð ð
ð ð	
ð
 ð
ð ð
ð ð
ð ð
ð 
ñ
ó    c                	óä   <€ \         SV `  4        \        P                  ! \        P                  ! WW5WFVR 7      \        P
                  ! VRR7      \        P                  ! RR7      4      V n        R# ))r   r   r   r   F©ÚaffineT©ÚinplaceN)ÚsuperÚ__init__r   Ú
SequentialÚConv2dÚBatchNorm2dÚReLUÚlayer)	Úselfr   r   r   r   r   r   r   Ú	__class__s	   &&&&&&&&€r    r*   ÚBasicLayer.__init__<   sS   ø€ ô 	‰ÑÔÜ—]’]Ü�IŠIØ¨;ÐPVÐptôô �NŠN˜<°Ô6Ü�GŠG˜DÔ!ó
ˆŽ
r#   c               ó    € V ^8„  d   QhRRRR/# )r   Úxútorch.Tensorr   r   )r   s   "r    r!   r"   O   s   € ÷ 	ñ 	˜ð 	¨,ñ 	r#   c                ó$   € V P                  V4      # )z¡Run the module forward pass.

Args:
    x: Input feature map with shape ``(B, C_in, H, W)``.

Returns:
    Output feature map with shape ``(B, C_out, H', W')``.
©r/   )r0   r4   s   &&r    ÚforwardÚBasicLayer.forwardO   s   € ð �z‰z˜!‹}Ðr#   r7   )é   é   r;   r;   F)	Ú__name__Ú
__module__Ú__qualname__Ú__firstlineno__Ú__doc__r*   r8   Ú__static_attributes__Ú__classcell__©r1   s   @r    r   r   /   s   ø† ñ
÷
ò 
÷&	ó 	r#   r   c                  óN   a € ] tR t^[tRtR V 3R lltR	R R lltR R ltRtV ;t	# )
Ú
XFeatModela'  Compute the dense descriptors, keypoint logits and reliability map of XFeat at 1/8 resolution.

``net = XFeatModel().eval()`` builds the random-weight network for inference (``XFeat.from_pretrained().net``
is trained), and ``feats, keypoints, heatmap = net(images)`` takes float images ``(B, C, H, W)`` with any
channel count and ``H`` and ``W`` multiples of 8, and returns the dense descriptors ``(B, 64, H/8, W/8)``, not
normalised, the keypoint logits ``(B, 65, H/8, W/8)`` and the reliability map ``(B, 1, H/8, W/8)``, a sigmoid. It
finds no keypoints itself: for keypoints, descriptors and matches, use :class:`XFeat` instead. It implements the
architecture of "XFeat: Accelerated Features for Lightweight Image Matching", CVPR 2024.

Convention:
    - The channels are averaged and the result is instance-normalised, so any channel count is accepted and an
      affine change ``a x + b`` of the intensities with ``a > 0`` changes the outputs only through the norm's
      ``eps`` (``1e-5``): negligibly while the variance of the channel mean is much larger than ``eps``, and
      substantially for a low-contrast image, whose variance is close to it (see :class:`XFeat`).
    - A new ``XFeatModel`` is in training mode. A single ``32 x 32`` image reaches BatchNorm with one value per
      channel and raises; call ``.eval()`` for inference.
    - ``H`` and ``W`` must be multiples of 8; other sizes raise an error or give maps of mismatched sizes.
      :class:`XFeat` resizes its input to multiples of 32.
    - ``keypoints`` holds 65 logits per 8 x 8 cell: channel ``(y % 8) * 8 + x % 8`` of cell ``(y // 8, x // 8)``
      is pixel ``(x, y)``, and channel 64 is the "no keypoint" dustbin.

Note:
    Image normalisation (``InstanceNorm2d``) is wrapped in ``torch.no_grad()``
    following the original design; backpropagating through it is not supported.

See Also:
    - :class:`XFeat`: runs this network and detects, describes and matches keypoints from its maps.
    - :class:`InterpolateSparse2d`: samples the descriptor map at sparse keypoints, as :class:`XFeat` does.

c               ó   € V ^8„  d   QhRR/# )r   r   r   r   )r   s   "r    r!   ÚXFeatModel.__annotate__{   s   € ÷ J
ñ J
˜$ñ J
r#   c                	ó"  <€ \         SV `  4        \        P                  ! ^4      V n        \        P
                  ! \        P                  ! ^^R7      \        P                  ! ^^^^^ R7      4      V n        \        P
                  ! \        ^^^R7      \        ^^^R7      \        ^^^R7      \        ^^^R7      4      V n
        \        P
                  ! \        ^^^R7      \        ^^^R7      4      V n        \        P
                  ! \        ^^@^R7      \        ^@^@^R7      \        ^@^@^^ R7      4      V n        \        P
                  ! \        ^@^@^R7      \        ^@^@^R7      \        ^@^@^R7      4      V n        \        P
                  ! \        ^@^€^R7      \        ^€^€^R7      \        ^€^€^R7      \        ^€^@^^ R7      4      V n        \        P
                  ! \        ^@^@^R7      \        ^@^@^R7      \        P                  ! ^@^@^^ R7      4      V n        \        P
                  ! \        ^@^@^^ R7      \        ^@^@^^ R7      \        P                  ! ^@^^4      \        P                   ! 4       4      V n        \        P
                  ! \        ^@^@^^ R7      \        ^@^@^^ R7      \        ^@^@^^ R7      \        P                  ! ^@^A^4      4      V n        \        P
                  ! \        P&                  ! ^€R4      \        P(                  ! RRR7      \        P*                  ! RR7      \        P&                  ! RR4      \        P(                  ! RRR7      \        P*                  ! RR7      \        P&                  ! RR4      \        P(                  ! RRR7      \        P*                  ! RR7      \        P&                  ! RR4      \        P(                  ! RRR7      \        P*                  ! RR7      \        P&                  ! R^@4      4      V n        R	# )
r;   )r   )r   r   )r   i   Fr%   Tr'   N)r)   r*   r   ÚInstanceNorm2dÚnormr+   Ú	AvgPool2dr,   Úskip1r   Úblock1Úblock2Úblock3Úblock4Úblock5Úblock_fusionÚSigmoidÚheatmap_headÚkeypoint_headÚLinearÚBatchNorm1dr.   Úfine_matcher)r0   r1   s   &€r    r*   ÚXFeatModel.__init__{   s  ø€ Ü‰ÑÔÜ×%Ò% aÓ(ˆŒ	ä—]’]Ü�LŠL˜ 1Ô%Ü�IŠI�a˜˜Q q°!Ô4ó
ˆŒ
ô
 —m’mÜ�q˜! AÔ&Ü�q˜! AÔ&Ü�q˜! AÔ&Ü�q˜" QÔ'ó	
ˆŒô —m’mÜ�r˜2 aÔ(Ü�r˜2 aÔ(ó
ˆŒô
 —m’mÜ�r˜2 aÔ(Ü�r˜2 aÔ(Ü�r˜2˜q¨!Ô,ó
ˆŒô —m’mÜ�r˜2 aÔ(Ü�r˜2 aÔ(Ü�r˜2 aÔ(ó
ˆŒô —m’mÜ�r˜3 qÔ)Ü�s˜C¨Ô*Ü�s˜C¨Ô*Ü�s˜B ¨1Ô-ó	
ˆŒô ŸMšMÜ�r˜2 aÔ(Ü�r˜2 aÔ(Ü�IŠI�b˜"˜a¨Ô+ó
ˆÔô ŸMšMÜ�r˜2˜q¨!Ô,Ü�r˜2˜q¨!Ô,Ü�IŠI�b˜!˜QÓÜ�JŠJ‹Ló	
ˆÔô  Ÿ]š]Ü�r˜2˜q¨!Ô,Ü�r˜2˜q¨!Ô,Ü�r˜2˜q¨!Ô,Ü�IŠI�b˜"˜aÓ ó	
ˆÔô ŸMšMÜ�IŠI�c˜3ÓÜ�NŠN˜3 uÔ-Ü�GŠG˜DÔ!Ü�IŠI�c˜3ÓÜ�NŠN˜3 uÔ-Ü�GŠG˜DÔ!Ü�IŠI�c˜3ÓÜ�NŠN˜3 uÔ-Ü�GŠG˜DÔ!Ü�IŠI�c˜3ÓÜ�NŠN˜3 uÔ-Ü�GŠG˜DÔ!Ü�IŠI�c˜2Óó
ˆÖr#   c               ó$   € V ^8„  d   QhRRRRRR/# )r   r4   r5   Úwsr   r   r   )r   s   "r    r!   rG   Ç   s&   € ÷ Hñ H˜<ð H¨Sð H¸ñ Hr#   c                óú   € VP                   w  r4rVVP                  ^W"4      P                  ^W"4      P                  W4WR,          Wb,          V^,          4      pVP                  ^ ^^^^4      P	                  ^^R7      # )zHUnfold spatial dims by window size ``ws`` and concatenate into channels.©Ú	start_dimÚend_dim)ÚshapeÚunfoldÚreshapeÚpermuteÚflatten)r0   r4   r[   ÚBÚCÚHÚWs   &&&    r    Ú	_unfold2dÚXFeatModel._unfold2dÇ   so   € à—W‘W‰
ˆˆaØ�H‰H�Q˜Ó×&Ñ& q¨"Ó1×9Ñ9¸!ÀÅÈÍÐRTÐVWÕRWÓXˆØ�y‰y˜˜A˜q ! QÓ'×/Ñ/¸!ÀQÐ/ÓGÐGr#   c               ó    € V ^8„  d   QhRRRR/# )r   r4   r5   r   z/Tuple[torch.Tensor, torch.Tensor, torch.Tensor]r   )r   s   "r    r!   rG   Í   s   € ÷ )ñ )˜ð )Ð*Yñ )r#   c                ó0  € \         P                  ! 4       ;_uu_ 4        VP                  ^RR7      pV P                  V4      pRRR4       V P	                  V4      pV P                  W P                  V4      ,           4      pV P                  V4      pV P                  V4      pV P                  V4      p\        P                  ! WTP                  R,          VP                  R	,          3RRR7      p\        P                  ! WdP                  R,          VP                  R	,          3RRR7      pV P                  WE,           V,           4      pV P                  V4      pV P                  V P!                  V^R7      4      p	WyV3#   + '       g   i     ELJ; i)
a	  Run the XFeat backbone.

Args:
    x: image tensor of shape ``(B, C, H, W)``.

Returns:
    Tuple of:
    - feats: dense descriptors ``(B, 64, H/8, W/8)``.
    - keypoints: keypoint logits ``(B, 65, H/8, W/8)``.
    - heatmap: reliability map ``(B, 1, H/8, W/8)``.
T)ÚdimÚkeepdimNÚbilinearF©ÚmodeÚalign_corners)r[   éþÿÿÿéÿÿÿÿ)ÚtorchÚno_gradÚmeanrJ   rM   rN   rL   rO   rP   rQ   ÚFÚinterpolater`   rR   rT   rU   ri   )
r0   r4   Úx1Úx2Úx3Úx4Úx5ÚfeatsÚheatmapÚ	keypointss
   &&        r    r8   ÚXFeatModel.forwardÍ   s*  € ô �]Š]�_�_Ø—‘˜1 d�Ó+ˆAØ—	‘	˜!“ˆA÷ ð �[‰[˜‹^ˆØ�[‰[˜Ÿj™j¨›mÕ+Ó,ˆØ�[‰[˜‹_ˆØ�[‰[˜‹_ˆØ�[‰[˜‹_ˆä�]Š]˜2§¡¨¥¨b¯h©h°r­lÐ;À*Ð\aÔbˆÜ�]Š]˜2§¡¨¥¨b¯h©h°r­lÐ;À*Ð\aÔbˆØ×!Ñ! "¥'¨B¥,Ó/ˆà×#Ñ# EÓ*ˆØ×&Ñ& t§~¡~°a¸A ~Ó'>Ó?ˆ	Ø Ð(Ð(÷! �_ˆ_ús   ž%FÆF	)rM   rN   rO   rP   rQ   rR   rX   rT   rU   rJ   rL   )r   )
r<   r=   r>   r?   r@   r*   ri   r8   rA   rB   rC   s   @r    rE   rE   [   s%   ø† ñ÷>J
ð J
÷XH÷)ó )r#   rE   c                  óN   a € ] tR t^ìtRtR	R V 3R llltR R ltR R ltRtV ;t	# )
ÚInterpolateSparse2da£	  Sample a feature map at sparse (x, y) pixels with the XFeat weights' coordinate scaling.

``interp = InterpolateSparse2d("bicubic")`` and ``out = interp(x, pos, H, W)`` take a feature map ``(B, C, h, w)``
and positions ``(B, N, 2)`` as ``(x, y)`` pixels of an image of height ``H`` and width ``W``, and return the
features ``(B, N, C)`` that :func:`torch.nn.functional.grid_sample` reads there with ``mode``, in the dtype of
``x``. The positions are divided by ``W - 1`` and ``H - 1`` but sampled with ``align_corners=False``, as the
pretrained XFeat weights expect, so ``H`` and ``W`` must be greater than 1, and a map of the image's own size is
not read at ``pos`` itself (see the Convention block). To read a map of the image's own size at the pixel itself,
normalise the positions with :func:`~kornia.geometry.conversions.normalize_pixel_coordinates` and pass
``align_corners=True`` to ``grid_sample`` instead.

Convention:
    - ``pos`` holds ``(x, y)`` pixels of an image of height ``H`` and width ``W`` whose feature map has height
      ``h`` and width ``w``. A position ``(px, py)`` is read at ``px * w / (W - 1) - 0.5`` and
      ``py * h / (H - 1) - 0.5`` in the map's pixel frame: ``normgrid``'s ``2 p / (W - 1) - 1`` sampled with
      ``align_corners=False``, the convention the pretrained XFeat weights use.
    - A float16 or bfloat16 map is sampled in float32 and returned in its dtype, and float16 or bfloat16 positions
      are normalised in float32: torch's half-precision ``grid_sample`` can return wrong values, NaN or overflow on
      CPU, and a half-precision grid is off by a pixel or more on a large map.

Args:
    mode: interpolation mode for :func:`torch.nn.functional.grid_sample`.
        Default: ``'bicubic'``.
    align_corners: stored and not used: ``grid_sample`` is always called with ``align_corners=False``. Default:
        ``False``.

Shape:
    - Input ``x``: ``(B, C, h, w)``.
    - Input ``pos``: ``(B, N, 2)`` integer or float (x, y) coordinates.
    - Output: ``(B, N, C)``.

See Also:
    - :class:`XFeat`: samples its dense descriptors at its keypoints with this module.
    - :class:`XFeatModel`: the network whose descriptor map :class:`XFeat` samples with this module.
    - :func:`~kornia.geometry.conversions.normalize_pixel_coordinates`: the same division by ``W - 1`` and
      ``H - 1``, meant for ``grid_sample`` with ``align_corners=True``, which reads a map of the image's size at
      the pixel itself.

c               ó$   € V ^8„  d   QhRRRRRR/# )r   rq   Ústrrr   r   r   r   r   )r   s   "r    r!   Ú InterpolateSparse2d.__annotate__  s!   € ÷ +ñ +˜Sð +¸Tð +Èdñ +r#   c                	ó<   <€ \         SV `  4        Wn        W n        R # ©N)r)   r*   rq   rr   )r0   rq   rr   r1   s   &&&€r    r*   ÚInterpolateSparse2d.__init__  s   ø€ Ü‰ÑÔØŒ	Ø*Ör#   c               ó(   € V ^8„  d   QhRRRRRRRR/# )r   r4   r5   rg   r   rh   r   r   )r   s   "r    r!   r‡     s(   € ÷ $ñ $˜,ð $¨3ð $°3ð $¸<ñ $r#   c                óh  € \         P                  P                  4       '       dH   \        \         P                  ! V^,
          V^,
          .VP
                  R7      VP                  4      pM2\        V^,
          V^,
          .VP                  VP
                  R7      pRW,          ,          R,
          # )aB  Normalise pixel coordinates to the ``[-1, 1]`` range expected by ``grid_sample``.

Uses the formula from the original XFeat implementation:
``2 * x / [W-1, H-1] - 1``.  Note that ``grid_sample`` is always
called with ``align_corners=False``; this asymmetry matches the
convention the pretrained weights were trained with.
)Údtype©Údevicer�   g       @ç      ð?)ru   ÚjitÚis_scriptingr   Útensorr�   r�   r
   )r0   r4   rg   rh   Úwhs   &&&& r    ÚnormgridÚInterpolateSparse2d.normgrid  sx   € ô �9‰9×!Ñ!×#Ò#ä'¬¯ª°a¸!µe¸QÀ½U°^È1Ï7É7Ô(SÐUV×U]ÑU]Ó^‰Bä  ! a¥%¨¨Q­ ¸¿¹ÈÏÉÔPˆBØ�a•f�~ Õ#Ð#r#   c          
     ó,   € V ^8„  d   QhRRRRRRRRRR/# )r   r4   r5   Úposrg   r   rh   r   r   )r   s   "r    r!   r‡   )  s/   € ÷ 1ñ 1˜ð 1¨Lð 1¸Sð 1ÀSð 1È\ñ 1r#   c                óÚ  € \        V4      '       d   \        P                  MVP                  pT P	                  \        V4      '       d   VP                  4       MTW44      P                  R4      P                  V4      p\        P                  ! VP                  V4      W`P                  RR7      P                  VP                  4      pVP                  ^ ^^^4      P                  R4      # )a>  Sample ``x`` at positions ``pos``.

Args:
    x: feature map ``(B, C, h, w)``.
    pos: sampling positions ``(B, N, 2)`` in pixel coordinates.
    H: height used for coordinate normalisation, greater than 1.
    W: width used for coordinate normalisation, greater than 1.

Returns:
    Sampled features ``(B, N, C)``.
Frp   rs   )r   ru   Úfloat32r�   r•   ÚfloatÚ	unsqueezeÚtorx   Úgrid_samplerq   rc   Úsqueeze)r0   r4   r˜   rg   rh   ÚwideÚgrids   &&&&&  r    r8   ÚInterpolateSparse2d.forward)  s«   € ô !9¸× ;Ò ;Œu�}Š}ÀÇÁˆØ�}‰}Ô,DÀS×,IÒ,I˜SŸY™Yœ[ÈsÐTUÓY×cÑcÐdfÓg×jÑjÐkoÓpˆô �MŠM˜!Ÿ$™$˜t›* d·±È%ÔP×SÑSÐTU×T[ÑT[Ó\ˆØ�y‰y˜˜A˜q !Ó$×,Ñ,¨RÓ0Ð0r#   )rr   rq   )ÚbicubicF)
r<   r=   r>   r?   r@   r*   r•   r8   rA   rB   rC   s   @r    r„   r„   ì   s"   ø† ñ&÷P+ò +õ
$÷1ó 1r#   r„   c                  ó.  a € ] tR tRt$ RtRtR]R&   R-R V 3R lllt]R-R R	 ll4       t	R
 R lt
]R R l4       tR R lt]R.R R ll4       t]R/R R ll4       t]R R l4       t]R0R R ll4       tR1R R lltR2R R lltR3R R lltR4R R lltR5R  R! llt]P0                  ! 4       R6R" R# ll4       t]P0                  ! 4       R7R$ R% ll4       tR& R' lt]P0                  ! 4       R8R( R) ll4       t]P0                  ! 4       R9R* R+ ll4       tR,tV ;t# ):ÚXFeati>  aÅ-  Detect and describe keypoints with XFeat, and match image pairs, sparse or refined (XFeat*).

``xfeat = XFeat.from_pretrained()`` loads trained weights in evaluation mode.
``out = xfeat.detectAndCompute(images)`` takes images ``(B, C, H, W)`` with any channel count and returns one
dictionary per image. Each contains up to ``top_k`` keypoints ``(N, 2)`` in ``(x, y)`` pixels, scores ``(N,)``
in descending order and L2-normalised descriptors ``(N, 64)``.
Use :meth:`match_xfeat` to extract and match sparse features, or :meth:`match_xfeat_star` for refined matches
from semi-dense features. For subpixel keypoint detection, use :class:`ALIKED` instead.

Reference:
    "XFeat: Accelerated Features for Lightweight Image Matching", CVPR 2024.
    https://www.verlab.dcc.ufmg.br/descriptors/xfeat_cvpr24/

.. image:: _static/img/XFeat.png

Convention:
    - Use the named extraction and matching methods: XFeat has no ``forward``. Its network, ``xfeat.net``,
      is an :class:`XFeatModel` that produces dense maps. To match with LighterGlue, construct LAFs with
      :func:`~kornia.feature.laf_from_center_scale_ori` on ``keypoints[None]`` and pass them with the descriptors
      to :class:`LightGlueMatcher` in ``"xfeat"`` mode, with gradients disabled.
    - ``XFeat()`` builds random weights in training mode. Batch normalisation can raise on a single small image;
      call ``.eval()`` for inference. :meth:`from_pretrained` returns the trained model in evaluation mode.
    - :meth:`detectAndCompute`, :meth:`detectAndComputeDense`, :meth:`match_xfeat` and :meth:`match_xfeat_star`
      run under ``torch.inference_mode``, so they return inference tensors.
    - The image is ``(B, C, H, W)`` with any channel count. Each extraction resizes the image it gets
      bilinearly to ``(H', W')``: ``H`` and ``W`` rounded down to multiples of 32, with a minimum of 32.
      :class:`XFeatModel` then averages the channels and instance-normalises the result, so an affine change of the
      intensities with a positive gain changes its maps only through the norm's ``eps``, which weighs more the
      lower the image's contrast. With the pretrained weights and ``top_k=2048``, the :math:`[0, 1]` and
      :math:`[0, 255]` versions of Oxford graf and wall ``img1`` differ in at most 1 keypoint, in 1 to 2 % of them
      with the intensities multiplied by 0.1, and in 35 to 40 % multiplied by 0.01.
    - Keypoints are float32. Scores and descriptors have the dtype of the weights, and the resized image is cast to
      it, so a float16 or bfloat16 model runs on an image of any float dtype; under autocast, the descriptors of
      :meth:`detectAndComputeDense` have the dtype autocast gives the network. With the pretrained weights,
      ``top_k=2048`` and the 290 HPatches pairs on an RTX 4090 with torch 2.15, :meth:`match_xfeat` keeps its
      inliers at 3 px within 0.6 % of float32, and float16 and bfloat16 keep 99.4 % and 95.0 % of its keypoints. On
      an Apple M1 half precision takes about 15 times as long as float32 on the CPU and about as long on MPS. On
      torch 2.5.1 the CPU float16 instance norm is wrong: on HPatches a ``[0, 255]`` image gave no keypoints and a
      ``[0, 1]`` one 18 % of the inliers. Use float32 or bfloat16 weights there. torch 2.15 and a 2.16 nightly are
      correct; versions in between were not checked.
    - :meth:`detectAndCompute` keypoints are integer pixels of the resized image, strict maxima of the keypoint
      heatmap in their 5 x 5 window (see the note). Pixel :math:`i` of the resized image is reported at its centre
      in the input, :math:`(i + 0.5) W / W' - 0.5` in :math:`x` and likewise in :math:`y`, in the pixel convention
      of :func:`~kornia.feature.laf_from_center_scale_ori` (see :ref:`Local features <local-features-conventions>`).
      That is exactly :math:`i` when ``H`` and ``W`` are multiples of 32. The reference implementation reports
      :math:`i W / W'` instead, up to nearly half a pixel away.
    - The heatmap value must be strictly above ``detection_threshold``. ``scores`` is that value times the
      reliability map, and the ``top_k`` best keypoints come sorted by it. Each descriptor is 64-D, sampled
      bicubically from the dense map at the keypoint by :class:`InterpolateSparse2d`, and L2-normalised.
    - With ``multiscale=False``, :meth:`detectAndComputeDense` takes cell ``(j, i)`` of the 1/8-resolution map at
      pixel ``8 * (j, i)`` of the resized image, the top-left pixel of the cell and not its centre, and reports
      that pixel's centre in the input as above: exactly ``8 * (j, i)`` when ``H`` and ``W`` are multiples of 32.
      It keeps up to ``top_k`` cells by reliability; ``top_k < 1`` keeps every cell.
      With the default ``multiscale=True``, it rescales the image bilinearly by 0.6 and by 1.3, runs that extraction
      on each with ``int(0.2 * top_k)`` and the remaining ``top_k - int(0.2 * top_k)`` cells, and maps each
      keypoint ``p`` of the image rescaled by ``s`` back through the pixel centre, ``(p + 0.5) / s - 0.5``;
      ``scales`` is ``1 / 0.6`` or ``1 / 1.3`` for each keypoint. The reference divides by the factor, ``p / s``,
      0.333 px up and to the left of the pixel at 0.6 and 0.115 px down and to the right at 1.3
      (`#6537 <https://github.com/kornia/kornia/issues/6537>`_). A share of 0 yields
      no cell from its scale, and a scale with fewer
      cells than its share returns all of them, so there are never more than ``top_k`` keypoints, and exactly
      ``top_k`` when both scales have enough cells. A ``top_k`` below 1 keeps every cell of both scales. Its
      descriptors are not normalised. The reference implementation gives the 1.3 scale ``int(0.8 * top_k)`` and
      reads a share of 0 as "every cell"; kornia does not, because that returns more keypoints than ``top_k`` asks
      for.
    - Known defects: autograd cannot save the inference tensors of
      the four methods above for a backward pass, so :class:`~kornia.feature.LightGlueMatcher`, whose parameters
      require gradients, raises on them with gradients enabled, the default grad mode: call it under
      ``torch.no_grad()`` or ``torch.inference_mode()``, or ``clone()`` the outputs first
      (`#6533 <https://github.com/kornia/kornia/issues/6533>`_).

Args:
    top_k: maximum number of keypoints to keep per image. Default: ``4096``.
    detection_threshold: the keypoint heatmap value a keypoint must exceed, see the Convention block. Default:
        ``0.05``.

Note:
    Keypoints are the strict local maxima of the keypoint heatmap: :func:`~kornia.geometry.subpix.nms2d` keeps a
    position only if its score is greater than every other score in its full 5x5 window. Tied maxima, and the
    positions within 2 pixels of the border whose window runs off the image, are never keypoints. This departs
    on purpose from the reference implementation (verlab/accelerated_features). Its NMS keeps every position
    equal to the maximum of its window: all positions of a plateau survive, and whether a near-tie survives
    depends on rounding-level differences of the scores. Its window is also clipped at the border, so it judges
    a border position against part of its window. With the pretrained weights on Oxford graf and boat img1,
    every candidate of the reference that kornia leaves out lies in that border strip.

    XFeat* (:meth:`match_xfeat_star`) anchors both matched cells at bin 3: it moves both points three pixels
    into their cells, then moves the first point by the fine displacement. Both are pixels of the image the network
    saw, and one such pixel spans ``r / s`` input pixels per axis, for extraction scale ``s`` (0.6 or 1.3) and the
    ratio ``r`` of the resize to multiples of 32. This differs from the raw top-left coordinates returned by
    :meth:`detectAndComputeDense` and from the reference, which starts both points at the top-left pixel and
    scales the displacement by ``1 / s``.

    On 40 Oxford affine pairs, this match origin raises homography AUC@3 from 0.365 to 0.401 (three
    correspondence-order seeds, float32, ``top_k=4096``, USAC_MAGSAC at 1 px), and on 813 IMC PhotoTourism
    validation pairs scene-mean relative-pose mAA@10 from 0.458 to 0.473 (USAC_MAGSAC at 0.5 px, measured before
    the pixel-centre mapping of the dual-scale rescale below).

    The displacement of the first image is the soft-argmax of the
    fine matcher's 8 x 8 heatmap times the keypoint's scale, measured from bin 3 of each axis. This also departs
    on purpose from the reference implementation, which measures it from bin 4, the window centre: the pretrained
    fine matcher puts a zero displacement at bin 3. Matching Oxford bikes img1 with itself (pretrained weights,
    ``multiscale=False``), the reference's refinement moves the points by (-1.04, -1.25) px on average and leaves
    1 % of them within 1 px of their position, against (-0.04, -0.25) px and 94 % from bin 3. On 18 Oxford affine
    pairs the median homography corner error drops from 2.58 to 2.30 px; IMC 2021 PhotoTourism relative pose
    mAA@10 is the same within noise (0.441 and 0.443 over 813 pairs). Away from a zero displacement the soft-argmax
    still moves a point only about half of the way, as in the reference: on Oxford graf 1-2 to 1-5 its response to
    the true sub-cell offset has a slope of about 0.5, so bin 3 removes the constant part of the error, not that
    shrinkage.

    Reporting keypoints at the pixel centre of the resize to a multiple of 32 also departs on purpose from the
    reference. With the pretrained weights and 8 Oxford images, each matched with resizes of itself to two sizes
    whose true map is known exactly, the share of matches within 1 px goes from 24.2 to 24.5 % for
    :meth:`match_xfeat`, from 40.1 to 40.7 % for :class:`LightGlueMatcher` and from 28.7 to 29.1 % for
    :meth:`match_xfeat_star`. Homography AUC on Oxford affine and HPatches stays within the noise of the estimator
    for the first two, and on HPatches at about 320 px AUC@3 of :meth:`match_xfeat_star` gains 0.0025. The 0.6 and
    1.3 rescale of the dual-scale extraction goes through the pixel centre as well. With the bin-3 anchor, Oxford
    affine AUC@3 of :meth:`match_xfeat_star` stays within seed noise (0.404 before, 0.401 after), and the share of
    matches within 1 px of an exactly known map goes from 46.6 to 50.4 % for an image matched with its 0.7 resize,
    and from 47.6 to 48.0 %, 35.9 to 36.9 % and 21.6 to 21.2 % for its rotations by 20 degrees, by 20 degrees at
    scale 0.7 and by -35 degrees at scale 1.2 (`#6537 <https://github.com/kornia/kornia/issues/6537>`_).

See Also:
    - :class:`XFeatModel`: the network it runs, which returns the dense maps at 1/8 resolution.
    - :class:`InterpolateSparse2d`: samples the dense descriptors at the keypoints.
    - :class:`ALIKED`: learned sub-pixel keypoints with 128-D descriptors, for RGB images of any size.
    - :class:`DISK`: learned integer-pixel keypoints with 128-D descriptors, for RGB images whose sides are
      multiples of 16.
    - :class:`DeDoDe`: separate learned detector and descriptor networks, with ``n`` keypoints in every image.
    - :func:`laf_from_center_scale_ori`: turns the keypoints of one image into the LAFs that
      :class:`LightGlueMatcher` takes.
    - :class:`LightGlueMatcher`: matches the descriptors and keypoints with the LighterGlue ``"xfeat"`` weights
      instead of mutual nearest neighbours.

Example:
    >>> model = XFeat.from_pretrained()
    >>> img = torch.rand(1, 3, 256, 256)
    >>> out = model.detectAndCompute(img)
    >>> out[0]['keypoints'].shape
    torch.Size([..., 2])
zHhttps://github.com/verlab/accelerated_features/raw/main/weights/xfeat.ptr†   Úweights_urlc               ó$   € V ^8„  d   QhRRRRRR/# )r   Útop_kr   Údetection_thresholdr›   r   r   r   )r   s   "r    r!   ÚXFeat.__annotate__Ï  s"   € ÷ 9ñ 9˜cð 9¸uð 9ÐPTñ 9r#   c                	óº   <€ \         SV `  4        Wn        W n        \	        4       V n        \        R 4      V n        \        R4      V n        \        R4      V n	        R# )r£   Únearestro   N)
r)   r*   r¨   r©   rE   Únetr„   ÚinterpolatorÚ_nearestÚ	_bilinear)r0   r¨   r©   r1   s   &&&€r    r*   ÚXFeat.__init__Ï  sG   ø€ Ü‰ÑÔØŒ
Ø#6Ô Ü“<ˆŒÜ/°	Ó:ˆÔÜ+¨IÓ6ˆŒÜ,¨ZÓ8ˆŽr#   c               ó$   € V ^8„  d   QhRRRRRR/# )r   r¨   r   r©   r›   r   r¥   r   )r   s   "r    r!   rª   Ù  s"   € ÷ ñ  Cð ÀUð ÐV[ñ r#   c                óœ   € V ! WR7      p\        V P                  RR7      pVP                  P                  V4       VP	                  4        V# )aE  Instantiate XFeat with pretrained weights downloaded from the official release.

Args:
    top_k: maximum number of keypoints to keep. Default: ``4096``.
    detection_threshold: the keypoint heatmap value a keypoint must exceed. Default: ``0.05``.

Returns:
    XFeat model with pretrained weights loaded, set to eval mode.
)r¨   r©   zxfeat.pt)Ú	file_name)r	   r¦   r­   Úload_state_dictÚeval)Úclsr¨   r©   ÚmodelÚ
state_dicts   &&&  r    Úfrom_pretrainedÚXFeat.from_pretrainedØ  s>   € ñ ˜%ÔIˆÜ-¨c¯o©oÈÔTˆ
Ø�	‰	×!Ñ! *Ô-Ø�
‰
ŒØˆr#   c               ó    € V ^8„  d   QhRRRR/# )r   r4   r5   r   z!Tuple[torch.Tensor, float, float]r   )r   s   "r    r!   rª   í  s   € ÷ 
?ñ 
? Lð 
?Ð5Vñ 
?r#   c                óp  € \        VP                  4       ^8H  R4       VP                  RR w  r#V P                  W#4      w  rEW$,          W5,          rv\        P
                  ! VP                  4       WE3RRR7      pVP                  \        V P                  P                  4       4      P                  4      Wg3# )zÖResize to the largest multiple of 32 not exceeding the input size (min 32); return image and scale ratios.

Pixel ``i`` of the resized image has its centre at ``(i + 0.5) * r - 0.5`` of the input, for ratio ``r``.
z'Input must be a 4-D tensor (B, C, H, W)Nro   Frp   rs   )r   rm   r`   Ú_resized_sizerx   ry   r›   r�   Únextr­   Ú
parametersr�   )r0   r4   rg   rh   Ú_HÚ_WÚrhÚrws   &&      r    Ú_preprocess_tensorÚXFeat._preprocess_tensorí  s�   € ô
 	�Q—U‘U“W ‘\Ð#LÔMØ�w‰w�r�sˆ|‰ˆØ×#Ñ# AÓ)‰ˆØ•˜�ˆBÜ�MŠM˜!Ÿ'™'›) b X°JÈeÔTˆØ�t‰t”D˜Ÿ™×,Ñ,Ó.Ó/×5Ñ5Ó6¸Ð>Ð>r#   c               ó$   € V ^8„  d   QhRRRRRR/# )r   Úhr   Úwr   zTuple[int, int]r   )r   s   "r    r!   rª   ú  s&   € ÷ @ñ @˜ð @ ð @¨ñ @r#   c                ój   € \        ^ V ^ ,          ^ ,          4      \        ^ V^ ,          ^ ,          4      3# )z_Return the size :meth:`_preprocess_tensor` resizes ``(h, w)`` to: multiples of 32, at least 32.)Úmax)rÈ   rÉ   s   &&r    r¾   ÚXFeat._resized_sizeù  s-   € ô �2˜˜R� 2•~Ó&¬¨B°°bµ¸BµÓ(?Ð?Ð?r#   c               ó(   € V ^8„  d   QhRRRRRRRR/# )r   r4   r5   Úfactorr›   Úmkptsr   r   )r   s   "r    r!   rª   þ  s)   € ÷ 	>ñ 	>˜lð 	>°Eð 	>À,ð 	>ÐS_ñ 	>r#   c                óB  € VP                   RR w  rEV P                  WE4      w  rg\        WW,          V,          WF,          V,          .VP                  \        P
                  ! 4       R7      pVP                  VP                   ^ ,          VP                   ^,          ^4      # )aC  Return input pixels per pixel of what the network saw, ``(B, K, 2)`` in x and y, for keypoints of ``x``.

``x`` is the input rescaled by ``factor`` (1 for the input itself); :meth:`_preprocess_tensor` then resizes it
by the ratio ``r`` of its side to a multiple of 32, so one pixel there spans ``r / factor`` input pixels.
NrŽ   rs   )r`   r¾   r
   r�   ru   Úget_default_dtypeÚexpand)	r0   r4   rÎ   rÏ   rÈ   rÉ   Ú_hÚ_wÚcells	   &&&&     r    Ú_cell_scalesÚXFeat._cell_scalesþ  sw   € ð �w‰w�r�sˆ|‰ˆØ×#Ñ# AÓ)‰ˆÜ ¥¨¥°µ¸&µÐAÈ%Ï,É,Ô^c×^uÒ^uÓ^wÔxˆØ�{‰{˜5Ÿ;™; q�>¨5¯;©;°q­>¸1Ó=Ð=r#   c               ó$   € V ^8„  d   QhRRRRRR/# )r   Úkptsr5   Úsoftmax_tempr›   r   r   )r   s   "r    r!   rª   
  s&   € ÷ Jñ J ð J¸Eð JÈLñ Jr#   c                ó  € \         P                  ! W,          ^4      R,          pVP                  w  r4rVVP                  ^ ^^^4      P	                  W5V^^4      pVP                  ^ ^^^^4      P	                  V^V^,          V^,          4      # )z@Convert 65-channel keypoint logits to a full-resolution heatmap.)ºNNN:Né@   N)rx   Úsoftmaxr`   rc   rb   )rÙ   rÚ   Úscoresre   Ú_rg   rh   r€   s   &&      r    Ú_get_kpts_heatmapÚXFeat._get_kpts_heatmap	  s~   € ô —’˜4Õ.°Ó2°6Õ:ˆØ—\‘\‰
ˆˆaØ—.‘.  A q¨!Ó,×4Ñ4°Q¸1¸aÀÓCˆØ�‰˜q ! Q¨¨1Ó-×5Ñ5°a¸¸AÀ½EÀ1ÀqÅ5ÓIÐIr#   c               ó(   € V ^8„  d   QhRRRRRRRR/# )r   r4   r5   Ú	thresholdr›   r   r   r   r   )r   s   "r    r!   rª     s)   € ÷ 	ñ 	�ð 	¨ð 	ÀCð 	ÐP\ñ 	r#   c           	     ó¼  € V P                   ^ ,          p\        WV3RR7      W8„  ,          pV Uu. uF(  qUP                  4       R,          P                  R4      NK*  	  pp\	        R V 4       ^ R7      p\
        P                  ! W7^3R\
        P                  V P                  R7      p\        V4       F   p	Wi,          W‰R\        Wi,          4      13&   K"  	  V# u upi )	zSNon-maximum suppression on a heatmap; returns (B, N, 2) integer keypoint positions.T)Ú	mask_onlyc              3  ó8   "  € T F  p\        V4      x € K  	  R # 5ir‰   )Úlen)Ú.0Úps   & r    Ú	<genexpr>ÚXFeat._nms.<locals>.<genexpr>  s   é € Ð3¡{ !”s˜1—v�v£{ùs   ‚)Údefault©r�   r�   N).:r;   NNrt   )r`   r   ÚnonzeroÚfliprË   ru   ÚfullÚlongr�   Úrangerè   )
r4   rä   r   re   r˜   ÚkÚpos_batchedÚpad_valÚpos_outÚbs
   &&&       r    Ú_nmsÚ
XFeat._nms  s¸   € ð �G‰G�A�JˆÜ�A [Ð1¸TÔBÀaÁmÕTˆÙ>AÓB¹c¸—y‘y“{ 7Õ+×0Ñ0°Ö4¹cˆÐBÜÑ3¡{Ó3¸QÔ?ˆÜ—*’*˜a¨!˜_¨b¼¿
¹
È1Ï8É8ÔTˆÜ�q–ˆAØ0;µˆGÐ,œ˜[�^Ó,Ð,Ð,Ó-ñ àˆùò Cs   °.Cc               ó(   € V ^8„  d   QhRRRRRRRR/# )r   rÈ   r   rÉ   r�   ztorch.devicer   r5   r   )r   s   "r    r!   rª     s.   € ÷ Jñ J�cð J˜cð J¨<ð J¸Lñ Jr#   c                óú   € \         P                  ! \         P                  ! WR7      \         P                  ! WR7      RR7      w  r4\         P                  ! VR,          VR,          .R4      P	                  R^4      # )z@Create a grid of (x, y) pixel coordinates of shape ``(H*W, 2)``.©r�   Úij©Úindexing©.Nrt   )ru   ÚmeshgridÚarangeÚcatrb   )rÈ   rÉ   r�   Úyr4   s   &&&  r    Ú
_create_xyÚXFeat._create_xy  sV   € ô �~Š~œeŸlšl¨1Ô<¼e¿lºlÈ1Ô>\ÐgkÔl‰ˆÜ�yŠy˜!˜I�,¨¨)­Ð5°rÓ:×BÑBÀ2ÀqÓIÐIr#   c               ó$   € V ^8„  d   QhRRRRRR/# )r   Úheatmapsr5   Útempr›   r   r   )r   s   "r    r!   rª   $  s!   € ÷ /ñ / Lð /¸ð /Èñ /r#   c                ó†  € V P                   w  r#p\        P                  ! WP                  W#V,          4      ,          R4      P                  W#V4      p \        P                  ! \        P
                  ! W@P                  R7      \        P
                  ! W0P                  R7      RR7      w  rVWT^,          ^,
          ,
          pWc^,          ^,
          ,
          p\        P                  ! VR,          V ,          R,          VR,          V ,          R,          .R4      pVP                  W#V,          ^4      P                  ^4      # )a  Compute soft-argmax offsets from an (N, H, W) heatmap, measured from bin ``(W // 2 - 1, H // 2 - 1)``.

That bin, not the window centre the reference implementation uses, is where the pretrained fine matcher puts
a zero displacement; see the XFeat* note of :class:`XFeat`.
rý   Úxyrÿ   Nrt   r  )	r`   ru   rÞ   Úviewr  r  r�   r  Úsum)r	  r
  ÚNrg   rh   r4   r  Úcoordss   &&      r    Ú_subpix_softmax2dÚXFeat._subpix_softmax2d#  sæ   € ð —.‘.‰ˆˆaÜ—=’= ¯©°a¸Q½Ó(?Õ!?ÀÓD×IÑIÈ!ÐPQÓRˆÜ�~Š~Ü�LŠL˜§?¡?Ô3´U·\²\À!ÏOÉOÔ5\Ðgkô
‰ˆð �a•˜!•ÕˆØ�a•˜!•ÕˆÜ—’˜Q˜t�W xÕ/°Õ;¸aÀ½gÈÕ>PÐR[Õ=\Ð]Ð_aÓbˆØ�{‰{˜1 !�e QÓ'×+Ñ+¨AÓ.Ð.r#   c               ó(   € V ^8„  d   QhRRRRRRRR/# )r   Úfeats1r5   Úfeats2Ú
min_cossimr›   r   ú!Tuple[torch.Tensor, torch.Tensor]r   )r   s   "r    r!   rª   4  s,   € ÷ ñ Ø"ðØ,8ðØFKðà	*ñr#   c                ó   € VP                   ^ ,          ^ 8X  g   VP                   ^ ,          ^ 8X  dC   \        P                  ! ^ \        P                  VP                  R7      pWDP                  4       3# WP                  4       ,          pW!P                  4       ,          pVP                  ^R7      w  rxVP                  ^R7      w  ry\        P                  ! \        V4      VP                  R7      p
W˜,          V
8H  pV^ 8”  d:   VP                  ^R7      w  rÇWÃ8„  pW«V,          ,          p
W‹V,          ,          pW®3# W«,          p
W‹,          pW®3# )zDMutual nearest-neighbour matching on L2-normalised descriptor pairs.rî   ©rm   rý   )
r`   ru   Úemptyrò   r�   ÚcloneÚtrË   r  rè   )r0   r  r  r  r  ÚcossimÚcossim_trà   Úmatch12Úmatch21Úidx0ÚmutualÚ
cossim_maxÚgoodÚidx1s   &&&&           r    Ú
_match_mnnÚXFeat._match_mnn4  s  € ð �<‰<˜�?˜aÔ 6§<¡<°¥?°aÔ#7Ü—K’K ¬¯©¸F¿M¹MÔJˆEØŸ+™+›-Ð'Ð'àŸ(™(›*Õ$ˆØŸH™H›JÕ&ˆØ—Z‘Z A�ZÓ&‰
ˆØ—\‘\ a�\Ó(‰
ˆÜ�|Š|œC ›L°·±Ô@ˆØÕ! TÑ)ˆØ˜Œ>Ø"ŸJ™J¨1˜JÓ-‰MˆJØÑ*ˆDØ �Õ&ˆDØ D�=Õ)ˆDð ˆzÐð •<ˆDØ•?ˆDØˆzÐr#   c               ó(   € V ^8„  d   QhRRRRRRRR/# )r   r  r5   r  r  r›   r   ú'List[Tuple[torch.Tensor, torch.Tensor]]r   )r   s   "r    r!   rª   N  s,   € ÷ ñ Ø"ðØ,8ðØFKðà	0ñr#   c           
     óÐ  € VP                   ^ ,          p\        P                  ! WP                  ^ ^^4      4      p\        P                  ! VRR7      pV^ 8”  d   VP                  RR7      MRp?\        P                  ! \        P                  ! W!P                  ^ ^^4      4      RR7      p\        P                  ! VP                   ^,          VP                  R7      p	. p
\        V4       Fv  pW‹,          Wk,          ,          V	8H  pVe   WÇV,          V8„  ,          p\        P                  ! V4      P                  R4      pV
P                  WÖV,          V,          34       Kx  	  V
# )z@Batched MNN matching; returns a list of ``(idx0, idx1)`` tuples.r  Nrý   rt   )r`   ru   Úbmmrc   ÚargmaxÚamaxr  r�   ró   rï   rŸ   Úappend)r0   r  r  r  re   r  r  r#  r   r!  Úbatched_matchesrø   ÚkeepÚrowss   &&&&          r    Ú_batch_matchÚXFeat._batch_matchN  s  € ð �L‰L˜�OˆÜ—’˜6§>¡>°!°Q¸Ó#:Ó;ˆÜ—,’,˜v¨2Ô.ˆØ,6¸¬N�V—[‘[ R�[Ô(Àˆ
àô —,’,œuŸyšy¨·±ÀÀ1ÀaÓ1HÓIÈrÔRˆÜ�|Š|˜GŸM™M¨!Õ,°W·^±^ÔDˆØˆÜ�q–ˆAØ•:˜g�jÕ)¨TÑ1ˆDØÒ%Ø¨!�}¨zÑ9Õ:�ä—=’= Ó&×.Ñ.¨rÓ2ˆDØ×"Ñ" D°!­*°TÕ*:Ð#;Ö<ñ ð Ðr#   c               ó$   € V ^8„  d   QhRRRRRR/# )r   r4   r5   r¨   úOptional[int]r   r  r   )r   s   "r    r!   rª   g  s"   € ÷ ñ  ð °]ð ÐNoñ r#   c           	     óØ  € V P                  V4      w  rpV P                  V4      w  rVpVP                  w  r‰r«Vf	   W«,          pV P                  W«VP                  4      ^,          P                  VRR4      pVP                  ^ ^^^4      P                  ^^R7      pVP                  ^ ^^^4      P                  ^R7      pV^8  d8   \        P                  ! V^ ^VP                  R7      VP                  V^ V	4      3# \        P                  ! V\        VP                  ^,          V4      RR7      w  rÞ\        P                  ! V^VR,          P                  RRV	4      4      p\        P                  ! V^VR,          P                  RR^4      4      p\        WC.VP                  \        P                  ! 4       R7      pVR,           VP!                  ^R4      ,          R,
          pVV3# )	z„Extract coarse descriptors from an FPN feature map, top-k by reliability.

``top_k=None`` keeps every cell; ``top_k=0`` keeps none.
r]   )r^   rý   )rô   rm   rŽ   ç      à?rt   r  )rÅ   r­   r`   r  r�   rÒ   rc   rd   ru   ÚzerosÚ	new_zerosÚtopkÚminÚgatherr
   rÑ   r  )r0   r4   r¨   Úrh1Úrw1ÚM1Ú_K1ÚH1re   rf   Ú_H1Ú_W1Úxy1rà   Ú	top_k_idxr   rÏ   Úscales   &&&               r    Ú_extract_denseÚXFeat._extract_denseg  s–  € ð
 ×-Ñ-¨aÓ0‰ˆ�Ø—h‘h˜q“k‰ˆ�ØŸ™‰ˆˆcØŠ=Ø•IˆEØ�‰˜s¨¯©Ó3°aÕ7×?Ñ?ÀÀ2ÀrÓJˆØ�Z‰Z˜˜1˜a Ó#×+Ñ+°aÀÐ+ÓCˆØ�Z‰Z˜˜1˜a Ó#×+Ñ+°aÐ+Ó8ˆØ�1Œ9Ü—;’;˜q ! Q¨r¯y©yÔ9¸2¿<¹<ÈÈ1ÈaÓ;PÐPÐPÜ—z’z "¬¨B¯H©H°Q­K¸Ó(?ÀRÔH‰ˆÜ—’˜R  I¨iÕ$8×$?Ñ$?ÀÀBÈÓ$JÓKˆÜ—’˜S ! Y¨yÕ%9×%@Ñ%@ÀÀRÈÓ%KÓLˆä  
°5·<±<Äu×G^ÒG^ÓG`ÔaˆØ˜• §
¡
¨1¨bÓ 1Õ1°CÕ7ˆØ�eˆ|Ðr#   c          
     ó,   € V ^8„  d   QhRRRRRRRRRR	/# )
r   r4   r5   r¨   r5  Ús1r›   Ús2r   z=Tuple[torch.Tensor, torch.Tensor, torch.Tensor, torch.Tensor]r   )r   s   "r    r!   rª   ~  s;   € ÷  _ñ  _Øð _Ø&3ð _Ø9>ð _ØJOð _à	Fñ _r#   c                óR  € Vf   R;rVM$\        VR,          4      p\        V4      V,
          p\        P                  ! WRRR7      pV P                  Wv4      w  r‰V P	                  WtV4      p
V^ 8X  df   VP                  VP                  ^ ,          ^ ^34      pV	P                  V	P                  ^ ,          ^ V	P                  R
,          34      pV
R,          pM>\        P                  ! WRRR7      pV P                  Wå4      w  r¼V P	                  WãV4      p\        P                  ! VR,           V,          R,
          VR,           V,          R,
          .^R7      p\        P                  ! VP                  R,          VP                  R	7      ^V,          ,          p\        P                  ! VP                  R,          VP                  R	7      ^V,          ,          p\        P                  ! WÚ.^R7      pV\        P                  ! VV.^R7      \        P                  ! WÉ.^R7      V3# )a  Extract dense features at two scales and merge; return keypoints, scales, descriptors and cell scales.

``top_k`` is split into ``int(0.2 * top_k)`` for the first scale and the rest for the second;
``None`` keeps every cell of both. A zero share yields no cell from its scale.
Ngš™™™™™É?Fro   )Úscale_factorrr   rq   r7  r  ºNr   Nrý   rt   )rÜ   :Né    N)r   rx   ry   rG  rÖ   Ú	new_emptyr`   ru   r  Úonesr�   )r0   r4   r¨   rJ  rK  Úk1Úk2r{   Úmkpts_2Úfeats_2Úcell_2Úmkpts_1Úfeats_1Úcell_1rz   rÏ   Úsc1Úsc2rÕ   s   &&&&&              r    Ú_extract_dualscaleÚXFeat._extract_dualscale~  s·  € ð Š=ØˆNˆB�ä�U˜T•\Ó"ˆBÜ�U“˜b•ˆBÜ�]Š]˜1¸UÈÔTˆØ×.Ñ.¨rÓ6ÑˆØ×"Ñ" 2¨7Ó3ˆØ�Œ7ð ×'Ñ'¨¯©°qÕ)9¸1¸aÐ(@ÓAˆGØ×'Ñ'¨¯©°qÕ)9¸1¸g¿m¹mÈBÕ>OÐ(PÓQˆGØ˜E•]‰Fä—’˜qÀÈZÔXˆBØ#×2Ñ2°2Ó:ÑˆGØ×&Ñ& r¨wÓ7ˆFô —	’	˜G c�M¨RÕ/°#Õ5¸À#½ÈÕ7KÈcÕ7QÐRÐXYÔZˆÜ�jŠj˜Ÿ™ rÕ*°7·>±>ÔBÀaÈ"ÅfÕMˆÜ�jŠj˜Ÿ™ rÕ*°7·>±>ÔBÀaÈ"ÅfÕMˆÜ�yŠy˜&Ð)¨qÔ1ˆØ”e—i’i  c 
°Ô2´E·I²I¸wÐ>PÐVWÔ4XÐZ^Ð^Ð^r#   c               ó0   € V ^8„  d   QhRRRRRRRRRR	R
R/# )r   Úd0úDict[str, torch.Tensor]Úd1Úmatchesr)  Ú	batch_idxr   Ú	fine_confr›   r   r5   r   )r   s   "r    r!   rª      sN   € ÷ Gñ Gà#ðGð $ðGð 9ð	Gð
 ðGð ðGð 
ñGr#   c                óø  € W4,          w  rgVR,          V,          V,          pVR,          V,          V,          p	VR,          V,          V,          P                  4       p
VR,          V,          V,          pVR,          V,          V,          pVR,          V,          V,          pV P                  P                  \        P                  ! W‰.RR7      4      p\
        P                  ! V^,          RR7      P                  RR7      ^ ,          pV P                  VP                  R^^4      4      pW®V,          ,           RV,          ,           p
VRV,          ,           p\        P                  ! W«.RR7      Wõ8„  ,          # )zORefine coarse match positions using the fine-matcher MLP with subpixel softmax.Údescriptorsr�   Úcell_scalesr  ç      @rt   )
r  r­   rX   ru   r  rx   rÞ   rË   r  r  )r0   r_  ra  rb  rc  rd  r!  r%  r  r  Úmkpts_0rW  Úcell0Úcell1ÚoffsetsÚconfs   &&&&&&          r    Ú_refine_matchesÚXFeat._refine_matches   s4  € ð Õ'‰
ˆØ�MÕ" 9Õ-¨dÕ3ˆØ�MÕ" 9Õ-¨dÕ3ˆØ�[•/ )Õ,¨TÕ2×8Ñ8Ó:ˆØ�[•/ )Õ,¨TÕ2ˆØ�=Õ! )Õ,¨TÕ2ˆØ�=Õ! )Õ,¨TÕ2ˆØ—(‘(×'Ñ'¬¯	ª	°6Ð2BÈÔ(KÓLˆÜ�yŠy˜ 1�¨"Ô-×1Ñ1°bÐ1Ó9¸!Õ<ˆØ×(Ñ(¨¯©°b¸!¸QÓ)?Ó@ˆð  e�OÕ+¨c°E­kÕ9ˆØ˜C %�KÕ'ˆä�yŠy˜'Ð+°Ô4°TÑ5EÕFÐFr#   c               ó(   € V ^8„  d   QhRRRRRRRR/# )	r   r4   r5   r¨   r5  r©   zOptional[float]r   zList[Dict[str, torch.Tensor]]r   )r   s   "r    r!   rª   Ä  s2   € ÷ =ñ =àð=ð ð=ð -ð	=ð
 
'ñ=r#   c           
     ó  € Vf   V P                   pVf   V P                  pV P                  V4      w  rpVP                  w  rgr‰V P	                  V4      w  r«pVP
                  \        P                  8X  d   \        M\        P                  pV! V
P                  VP
                  4      ^R7      P                  VP
                  4      p
V P                  V4      pV P                  Wã^R7      pV P                  WïW‰4      V P                  WÏW‰4      ,          P!                  R4      P                  VP
                  4      pRV\        P"                  ! VR8H  RR7      &   \%        VVP                  R,          4      p\        P&                  ! VVRRRR7      w  pp\        P(                  ! VR,          RV4      p\        P(                  ! VR,          RV4      p\        P*                  ! VR,          VR,          .RR7      pV P-                  W¯W‰R7      pV! VRR7      P                  VP
                  4      p\/        WT.VP0                  \        P2                  ! 4       R7      pVR,           VP5                  ^^R4      ,          R,
          p. p\7        V4       Fs  p\        P8                  ! VV,          ^ 8„  4      P!                  R4      pVP;                  RVV,          V,          R	VV,          V,          R
VV,          V,          /4       Ku  	  V# )a0  Detect sparse keypoints and compute descriptors.

Args:
    x: image tensor of shape ``(B, C, H, W)``.
    top_k: number of keypoints to keep (overrides ``self.top_k``).
    detection_threshold: the heatmap value to exceed (overrides ``self.detection_threshold``).

Returns:
    List of length ``B``. Each element is a dict with:

    - ``'keypoints'``: ``(N, 2)`` keypoints in (x, y) pixel coordinates.
    - ``'scores'``: ``(N,)`` keypoint heatmap value times reliability, in descending order.
    - ``'descriptors'``: ``(N, 64)`` L2-normalised descriptors.
r  )rä   r   T)rô   rm   ÚlargestÚsorted)rg   rh   rŽ   r7  r�   rß   rf  rt   ).rO  ).r;   r  )r¨   r©   rÅ   r`   r­   r�   ru   Úfloat16r   rx   Ú	normalizer�   rá   rù   r¯   r°   rŸ   Úallr;  r:  r<  r  r®   r
   r�   rÑ   r  ró   rï   r.  )r0   r4   r¨   r©   r=  r>  re   rà   rB  rC  r?  ÚK1rA  ru  ÚK1hrÏ   rß   rô   ÚidxsÚmkpts_xÚmkpts_yr   rF  Úresultsrø   r1  s   &&&&                      r    ÚdetectAndComputeÚXFeat.detectAndComputeÃ  sp  € ð* Š=Ø—J‘JˆEØÒ&Ø"&×":Ñ":ÐØ×-Ñ-¨aÓ0‰ˆ�ØŸ™‰ˆˆcà—X‘X˜a“[‰
ˆ�ð
 &'§W¡W´·±Ô%=•MÄ1Ç;Á;ˆ	ñ �r—u‘u˜QŸW™W“~¨1Ô-×0Ñ0°·±Ó9ˆà×$Ñ$ RÓ(ˆØ—	‘	˜#È!�	ÓLˆà—-‘- ¨CÓ5¸¿¹ÀrÐRUÓ8[Õ[×dÑdÐegÓh×kÑkÐlm×lsÑlsÓtˆØ13ˆŒu�yŠy˜ "™¨"Ô-Ñ.ä��v—|‘| BÕ'Ó(ˆÜ—z’z &¨A°2¸tÈDÔQ‰ˆ�Ü—,’,˜u V�}¨b°$Ó7ˆÜ—,’,˜u V�}¨b°$Ó7ˆÜ—	’	˜7 9Õ-¨w°yÕ/AÐBÈÔKˆà×!Ñ! "¨sÐ!Ó:ˆÙ˜% RÔ(×+Ñ+¨A¯G©GÓ4ˆô    
°5·<±<Äu×G^ÒG^ÓG`ÔaˆØ˜• §
¡
¨1¨a°Ó 4Õ4°sÕ:ˆàˆÜ�q–ˆAä—=’= ¨¥¨Q¡Ó/×7Ñ7¸Ó;ˆDØ�N‰N˜K¨¨q­°$­¸À6È!Å9ÈTÅ?ÐTaÐchÐijÕckÐlpÕcqÐrÖsñ ð ˆr#   c               ó(   € V ^8„  d   QhRRRRRRRR/# ©	r   r4   r5   r¨   r5  Ú
multiscaler   r   r`  r   )r   s   "r    r!   rª     s8   € ÷ kñ kàðkð ðkð ð	kð
 
!ñkr#   c                ó`   € V P                  WV4      pRVR,          RVR,          RVR,          /# )a“  Detect keypoints and compute dense coarse descriptors.

Args:
    x: image tensor of shape ``(B, C, H, W)``.
    top_k: number of features to keep (overrides ``self.top_k``). A value below 1 keeps every cell. With
        ``multiscale=True`` the budget is split between the scales, ``int(0.2 * top_k)`` for the 0.6x
        extraction and the rest for the 1.3x one, so the result never exceeds a positive ``top_k``; a scale
        with a budget of 0 contributes nothing. This departs from the reference implementation, which
        gives the 1.3x scale ``int(0.8 * top_k)`` and reads a budget that rounds down to 0 as "every cell".
    multiscale: use dual-scale (0.6x and 1.3x) extraction. Default: ``True``.

Returns:
    Dict with:

    - ``'keypoints'``: ``(B, K, 2)`` coarse keypoints.
    - ``'descriptors'``: ``(B, K, 64)`` coarse descriptors.
    - ``'scales'``: ``(B, K)`` extraction scale per keypoint.
r�   rf  Úscales)Ú_detect_dense)r0   r4   r¨   r�  Úouts   &&&& r    ÚdetectAndComputeDenseÚXFeat.detectAndComputeDense  s;   € ð2 × Ñ  ¨:Ó6ˆØ˜S Õ-¨}¸cÀ-Õ>PÐRZÐ\_Ð`hÕ\iÐjÐjr#   c               ó(   € V ^8„  d   QhRRRRRRRR/# r€  r   )r   s   "r    r!   rª     s/   € ÷ ]ñ ]˜|ð ]°Mð ]Ètð ]ÐXoñ ]r#   c                ó8  € Vf   V P                   pV^8¼  d   TMRpV'       d   V P                  W4      w  rVrxMYV P                  W4      w  rW\        P                  ! VP
                  R,          VP                  R7      pV P                  VRV4      pRVRVRVRV/# )	zÊReturn :meth:`detectAndComputeDense`'s dict plus ``'cell_scales'``, which :meth:`_refine_matches` reads.

``'cell_scales'`` is ``(B, K, 2)``: input pixels per pixel of what the network saw, in x and y.
NrN  rý   r�   r�   rf  rƒ  rg  )r¨   r\  rG  ru   rQ  r`   r�   rÖ   )	r0   r4   r¨   r�  ÚbudgetrÏ   Úscr   rÕ   s	   &&&&     r    r„  ÚXFeat._detect_dense  s“   € ð
 Š=Ø—J‘JˆEà 1œ*‘¨$ˆßØ%)×%<Ñ%<¸QÓ%GÑ"ˆE�u˜dà×.Ñ.¨qÓ9‰LˆEÜ—’˜EŸK™K¨�O°E·L±LÔAˆBØ×$Ñ$ Q¨¨UÓ3ˆDØ˜U M°5¸(ÀBÈÐW[Ð\Ð\r#   c          
     ó,   € V ^8„  d   QhRRRRRRRRRR	/# )
r   Úimg1r5   Úimg2r¨   r5  r  r›   r   ú6List[torch.Tensor] | Tuple[torch.Tensor, torch.Tensor]r   )r   s   "r    r!   rª   1  s=   € ÷ )ñ )àð)ð ð)ð ð	)ð
 ð)ð 
@ñ)r#   c                ó*  € \        VP                  ^ ,          VP                  ^ ,          8H  R4       Vf   V P                  pV P                  WR7      pV P                  W#R7      p. p\	        WV4       FX  w  r‰V P                  VR,          V	R,          VR7      w  r«VP                  VR,          V
,          V	R,          V,          34       KZ  	  \        V4      ^8w  d)   V Uu. uF  p\        P                  ! VRR7      NK  	  up# V^ ,          # u upi )a’  Detect, describe and mutually match keypoints from two batches of images.

Pair ``b`` is image ``b`` of ``img1`` with image ``b`` of ``img2``. Each batch goes through
:meth:`detectAndCompute` in one call, and then the descriptors of each pair are matched on their own by
mutual nearest neighbour. A backend may round a batched convolution differently from a single-image one (MPS,
and CUDA with cuDNN's default TF32 convolutions), so a pair matched in a batch can gain or lose a few
near-tied matches compared with matching it alone.

Args:
    img1: first images ``(B, C, H, W)``.
    img2: second images ``(B, C, H, W)``, with the same ``B`` as ``img1``.
    top_k: number of top keypoints to use.
    min_cossim: the cosine similarity a match must exceed; a value of 0 or below, such as the default
        ``-1``, disables the check.

Returns:
    If ``B != 1``: list of ``(N, 4)`` tensors with ``(x1, y1, x2, y2)`` matches, one per pair; an empty
    batch gives an empty list.
    If ``B == 1``: tuple ``(mkpts0, mkpts1)`` of matched keypoints, each ``(N, 2)``.

See Also:
    :meth:`match_xfeat_star`: the dense, refined variant, with the same return convention.
z1img1 and img2 must hold the same number of images)r¨   rf  )r  r�   r  rt   )
r   r`   r¨   r}  Úzipr&  r.  rè   ru   r  )r0   rŽ  r�  r¨   r  Úout1Úout2ÚpairsÚf1Úf2r!  r%  Úpairs   &&&&&        r    Úmatch_xfeatÚXFeat.match_xfeat0  sì   € ô> 	�T—Z‘Z •] d§j¡j°¥mÑ3Ð5hÔiØŠ=Ø—J‘JˆEØ×$Ñ$ TÐ$Ó7ˆØ×$Ñ$ TÐ$Ó7ˆØˆÜ˜$–o‰FˆBØŸ™¨¨MÕ):¸B¸}Õ<MÐZd˜Óe‰JˆDØ�L‰L˜"˜[�/¨$Õ/°°KµÀÕ1FÐGÖHñ &ô ˆu‹:˜Œ?Ù8=Ó>¹°”E—I’I˜d¨×+¹Ñ>Ð>Ø�Q�xˆùò ?s   Ã#!Dc               ó(   € V ^8„  d   QhRRRRRRRR/# )r   Úim_set1r5   Úim_set2r¨   r5  r   r�  r   )r   s   "r    r!   rª   ]  s3   € ÷ 4ñ 4àð4ð ð4ð ð	4ð
 
@ñ4r#   c           
     ó€  € Vf   V P                   pV P                  WR4      pV P                  W#R4      pV P                  VR,          VR,          4      pVP                  ^ ,          p\	        V4       Uu. uF  q€P                  WEWhR7      NK  	  p	pV^8w  d   V	# V	^ ,          R,          V	^ ,          R,          3# u upi )a÷  Extract coarse features, match pairs and refine matches (XFeat*).

Both matched cells are anchored three pixels into the cell, in pixels of the image the network saw. The first
point also receives the fine displacement measured from bin 3. Raw :meth:`detectAndComputeDense` coordinates
stay at the top-left cell origin; see the class note for the coordinate convention.

Args:
    im_set1: batch of images ``(B, C, H, W)``.
    im_set2: batch of images ``(B, C, H, W)``, with the same ``B`` as ``im_set1``.
    top_k: number of top features to use.

Returns:
    If ``B != 1``: list of ``(N, 4)`` tensors with ``(x1, y1, x2, y2)`` matches, one per pair; an empty
    batch gives an empty list.
    If ``B == 1``: tuple of ``(N, 2)`` matched keypoint tensors.
Trf  )rb  rc  )rÜ   rN  )rÜ   :r   NN)r¨   r„  r2  r`   ró   rn  )
r0   rœ  r�  r¨   r“  r”  Ú	idxs_listre   rø   rb  s
   &&&&      r    Úmatch_xfeat_starÚXFeat.match_xfeat_star\  sº   € ð. Š=Ø—J‘JˆEØ×!Ñ! '°$Ó7ˆØ×!Ñ! '°$Ó7ˆØ×%Ñ% d¨=Õ&9¸4ÀÕ;NÓOˆ	Ø�M‰M˜!ÕˆÜ]bÐcdÔ]eÓfÑ]eÐXY×'Ñ'¨¸IÐ'ÖSÑ]eˆÐfØ�Œ6ØˆNØ�q�z˜%Õ  '¨!¥*¨UÕ"3Ð3Ð3ùò gs   Á5B;)r°   r¯   r©   r®   r­   r¨   )i   çš™™™™™©?)r�   )r¢  é   )rh  )g=
×£p=ê?)rt   )i@  )g333333ã?gÍÌÌÌÌÌô?)g      Ð?)NN)NT)Nrt   r‰   ) r<   r=   r>   r?   r@   r¦   Ú__annotations__r*   Úclassmethodrº   rÅ   Ústaticmethodr¾   rÖ   rá   rù   r  r  r&  r2  rG  r\  rn  ru   Úinference_moder}  r†  r„  r™  r   rA   rB   rC   s   @r    r¥   r¥   >  sD  ø‡ ñLð\ b€K�Óa÷9ò 9ð öó ðõ(
?ð ô@ó ð@õ	>ð öJó ðJð ö	ó ð	ð ôJó ðJð
 ö/ó ð/÷ ÷4÷2÷. _÷DGðF ×ÒÓö=ó ð=ð~ ×ÒÓökó ðkõ6]ð" ×ÒÓö)ó ð)ðV ×ÒÓö4ó ö4r#   r¥   )r@   Ú
__future__r   Útypingr   r   r   r   ru   Útorch.nn.functionalr   Ú
functionalrx   Úkornia.core.checkr   Úkornia.core.downloadr	   Úkornia.core.opsr
   Úkornia.core.utilsr   r   r   Úkornia.geometry.subpixr   ÚModuler   rE   r„   r¥   r   r#   r    Ú<module>r²     s|   ðñ$õ #ç .Ó .ã ß Ð Ý å *Ý 9Ý +ß ]Ñ ]Ý (ô)�—‘ô )ôXN)�—‘ô N)ôbO1˜"Ÿ)™)ô O1ôd~4ˆB�I‰Iö ~4r#   