+
     åûjÊ ã                   óÔ  € ^ RI t ^ RIt^ RIt^ RIt^ RIt^ RIHtHt ^ RI	H
t
Ht ^ RIHtHtHt ^ RIHtHt ^ RIHtHtHtHtHtHtHt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'H(t(H)t)H*t*H+t+H,t,H-t-H.t. ^ R	I/H0t0H1t1H2t2 ^ R
I3H4t4H5t5 R R lt6R|R R llt7R}R R llt8R}R R llt9R R lt:R R lt;R~R R llt<R R lt=R R lt>R R lt?R R  lt@R! R" ltARR# R$ lltBR% R& ltCR' R( ltDR) R* ltER+ R, ltFR- R. ltGR/ R0 ltHR1 R2 ltIR€R3 R4 lltJR5 R6 ltKR€R7 R8 lltLR€R9 R: lltMR; R< ltNR= R> ltOR}R? R@ lltPRA RB ltQRC RD ltRRE RF ltSRG RH ltTRI RJ ltURK RL ltVRM RN ltWRO RP ltXRQ RR ltYR€RS RT lltZRU RV lt[RW RX lt\RY RZ lt]R[ R\ lt^]_! ]PÀ                  R]R4      ;'       g    ]_! ]PÂ                  R]R4      tb]_! ]PÀ                  R^R4      tcR_ R` ltdRa Rb lte]PÌ                  PÎ                  Rc Rd l4       th]PÌ                  PÎ                  Re Rf l4       tiRg Rh ltjRi Rj ltkRk Rl ltlRm Rn ltm]! Ro4      tnRp Rq ltoRr Rs ltpRt Ru ltqRv Rw ltrR�Rx Ry lltsRz R{ lttR# )‚é    N)ÚMappingÚSequence)ÚAbstractContextManagerÚnullcontext)ÚasdictÚfieldsÚis_dataclass)Ú	FrameTypeÚ	UnionType)ÚAnyÚDictÚListÚOptionalÚTupleÚTypeÚTypeVarÚUnionÚget_argsÚ
get_originÚget_type_hints)Úinv_ex)Ú_adjugate_2x2Ú_adjugate_3x3Ú_adjugate_4x4Ú_det_perm_2x2Ú_det_perm_3x3Ú_det_perm_4x4Ú_inverse_3x3_crossÚ_inverse_3x3_scalar)ÚKORNIA_CHECKÚKORNIA_CHECK_IS_TENSORÚKORNIA_CHECK_TYPE)ÚDeviceErrorÚTypeCheckErrorc                óD   € V ^8„  d   QhR\         P                  R\        /# ©é   ÚinputÚreturn©ÚtorchÚTensorÚbool)Úformats   "ÚMC:\Ai_Coding\apps\studio\ComfyUI\.venv\Lib\site-packages\kornia\core\utils.pyÚ__annotate__r0   0   s   € ÷ 
:ñ 
:¤E§L¡Lð 
:´Tñ 
:ó    c                ó\   € V P                   \        P                  \        P                  39   # )a  Return whether ``input`` is resampled in float32 and returned in its own dtype: true for float16/bfloat16.

The policy holds on every device. The CPU half ``grid_sample`` kernels are corrupt or missing (#5751). The CUDA
bicubic one is off by more than 1 on a ``[0, 1]`` image, the CUDA and MPS half gradients differ from the float32
ones, and under an autocast of the other half dtype a half ``grid_sample`` raises (#5814). Bilinear and nearest
sampling of a given grid is as accurate in half precision as in float32 on CUDA and MPS, so most of the error of
a half warp came from a sampling grid built in the half dtype, up to 0.98 in bfloat16 on both; the warps that
build their own grid therefore build it in float32 too (``kornia.geometry.transform.imgwarp._runs_in_float32``).
)Údtyper+   Úfloat16Úbfloat16©r(   s   &r/   Ú_samples_half_in_float32r7   0   s    € ð �;‰;œ5Ÿ=™=¬%¯.©.Ð9Ñ9Ð9r1   c                ó²   € V ^8„  d   QhR\         P                  R\         P                  R\        R\        R\        \        ,          R\         P                  /# )r'   r(   ÚgridÚmodeÚpadding_modeÚalign_cornersr)   )r+   r,   Ústrr   r-   )r.   s   "r/   r0   r0   =   s\   € ÷ iñ iÜ�<‰<ðiä
�,‰,ðiô ðiô ð	iô
 œD•>ðiô ‡\�\ñir1   c                ó*  € \        V 4      '       dk   VP                  V P                  8X  dP   \        P                  ! V P	                  4       VP	                  4       W#VR7      P                  V P                  4      # \        P                  ! WW#VR7      # )a«  Run :func:`torch.nn.functional.grid_sample` on 4-D or 5-D input, float16/bfloat16 in float32.

torch's CPU half ``grid_sample`` returns corrupt values on sources of about 128 px and more, and
torch 2.5.1 has no such kernel (#5751). On CUDA the half bicubic kernel is off by more than 1 on a ``[0, 1]``
image, the CUDA and MPS half gradients differ from the float32 ones, and under a float16 ``torch.autocast`` a
bfloat16 input raises (#5814). A half input with a grid of its own dtype is therefore sampled in float32 on every
device and returned in its dtype. A grid of another dtype, and every other input dtype, reach ``grid_sample``
unchanged, which rejects a mismatch as before.
)r:   r;   r<   )r7   r3   ÚFÚgrid_sampleÚfloatÚto)r(   r9   r:   r;   r<   s   &&&&&r/   Ú_torch_grid_samplerC   =   sh   € ô    ×&Ò&¨4¯:©:¸¿¹Ô+DÜ�}Š}Ø�K‰K‹M˜4Ÿ:™:›<¨dÐ]jô
ç
‰"ˆU�[‰[‹/ð	ô �=Š=˜¨4ÐZgÔhÐhr1   c                ó®   € V ^8„  d   QhR\         P                  R\         P                  R\        \         P                  ,          R\         P                  /# )r'   ÚtensorÚdevicer3   r)   )r+   r,   rF   r   r3   )r.   s   "r/   r0   r0   T   sA   € ÷ 31ñ 31Ü�L‰Lð31Ü"'§,¡,ð31Ü7?ÄÇÁÕ7Lð31ä
‡\�\ñ31r1   c                ó^  € \         P                  P                  4       '       dO   V P                  P                  R8H  ;'       d-    VP                  R8H  ;'       d    V P                  4       '       * pMdV P                  P                  R8H  ;'       dD    VP                  R8H  ;'       d-    \        4       '       * ;'       d    V P                  4       '       * pV'       d:   Ve#   W P                  8w  d   V P                  VR7      p V P                  VRR7      # Ve‚   W P                  8w  dr   V P                  V8w  da   VP                  R8X  d#   V P                  VR7      P                  VR7      # V P                  P                  R8X  d   V P                  VR7      p V P                  WR7      # )a¦  Move ``tensor`` to ``device`` (and ``dtype``), without waiting for queued work on a CUDA target.

A blocking host-to-device copy from pageable memory ends in ``cudaStreamSynchronize``, so the host waits
until the GPU has finished everything queued before it. With ``non_blocking=True`` CUDA stages a pageable
source before the call returns, so the source may be changed or freed straight away. A dtype change is made
on the host before the copy, as the blocking copy makes it, so the copied bits are the same, NaN payloads
included.

Only an eager copy from pageable CPU memory to CUDA is non-blocking:

- A pinned source is copied asynchronously by a non-blocking copy and could be changed by its owner before the
  copy lands, so it keeps the blocking copy.
- Under ``torch.compile`` and ``torch.export`` the copy stays blocking, as it was: Inductor (torch 2.14)
  miscompiles a non-blocking copy of a CPU tensor computed inside the graph, such as parameters sampled in a
  compiled ``forward``, and returns wrong values.
- A copy to the CPU stays blocking, because the host could otherwise read it before it arrives, and MPS and
  other targets keep the blocking copy, since they may read the source after the call returns.

A blocking copy that changes both the device and the dtype also casts on the CPU side: a copy to the CPU moves
and then casts, and a copy from the CPU casts and then moves. MPS has no float64. On torch 2.14 a single copy
from MPS to a float64 CPU tensor leaves the destination unwritten (pytorch/pytorch#197715), and so does the
backward of a single copy from a float64 CPU tensor to MPS. On torch 2.15 both raise, as does the backward of a
single copy from MPS to a float64 CPU tensor.

Args:
    tensor: The tensor to move.
    device: The target device.
    dtype: The target dtype, or ``None`` to keep the dtype of ``tensor``.

Returns:
    ``tensor`` itself when it already has the target device and dtype, a copy otherwise.
ÚcpuÚcuda©r3   T)rF   Únon_blocking©rF   ©rF   r3   )	r+   ÚjitÚis_scriptingrF   ÚtypeÚ	is_pinnedÚis_compilingr3   rB   )rE   rF   r3   rK   s   &&& r/   Ú_to_device_nonblockingrS   T   sM  € ôF ‡y�y×Ñ×ÒØ—}‘}×)Ñ)¨UÑ2×gÐg°v·{±{ÀfÑ7L×gÐgÐU[×UeÑUeÓUgÔQg‰ð �M‰M×Ñ %Ñ'×sÐs¨F¯K©K¸6Ñ,A×sÐsÌ,Ë.ÔFX×sÐsÐag×aqÑaqÓasÔ]sð 	÷ ØÒ ¯,©,Ô!6Ø—Y‘Y U�YÓ+ˆFØ�y‰y °TˆyÓ:Ð:ØÒ˜U§l¡lÔ2°v·}±}ÈÔ7Nà�;‰;˜%ÔØ—9‘9 F�9Ó+×.Ñ.°UÐ.Ó;Ð;Ø�=‰=×Ñ Ô&Ø—Y‘Y U�YÓ+ˆFØ�9‰9˜Fˆ9Ó0Ð0r1   c                óš   € V ^8„  d   QhR\         R\        P                  R\        \        P                  ,          R\        P
                  /# )r'   ÚdatarF   r3   r)   )r   r+   rF   r   r3   r,   )r.   s   "r/   r0   r0   Š   s<   € ÷ 	=ñ 	=¤ð 	=¬e¯l©lð 	=Ä8ÌEÏKÉKÕCXð 	=Ôdi×dpÑdpñ 	=r1   c                óŠ   € \        V \        P                  4      '       d   \        WV4      # \        P                  ! WVR7      # )au  Return ``torch.as_tensor(data, device=device, dtype=dtype)``, moving a tensor without waiting for the GPU.

``torch.as_tensor`` of a tensor is ``tensor.to(device, dtype)``, a blocking copy for a CPU tensor and a CUDA
``device``. A tensor is moved without waiting for queued work instead, with the same values; any other ``data``
goes through ``torch.as_tensor`` unchanged.
rM   )Ú
isinstancer+   r,   rS   Ú	as_tensor)rU   rF   r3   s   &&&r/   Ú_as_tensor_nonblockingrY   Š   s3   € ô �$œŸ™×%Ò%Ü% d°EÓ:Ð:Ü�?Š?˜4°eÔ<Ð<r1   c                ó$   € V ^8„  d   QhR\         /# ©r'   r)   ©r-   )r.   s   "r/   r0   r0   –   s   € ÷ =ñ =œ$ñ =r1   c                 óD   € \         P                  P                  R4      RJ# )z6Return whether `torch_xla` is available in the system.Ú	torch_xlaN)Ú	importlibÚutilÚ	find_spec© r1   r/   Úxla_is_availablerc   –   s   € ä�>‰>×#Ñ# KÓ0¸Ð<Ð<r1   c                óD   € V ^8„  d   QhR\         P                  R\        /# ©r'   Úxr)   r*   )r.   s   "r/   r0   r0   ›   s   € ÷ "ñ "œ%Ÿ,™,ð "¬4ñ "r1   c                ó2   € R\        V P                  4      9   # )z'Return whether tensor is on MPS device.Úmps)r=   rF   ©rf   s   &r/   Úis_mps_tensor_saferj   ›   s   € à”C˜Ÿ™“MÑ!Ð!r1   c                óD   € V ^8„  d   QhR\         R\        P                  /# )r'   Úindexr)   )Úintr+   rF   )r.   s   "r/   r0   r0       s   € ÷ ñ ¬ð ´E·L±Lñ r1   c                ó  € \         P                  P                  4       '       dH   ^ T u;8:  d$   \         P                  P                  4       8  d   M M\         P                  ! RV  24      # \         P                  ! R4      # )a^  Return the CUDA device of a given index when CUDA is available, else the CPU.

``device = get_cuda_device_if_available(index)`` returns ``torch.device(f"cuda:{index}")`` when
``torch.cuda.is_available()`` is true and ``index`` is inside ``[0, torch.cuda.device_count())``;
``torch.device("cpu")`` otherwise, so an out-of-range ``index`` on a machine with one GPU never hands
out a ``cuda:3`` device that only fails when a tensor is placed on it.

Args:
    index: the CUDA device index. Falls back to the CPU device when CUDA is unavailable or
        ``index`` is outside ``[0, torch.cuda.device_count())``.

Returns:
    ``cuda:<index>`` or ``cpu``.

See Also:
    - :func:`~kornia.core.utils.get_cuda_or_mps_device_if_available`: picks MPS instead on Apple silicon.
    - :func:`~kornia.core.utils.get_mps_device_if_available`: the MPS device, else the CPU.

zcuda:rH   )r+   rI   Úis_availableÚdevice_countrF   )rl   s   &r/   Úget_cuda_device_if_availablerq       sT   € ô( ‡z�z×Ñ× Ò  Q¨%Ö%K´%·*±*×2IÑ2IÓ2K×%KÜ�|Š|˜e E 7˜OÓ,Ð,ä�<Š<˜ÓÐr1   c                ó8   € V ^8„  d   QhR\         P                  /# r[   ©r+   rF   )r.   s   "r/   r0   r0   º   s   € ÷ ñ ¤U§\¡\ñ r1   c                 óÒ   € Rp \        \        P                  R4      '       d1   \        P                  P                  P	                  4       '       d   Rp \        P
                  ! V 4      # )a×  Return the Apple MPS device when it is available, else the CPU.

``device = get_mps_device_if_available()`` returns ``torch.device("mps")`` when
``torch.backends.mps.is_available()`` is true and ``torch.device("cpu")`` otherwise.

Returns:
    ``mps`` or ``cpu``.

See Also:
    - :func:`~kornia.core.utils.get_cuda_device_if_available`: the CUDA device, else the CPU.
    - :func:`~kornia.core.utils.get_cuda_or_mps_device_if_available`: picks MPS or CUDA by platform.

rH   rh   )Úhasattrr+   Úbackendsrh   ro   rF   )Údevs    r/   Úget_mps_device_if_availablerx   º   sF   € ð €CÜŒu�~‰~˜u×%Ò%¬%¯.©.×*<Ñ*<×*IÑ*I×*KÒ*KØˆÜ�<Š<˜ÓÐr1   c                ó8   € V ^8„  d   QhR\         P                  /# r[   rs   )r.   s   "r/   r0   r0   Î   s   € ÷ *ñ *¬U¯\©\ñ *r1   c                 óˆ   € \         P                  R8X  d%   \        P                  ! 4       R8X  d   \        4       # \	        4       # )a?  Return the platform's accelerator, MPS on Apple silicon and CUDA elsewhere, else the CPU.

``device = get_cuda_or_mps_device_if_available()`` returns :func:`~kornia.core.utils.get_mps_device_if_available` on
macOS on ``arm64`` and :func:`~kornia.core.utils.get_cuda_device_if_available` with index 0 on every other platform.

Returns:
    ``mps``, ``cuda:0`` or ``cpu``.

See Also:
    - :func:`~kornia.core.utils.get_cuda_device_if_available`: the CUDA device of a chosen index.
    - :func:`~kornia.core.utils.get_mps_device_if_available`: the MPS device on any platform.

ÚdarwinÚarm64)ÚsysÚplatformÚmachinerx   rq   rb   r1   r/   Ú#get_cuda_or_mps_device_if_availabler€   Î   s2   € ô ‡|�|�xÔ¤H×$4Ò$4Ó$6¸'Ô$AÜ*Ó,Ð,Ü'Ó)Ð)r1   c                ó¦   € V ^8„  d   QhR\         \        \        ,          ,          R\        \        P
                  \        P                  3,          /# )r'   Útensor_listr)   )r   r   r   r   r+   rF   r3   )r.   s   "r/   r0   r0   á   s8   € ÷ #1ñ #1¤t¬H´S­MÕ':ð #1¼uÄUÇ\Á\ÔSX×S^ÑS^ÐE^Õ?_ñ #1r1   c                óR  € V  Uu. uF'  p\        V\        P                  4      '       g   K%  VNK)  	  ppVR,           Fƒ  pVP                  V^ ,          P                  8w  g   K'  \	        RV^ ,          P                   RVP                   R2V^ ,          P                  VP                  .V^ ,          P                  R7      h	  VR,           Fp  pVP
                  V^ ,          P
                  8w  g   K'  \        RV^ ,          P
                   RVP
                   R2VP
                  V^ ,          P
                  R7      h	  V'       g6   \        P                  ! ^ 4      P                  \        P                  ! 4       3# V^ ,          P                  V^ ,          P
                  3# u upi )a^  Check that the tensors in the list share one device and one dtype, and return them.

Entries that are not tensors (``None`` included) are skipped. Without any tensor, the result is
(``torch.get_default_device()``, ``torch.get_default_dtype()``).

Returns:
    [torch.device, torch.dtype]

Raises:
    DeviceError: if two tensors are on different devices. Every device is checked before any dtype, so this
        error wins when the devices and the dtypes both differ, wherever the mismatches sit in the list.
    TypeCheckError: if all the tensors share one device and two of them have different dtypes.

:é   NNz4Passed tensors are not on the same device: expected z, got Ú.)Úactual_devicesÚexpected_devicez4Passed tensors do not have the same dtype: expected )Úactual_typeÚexpected_type)	rW   r+   r,   rF   r#   r3   r$   ÚemptyÚget_default_dtype)r‚   rE   Útensorss   &  r/   Ú_extract_device_dtyper�   á   sb  € ñ %0ÓT¡K˜&´:¸fÄeÇlÁl×3S�vˆv¡K€GÐTØ˜"—+�+ˆØ�=‰=˜G A�J×-Ñ-Ö-ÜØFÀwÈqÅz×GXÑGXÐFYÐY_Ð`f×`mÑ`mÐ_nÐnoÐpØ '¨¥
× 1Ñ 1°6·=±=ÐAØ '¨¥
× 1Ñ 1ôð ñ ð ˜"—+�+ˆØ�<‰<˜7 1�:×+Ñ+Ö+Ü ØFÀwÈqÅz×GWÑGWÐFXÐX^Ð_e×_kÑ_kÐ^lÐlmÐnØ"ŸL™LØ% a�j×.Ñ.ôð ñ ÷ ô —’˜A“×%Ñ%¤u×'>Ò'>Ó'@ÐAÐAØ�A�J×Ñ˜w q�z×/Ñ/Ð0Ð0ùò) Us
   …"F$¬F$c                óX   € V ^8„  d   QhR\         P                  R\         P                  /# )r'   r3   r)   )r+   r3   )r.   s   "r/   r0   r0     s&   € ÷ 	Oñ 	O¬E¯K©Kð 	O¼E¿K¹Kñ 	Or1   c                óp   € V \         P                  \         P                  39   d   V # \         P                  # )zèNormalize dtype to float32 or float64 for operations that require full precision.

Args:
    dtype: The input dtype to normalize.

Returns:
    torch.float32 if dtype is not float32 or float64, otherwise returns the original dtype.
)r+   Úfloat32Úfloat64rJ   s   &r/   Ú _normalize_to_float32_or_float64r’     s'   € ð œeŸm™m¬U¯]©]Ð;Ô;ˆ5ÐNÄÇÁÐNr1   c                óX   € V ^8„  d   QhR\         P                  R\         P                  /# r&   ©r+   r,   )r.   s   "r/   r0   r0     s"   € ÷ 	ñ 	œUŸ\™\ð 	¬e¯l©lñ 	r1   c                ó„   € V P                   \        P                  \        P                  39   d   V P	                  4       # V # )aŠ  Return a float16 or bfloat16 ``input`` in float32, and a float32 or float64 one as it is.

For an estimator that fits half-precision data in float32 and rounds its result once, on return: no backend
factorizes half precision, and the steps around the solve would each round to the input dtype. A float32 or
float64 input is the same tensor, so its result keeps its bits and its autograd graph.
)r3   r+   r4   r5   rA   r6   s   &r/   Ú_at_least_float32r–     s.   € ð ‡{�{”u—}‘}¤e§n¡nÐ5Ô5Ø�{‰{‹}ÐØ€Lr1   c                ód   € V ^8„  d   QhR\         P                  R\        R\         P                  /# )r'   r(   Údimr)   ©r+   r,   rm   )r.   s   "r/   r0   r0     s)   € ÷ ñ œŸ™ð ¬Cð ¼¿¹ñ r1   c           
     óf  € V P                   \        P                  8X  d   V P                  4       MT pVP	                  4       P                  VRR7      ^ 8H  p\        P                  ! V\        P                  ! V4      \        P                  ! W!RR7      4      pVP                  V P                   4      # )ad  L2-normalise ``input`` along ``dim`` with :func:`torch.nn.functional.normalize`'s default ``eps``.

``normalize`` divides by ``norm.clamp_min(eps)``, and the 1e-12 default underflows to zero in
float16, where an all-zero input therefore normalised to NaN. A float16 input is normalised in
float32 and cast back. Clamping the norm at the smallest float16 normal instead is safe but not
neutral: a vector whose norm sits in the subnormal window -- representable, and computed exactly
because the float16 ``norm`` accumulates in float32 -- came back with a norm of 0.5 rather than
1. Every other floating dtype carries the 1e-12 default and is unchanged.

Args:
    input: the tensor to normalise.
    dim: the dimension to normalise along.

Returns:
    the normalised tensor, in ``input``'s dtype. An all-zero vector normalises to zero with a
    zero gradient: a zero vector has no direction, and the gradient of the ``eps`` clamp there,
    ``1 / eps``, is ~1e12 in float32 and overflows to ``inf`` once cast back to float16. A
    non-zero vector, including one that holds a NaN, keeps ``normalize``'s value and gradient.
T©r˜   Úkeepdimgê-�™—q=)r˜   Úeps)r3   r+   r4   rA   ÚabsÚamaxÚwhereÚ
zeros_liker?   Ú	normalizerB   )r(   r˜   rf   ÚzeroÚouts   &&   r/   Ú_l2_normalizer¥     sz   € ð( Ÿ™¬¯©Ô5ˆ�‰Œ¸5€Að �5‰5‹7�<‰<˜C¨ˆ<Ó.°!Ñ3€DÜ
�+Š+�dœE×,Ò,¨QÓ/´·²¸QÈUÔ1SÓ
T€CØ�6‰6�%—+‘+ÓÐr1   c                óX   € V ^8„  d   QhR\         P                  R\         P                  /# r&   r”   )r.   s   "r/   r0   r0   <  s"   € ÷ -0ñ -0¤E§L¡Lð -0´U·\±\ñ -0r1   c                ó(  € V P                   \        P                  \        P                  39   pV'       d   V P	                  4       MT p\        4       '       g   \        V4      pM\        V4      pV'       d   VP                  V P                   4      # T# )ar  Closed-form inverse for batched 3x3 matrices, dispatching on the execution mode.

Used as an ONNX-traceable fallback to ``torch.linalg.inv``: the legacy ONNX
exporter does not lower ``aten::linalg_inv`` (as of opset 17). Computed via
the adjugate / determinant formula, which is composed entirely of basic
arithmetic ops that all standard ONNX opsets support.

The arithmetic lives in :mod:`kornia.core._small_linalg`; this function owns only the
choice between the two kernels, which is execution-mode policy and therefore stays here.

A float16 or bfloat16 input is inverted in float32 and the result cast back, as
:func:`_torch_inverse_cast` does. The determinant is a sum of products of three entries, so it leaves
float16's range long before the entries do: the pixel-normalization matrix of a 3000 px image,
with entries ``2 / 2999``, has a subnormal float16 determinant, 6 % off, and one of 11600 px a zero one.
Running ``cross`` in float32 also avoids the missing bfloat16 ``cross`` kernel on MPS in
torch 2.5.1.

Args:
    input: Tensor of shape ``(..., 3, 3)``.

Returns:
    Tensor of shape ``(..., 3, 3)`` containing the matrix inverse for each
    leading-dim slice, in the dtype of ``input``. Numerically equivalent to ``torch.linalg.inv`` for
    well-conditioned matrices; behavior on singular matrices is undefined
    (no explicit check, same as ``torch.linalg.inv`` itself).
)	r3   r+   r4   r5   rA   Ú_is_tracing_or_exportingr   r   rB   )r(   Úhalfrf   r¤   s   &   r/   Ú_inverse_3x3_closed_formrª   <  si   € ð6 �;‰;œ5Ÿ=™=¬%¯.©.Ð9Ñ9€Dßˆ�‰Œ 5€AÜ#×%Ò%ô ! Ó#‰ô " !Ó$ˆß"&ˆ3�6‰6�%—+‘+ÓÐ/¨CÐ/r1   c                ó$   € V ^8„  d   QhR\         /# r[   r\   )r.   s   "r/   r0   r0   l  s   € ÷ 4ñ 4¤$ñ 4r1   c                 ó®   € \         P                  P                  4       '       d   R# \         P                  P                  4       ;'       g    \	        4       # )a"  Whether a graph is being captured by ``torch.jit.trace`` or ``torch.export``/dynamo ONNX export.

Both capture modes lack ONNX lowerings for the ``linalg`` decompositions (``inv``, ``inv_ex``,
``lu_factor``), so callers switch to closed-form arithmetic. Always ``False`` under TorchScript.
F)r+   rN   rO   Ú
is_tracingÚis_exportingrb   r1   r/   r¨   r¨   l  s7   € ô ‡y�y×Ñ×ÒÙÜ�9‰9×ÑÓ!×3Ð3¤\£^Ð3r1   c                óŽ   € V ^8„  d   QhR\         P                  R\        \         P                  \         P                  3,          /# r&   ©r+   r,   r   )r.   s   "r/   r0   r0   w  s4   € ÷ wñ w¤§¡ð w´%¼¿¹ÄeÇlÁlÐ8RÕ2Sñ wr1   c                óf  € V P                   R,          pV P                   R,          V8X  d   V^8X  d   \        V 4      # V P                   R,          V8X  d   V^8X  d   \        V 4      # V P                   R,          V8X  d   V^8X  d   \        V 4      # \	        R\        V P                   4       24      h)z·Adjugate and determinant of batched square matrices up to 4x4 in basic arithmetic only.

Raises:
    NotImplementedError: for shapes other than ``(..., n, n)`` with ``n`` in 2, 3, 4.
zAClosed-form inverse only supports 2x2, 3x3 and 4x4 matrices, got éÿÿÿÿéþÿÿÿ)Úshaper   r   r   ÚNotImplementedErrorÚlist©r(   Úns   & r/   Ú_adjugate_closed_formr¹   w  s•   € ð 	�‰�B�€AØ‡{�{�2…˜!Ô  Q¤Ü˜UÓ#Ð#Ø‡{�{�2…˜!Ô  Q¤Ü˜UÓ#Ð#Ø‡{�{�2…˜!Ô  Q¤Ü˜UÓ#Ð#Ü
Ð aÔbfÐgl×grÑgrÓbsÐatÐuÓ
vÐvr1   c                óŽ   € V ^8„  d   QhR\         P                  R\        \         P                  \         P                  3,          /# r&   r°   )r.   s   "r/   r0   r0   ‡  s4   € ÷ vñ v¤§¡ð v´%¼¿¹ÄeÇlÁlÐ8RÕ2Sñ vr1   c                óf  € V P                   R,          pV P                   R,          V8X  d   V^8X  d   \        V 4      # V P                   R,          V8X  d   V^8X  d   \        V 4      # V P                   R,          V8X  d   V^8X  d   \        V 4      # \	        R\        V P                   4       24      h)z¼Determinant of batched square matrices up to 4x4 and the permanent of their absolute values.

Raises:
    NotImplementedError: for shapes other than ``(..., n, n)`` with ``n`` in 2, 3, 4.
z@Closed-form determinant supports 2x2, 3x3 and 4x4 matrices, got r²   r³   )r´   r   r   r   rµ   r¶   r·   s   & r/   Ú_det_perm_closed_formr¼   ‡  s•   € ð 	�‰�B�€AØ‡{�{�2…˜!Ô  Q¤Ü˜UÓ#Ð#Ø‡{�{�2…˜!Ô  Q¤Ü˜UÓ#Ð#Ø‡{�{�2…˜!Ô  Q¤Ü˜UÓ#Ð#Ü
Ð `ÔaeÐfk×fqÑfqÓarÐ`sÐtÓ
uÐur1   c                óD   € V ^8„  d   QhR\         P                  R\        /# r&   r*   )r.   s   "r/   r0   r0   —  s   € ÷ 3ñ 3¤E§L¡Lð 3´Tñ 3r1   c                 ón   € V P                   R,          pV P                   R,          V8H  ;'       d    VR9   # )r„   r²   r³   )r'   é   é   )r´   r·   s   & r/   Ú_has_closed_form_inverserÁ   —  s.   € Ø�‰�B�€AØ�;‰;�r�?˜aÑ×2Ð2 A¨¡NÐ2r1   c                óX   € V ^8„  d   QhR\         P                  R\         P                  /# r&   r”   )r.   s   "r/   r0   r0   œ  s&   € ÷ mñ m¤§¡ð m´·±ñ mr1   c                óˆ  € \         P                  ! \         P                  ! V P                  4       4      4      pVP	                  RRR7      p\         P
                  ! \         P                  ! V4      V\         P                  ! V4      4      pW,
          P	                  RRR7      p\         P
                  ! \         P                  ! V4      V\         P                  ! V4      4      p\        \        WV,           ) 4      4      w  rE\        WER,          ,          VP                  RR4      VP                  RR4      ,           ) 4      # )a[  Inverse of batched 2x2, 3x3 or 4x4 matrices as ``adj / det``, computed on a scaled copy.

The entries of the adjugate and the determinant are products of up to ``n`` entries, which overflow or
underflow the dtype long before the inverse does: for ``1e13 * I`` or ``1e-13 * I`` of order 4 in
float32 they are ``inf`` or ``0`` while the inverse is ``1e-13 * I`` or ``1e13 * I``. So the matrix is
balanced first, each row divided by the power of two below its largest magnitude and then each column of
that by the power of two below its own, ``inv(A) = D_c inv(D_r A D_c) D_r``, and the rows and columns of
the result are scaled back by the same factors. A power of two keeps every rounding step the one of the
unscaled computation, so the result is bit for bit the former ``adj / det`` wherever its adjugate and
determinant were normal numbers; where one of them overflowed or went subnormal the former result was
``inf``, ``nan``, zero or rounded (``diag(2 ** -100, 2 ** -40)`` in float32 has a subnormal determinant
and was off by 1.2e-7), and the new one is the inverse.

The scaling works on the exponents and never forms the row-scaled matrix: ``[[2 ** 100, 2 ** -60],
[2 ** 100, -2 ** -60]]`` in float32 would lose its second column to underflow on the way, and its inverse
is finite. The combined exponent of an entry can exceed what the dtype holds while the entry itself fits,
so it is applied as three powers of two of about a third of it each; every intermediate lies between the
start and the end, and is exact wherever the end is a normal number. A zero row or column is left alone, and
so is one holding a NaN, whose exponent would index the table of powers of two out of range (a NaN casts to
the most negative int64 on x86 and CUDA); its determinant is 0 or NaN either way.

Raises:
    NotImplementedError: for shapes other than ``(..., n, n)`` with ``n`` in 2, 3, 4.
T©rœ   r²   r³   ©.NN)r+   ÚfloorÚlog2rž   rŸ   r    Úisfiniter¡   r¹   Ú_times_power_of_twoÚ	transpose)r(   ÚexponentÚrowÚcolÚadjÚdets   &     r/   Ú_closed_form_inverserÐ   œ  sæ   € ô2 �{Š{œ5Ÿ:š: e§i¡i£kÓ2Ó3€HØ
�-‰-˜ Dˆ-Ó
)€CÜ
�+Š+”e—n’n SÓ)¨3´×0@Ò0@ÀÓ0EÓ
F€CØ�>×
Ñ
 ¨DÐ
Ó
1€CÜ
�+Š+”e—n’n SÓ)¨3´×0@Ò0@ÀÓ0EÓ
F€CÜ$Ô%8¸ÈÅ)ÀÓ%MÓN�H€CÜ˜s¨Õ%9Õ9¸S¿]¹]È2ÈrÓ=RÐUX×UbÑUbÐceÐgiÓUjÕ=jÐ;kÓlÐlr1   c                óx   € V ^8„  d   QhR\         P                  R\         P                  R\         P                  /# )r'   rf   rË   r)   r”   )r.   s   "r/   r0   r0   ¾  s2   € ÷ Wñ Wœ5Ÿ<™<ð W´5·<±<ð WÄEÇLÁLñ Wr1   c                ól  € V P                   \        P                  8X  d   RM^~pVP                  RV,          RV,          4      p\        P                  ! V^,          4      p\        P
                  ! \        V) V^,           4       Uu. uF  pRV,          NK  	  upV P                   V P                  R7      pWSV,           P                  \        P                  4      ,          pW,          V,          WQ^V,          ,
          V,           P                  \        P                  4      ,          ,          # u upi )a9  ``x * 2 ** exponent`` in three steps of about a third of the exponent each.

No step and no intermediate leaves the dtype while the result is inside it. ``exponent`` is integer
valued and is clipped to three times the largest exponent of a normal number of the dtype, beyond which a
nonzero result is ``inf`` or ``0`` anyway and a zero one stays ``0`` instead of turning into ``0 * inf``.
The powers of two are read from a table, not computed by ``pow``, which is not exact on every device
(MPS), and the scaling has to be exact to leave every rounding step as it was.
iþ  g      @g       @)r3   rF   g      À)
r3   r+   r‘   ÚclampÚroundrE   ÚrangerF   rB   Úint64)rf   rË   ÚlargestÚstepÚkÚpowersÚscales   &&     r/   rÉ   rÉ   ¾  sÛ   € ð —g‘g¤§¡Ô.‰d°C€GØ�~‰~˜d W�n¨c°G­mÓ<€HÜ�;Š;�x !•|Ó$€DÜ�\Š\¬5°'°¸7ÀQ½;Ô+GÓHÑ+G a˜3 Ÿ6˜6Ñ+GÑHÐPQ×PWÑPWÐ`a×`hÑ`hÔi€FØ˜7•N×&Ñ&¤u§{¡{Ó3Õ4€EØ�9�uÕ˜v°!°dµ(Õ':¸WÕ'D×&HÑ&HÌÏÉÓ&UÕVÕVÐVùò Is   ÂD1c                ód   € V ^8„  d   QhR\         P                  R\        R\         P                  /# )r'   r(   Úcheck_errorsr)   r*   )r.   s   "r/   r0   r0   Ï  s)   € ÷ =ñ =œuŸ|™|ð =¼4ð =Ì5Ï<É<ñ =r1   c                ó  € \        V R4       \        V P                  4      p\        4       '       dE   \	        V 4      '       d4   \        V P                  V4      4      P                  V P                  4      # V'       g>   \        V P                  V4      4      P                  P                  V P                  4      # \        P                  P                  V P                  V4      4      P                  V P                  4      # )ad  Make torch.inverse work with other than fp32/64.

The function torch.inverse is only implemented for fp32/64 which makes impossible to be used by fp16 or others. What
this function does, is cast input data type to fp32, apply torch.inverse, and cast back to the input dtype.

Under graph capture (``torch.jit.trace``, legacy ``torch.onnx.export`` and the dynamo
``torch.onnx.export(..., dynamo=True)`` / ``torch.export`` path) on 2x2, 3x3 and 4x4
matrices, falls back to a closed-form adjugate inverse so the resulting graph does not
include ``aten::linalg_inv``, which neither ONNX exporter lowers. ``torch.jit.is_tracing()``
is JIT-script-safe (unlike ``torch.onnx.is_in_onnx_export``, which contains an ``import``
statement).

Singular input is not checked here. In eager mode ``torch.linalg.inv`` decides, and raises, from the
pivots of its own factorization; under capture the adjugate is divided by the determinant, which gives
non-finite or large values. Which near-singular matrices raise, and which return large values, depends
on the torch version, the device and the capture mode. Callers that need a verdict use
:func:`safe_inverse_with_mask`, whose mask follows one rule everywhere.

``torch.linalg.inv`` reads its factorization status back on the host to raise for a singular matrix, which on
CUDA waits for every queued kernel. ``check_errors=False`` uses ``torch.linalg.inv_ex`` instead: the same
factorization and the same bits, without the read. Pass it only for a matrix that cannot be singular, such as a
pixel normalization kornia builds itself; a singular matrix then returns non-finite values instead of raising.
úInput must be torch.Tensor)r!   r’   r3   r¨   rÁ   rÐ   rB   r   Úinverser+   ÚlinalgÚinv)r(   rÝ   r3   s   && r/   Ú_torch_inverse_castrã   Ï  sª   € ô0 ˜5Ð">Ô?Ü,¨U¯[©[Ó9€EÜ×!Ò!Ô&>¸u×&EÒ&EÜ# E§H¡H¨U£OÓ4×7Ñ7¸¿¹ÓDÐDßÜ�e—h‘h˜u“oÓ&×.Ñ.×1Ñ1°%·+±+Ó>Ð>Ü�<‰<×Ñ˜EŸH™H U›OÓ,×/Ñ/°·±Ó<Ð<r1   c          
      óÀ   € V ^8„  d   QhR\         P                  R\        R\        \        \
        3,          R\        \        \
        3,          R\         P                  /# )r'   r(   ÚbinsÚminÚmaxr)   )r+   r,   rm   r   rA   r-   )r.   s   "r/   r0   r0   ð  sP   € ÷ 8ñ 8œUŸ\™\ð 8´ð 8¼5ÄÌÀÕ;Mð 8ÔTYÔZ_ÔaeÐZeÕTfð 8Ôkp×kwÑkwñ 8r1   c                ó’   € \        V R4       \        V P                  4      p\        P                  ! V P                  V4      WV4      # )a¦  Apply torch.histc to any real dtype, returning the counts in float32 or float64.

The input is cast to float32 (float64 stays float64) before binning: ``torch.histc`` has no CPU
kernel for integer input, and on MPS in torch 2.5.1 none for anything but float32.

The counts are returned in that compute dtype, **not** cast back to the input dtype. A count grows
with the number of values, not with their range: float16 holds integers exactly only up to 2048 and
rounds them to ``inf`` from 65520, bfloat16 only up to 256, and an integer dtype can wrap (uint8 past
255). They stay floating rather than becoming int64: ``torch.histc`` counts in the floating dtype it
bins in, so a float32 count stops being exact past 2**24 per accumulating thread (single-threaded on
the CPU, 2**25 + 3 equal values come back as 2**24), an int64 result would be no more exact, and a
float64 input keeps float64 counts for float64 arithmetic downstream.
rß   )r!   r’   r3   r+   ÚhistcrB   )r(   rå   ræ   rç   r3   s   &&&& r/   Ú_torch_histc_castrê   ð  s8   € ô ˜5Ð">Ô?Ü,¨U¯[©[Ó9€EÜ�;Š;�u—x‘x “¨°3Ó7Ð7r1   c          	      ó¸   € V ^8„  d   QhR\         P                  R\        R\        \         P                  \         P                  \         P                  3,          /# ©r'   r(   Úfull_matricesr)   ©r+   r,   r-   r   )r.   s   "r/   r0   r0     sH   € ÷ Nñ Nœ5Ÿ<™<ð N¼ð NÌÌeÏlÉlÔ\a×\hÑ\hÔjo×jvÑjvÐNvÕHwñ Nr1   c                ó¾   € \        W4      w  r#pVP                  V P                  4      VP                  V P                  4      VP                  V P                  4      3# )aÁ  Make torch.svd work with other than fp32/64.

The function torch.svd is only implemented for fp32/64 which makes
impossible to be used by fp16 or others. What this function does, is cast
input data type to fp32, apply torch.svd, and cast back to the input dtype.

NOTE: in torch 1.8.1 this function is recommended to use as torch.linalg.svd

For numerical stability, fp32 inputs are promoted to fp64 (except on MPS where fp64 is unsupported).

An MPS input past the shader-compilation ceiling is decomposed on the CPU and moved back, which
is what keeps the batched minimal solvers behind ``RANSAC`` working on Apple silicon.
``full_matrices`` selects full or reduced factors, as in ``torch.linalg.svd``.
)Ú_torch_svd_in_work_dtyperB   r3   )r(   rí   Úout1Úout2Úout3s   &&   r/   Ú_torch_svd_castrô     sG   € ô 0°ÓEÑ€D�Ø�G‰G�E—K‘KÓ  $§'¡'¨%¯+©+Ó"6¸¿¹ÀÇÁÓ8LÐMÐMr1   c          	      ó¸   € V ^8„  d   QhR\         P                  R\        R\        \         P                  \         P                  \         P                  3,          /# rì   rî   )r.   s   "r/   r0   r0     s@   € ÷  ñ  Ü�<‰<ð Ü(,ð ä
Œ5�<‰<œŸ™¤u§|¡|Ð3Õ4ñ r1   c                óê  € V P                  \        V 4      4      p\        V4      '       d™   VP                  4       R8¼  d„   \        P
                  P                  VP                  4       VR7      w  r4pVP                  VP                  4      VP                  VP                  4      VP                  VP                  4      r‡pM#\        P
                  P                  W!R7      w  rgpWgVP                  3# )a¤  Decompose ``input`` as :func:`_torch_svd_cast` does, returning ``U, S, V`` in :func:`_svd_work_dtype`.

A caller that needs the factors at the precision they were computed in, such as for a derivative, uses this
instead of casting ``input`` to the work dtype first: :func:`_torch_svd_cast` would promote a float32 input
to float64 again, so a float16 or bfloat16 input would be decomposed in float64 instead of float32.
é    )rí   )
rB   Ú_svd_work_dtyperj   Únumelr+   rá   ÚsvdrH   rF   ÚmH)	r(   rí   rf   ÚUÚSÚVhrñ   rò   Úout3Hs	   &&       r/   rð   rð     s²   € ð 	�‰” Ó'Ó(€Aô ˜!×Ò §¡£¨dÔ!2ô —<‘<×#Ñ# A§E¡E£G¸=Ð#ÓI‰ˆˆbØŸD™D §¡›N¨A¯D©D°·±«N¸B¿E¹EÀ!Ç(Á(»O�Eˆ�Eä!ŸL™L×,Ñ,¨QÐ,ÓLÑˆ�Eà�u—x‘xÐÐr1   c                óX   € V ^8„  d   QhR\         P                  R\         P                  /# r&   )r+   r,   r3   )r.   s   "r/   r0   r0   1  s"   € ÷ 9ñ 9œ5Ÿ<™<ð 9¬E¯K©Kñ 9r1   c                óÌ   € \        V 4      '       d   \        P                  # V P                  \        P                  8X  d   \        P                  # \        V P                  4      # )zeReturn the dtype :func:`_torch_svd_cast` decomposes ``input`` in: float64 for float32, except on MPS.)rj   r+   r�   r3   r‘   r’   r6   s   &r/   rø   rø   1  s@   € ä˜%× Ò Ü�}‰}ÐØ‡{�{”e—m‘mÔ#Ü�}‰}ÐÜ+¨E¯K©KÓ8Ð8r1   c                óD   € V ^8„  d   QhR\         P                  R\        /# r&   r*   )r.   s   "r/   r0   r0   :  s"   € ÷ Lñ LœeŸl™lð L¬tñ Lr1   c                ó˜  € \         P                  ! 4       '       d   V P                  '       d   R# \         P                  P	                  4       '       d   R# \         P
                  P                  4       '       dž   \        4       '       d   R# \         P
                  P                  P                  V 4      '       d]   \         P
                  P                  P                  V 4      p \         P                  ! 4       '       g   Ku  V P                  '       g   K‰  R# \         P                  P                  P                  V 4      P                  RJ# )ak  Return whether autograd can ask for a derivative through ``input``.

Reverse mode needs grad mode and an ``input`` that requires grad; forward mode (``torch.func.jvp``, ``jacfwd``,
``torch.autograd.forward_ad``) gives ``input`` a tangent instead, whatever the grad mode. TorchScript has no forward
mode and cannot compile the query.

Under ``torch.vmap`` the query reads through the batching wrappers: a wrapper hides both ``requires_grad`` and the
tangent of the tensor it batches, and the tangent query has no batching rule. Dynamo cannot unwrap, so a compiled
call under any function transform reports a derivative.
TFN)r+   Úis_grad_enabledÚrequires_gradrN   rO   Ú_CÚ _are_functorch_transforms_activerR   Ú
_functorchÚis_batchedtensorÚget_unwrappedÚautogradÚ
forward_adÚunpack_dualÚtangentr6   s   &r/   Ú_needs_derivativesr  :  sÎ   € ô ×Ò×Ò 5×#6×#6Ð#6ÙÜ‡y�y×Ñ×ÒÙÜ‡x�x×0Ñ0×2Ò2ô �>Š>ÙÜ�h‰h×!Ñ!×2Ñ2°5×9Ò9Ü—H‘H×'Ñ'×5Ñ5°eÓ<ˆEÜ×$Ò$×&Ô&¨5×+>×+>Ò+>ÙÜ�>‰>×$Ñ$×0Ñ0°Ó7×?Ñ?ÀtÐKÐKr1   c                ó†   € V ^8„  d   QhR\         P                  R\        R\        \        ,          R\         P                  /# )r'   r(   ÚlowerÚupperr)   )r+   r,   rA   r   )r.   s   "r/   r0   r0   U  s7   € ÷ 9ñ 9œŸ™ð 9¬Uð 9¼8ÄE½?ð 9ÔV[×VbÑVbñ 9r1   c                óÖ   € \        4       '       g   \        V 4      '       g   V P                  W4      # V P                  4       P                  W4      p\        P
                  ! W08H  W4      # )a�  Clamp ``input`` into ``[lower, upper]`` with an identity gradient on the closed range.

A clamp has no derivative at a bound: its one-sided derivatives are 0 and 1. torch returned 1 up to 2.13 and returns
0 from 2.14, its documented minimum-norm rule (pytorch/pytorch#191142). Kornia uses the derivative from inside the
range on every version: at an identity factor it is the only one on the documented input domain, and it lets a pixel
on a bound move back. Values outside the range get the bound and a zero gradient. ``upper=None`` has no upper bound.

The values always equal ``input.clamp(lower, upper)``, ``NaN`` included, so a call that records no gradient and
carries no forward-mode tangent is that single clamp. Otherwise, select ``input`` where the clamp left it
unchanged: one comparison against the clamped copy instead of two bound comparisons and their conjunction.
Forward-mode tangents must keep the identity derivative even inside ``torch.no_grad()``. The sign of a zero is
not part of the contract: ``clamp`` returns ``+0.0`` for ``-0.0`` on MPS, under Inductor (CPU and CUDA) and in the
SIMD lanes of eager arm64 CPU, while eager x86 CPU and CUDA keep ``-0.0``.
)r¨   r  rÓ   Údetachr+   r    )r(   r  r  Úclampeds   &&& r/   Ú_clamp_ranger  U  sS   € ô&  ×!Ò!Ô);¸E×)BÒ)BØ�{‰{˜5Ó(Ð(ð �l‰l‹n×"Ñ" 5Ó0€GÜ�;Š;�wÑ'¨Ó8Ð8r1   c                óX   € V ^8„  d   QhR\         P                  R\         P                  /# r&   r”   )r.   s   "r/   r0   r0   q  s"   € ÷ )ñ )œUŸ\™\ð )¬e¯l©lñ )r1   c                ó   € \        V RR4      # )z:Clamp ``input`` into ``[0, 1]`` with :func:`_clamp_range`.g        ç      ð?)r  r6   s   &r/   Ú_clamp_unit_ranger  q  s   € ä˜˜s CÓ(Ð(r1   c          
      óÚ   € V ^8„  d   QhR\         P                  R\         P                  R\         P                  R\        \        \         P                  3,          R\         P                  /# )r'   r(   ÚeigenvaluesÚeigenvectorsrl   r)   )r+   r,   r   rm   )r.   s   "r/   r0   r0   v  sV   € ÷ 8(ñ 8(Ü�<‰<ð8(Ü&+§l¡lð8(ÜBGÇ,Á,ð8(ÜW\Ô]`Ôbg×bnÑbnÐ]nÕWoð8(ä
‡\�\ñ8(r1   c                ó<  € VP                  4       pVP                  4       p\        V\        4      '       d   VRRV3,          pVRVR3,          pMRVP                  RVR,          P                  ! . VP
                  RR O^N5!  4      R	,          pVP                  RV4      p\        V 4      '       g   V# \        P                  ! VP
                  R,          VP                  R7      pT\        V\        4      '       d   W4P
                  R,          ,          MT8g  p	Wt,
          p
WšP                  4       \        P                  ! V
P                  4      P                  8„  ,          p\        P                  ! VR\        P                  ! Wº\        P                  ! V
4      4      ,          \        P                   ! V
4      4      pW\R,          ,          VP"                  ,          pV P%                  VP                  4      pWîP                  4       ,
          pVR
,          pWö,          pVV,          pWßV,          ,          VP"                  V,          VV,          ,          ,
          RV,          VP"                  V,          ,          ,
          pVV,           V,           R	,          # )aþ  Return the eigenvector ``eigenvectors[..., :, index]`` of the symmetric ``input``, differentiably.

The backward passes of ``torch.linalg.eigh`` and ``torch.linalg.svd`` divide by the gap between every pair of
eigenvalues, so the gradient of a single eigenvector is NaN where two of the *other* eigenvalues are equal, although
the vector is well defined while its own eigenvalue :math:`\lambda_k` is simple. With
:math:`R = \sum_{i \ne k} v_i v_i^\top / (\lambda_k - \lambda_i)`, the eigenvector of :math:`C` moves by
:math:`R\,dC\,v` to first order and by
:math:`R\,dC\,R\,dC\,v - (v^\top dC\,v)\,R^2 dC\,v - \tfrac12 v\,\|R\,dC\,v\|^2` to second. Both divide only by the
gaps to :math:`\lambda_k`, and an equal pair among the other eigenvalues enters only through its projector, which
does not depend on the basis chosen within it. The first-order term is the derivation of ``_NullSpaceBasis`` in
:mod:`kornia.geometry.epipolar.essential`.

The two terms are added to the detached eigenvector with ``dC = C - C.detach()``, which is zero in value (the
detached-value pattern of #4229): the value is the given eigenvector, and only the derivatives come from the terms.
A gap that is exactly zero, where the eigenvector is not unique, contributes nothing.

Args:
    input: the symmetric matrix ``C``, of shape ``(*, D, D)``.
    eigenvalues: eigenvalues of ``C``, of shape ``(*, K)``; for a positive semidefinite ``C`` they can be its
        singular values.
    eigenvectors: the matching orthonormal eigenvectors of ``C`` as columns, of shape ``(*, D, K)``.
    index: the column to return, as an ``int`` or a ``(*, 1)`` integer tensor.

Returns:
    The eigenvector, of shape ``(*, D)`` in the dtype of ``eigenvectors``, with first and second derivatives
    with respect to ``input``.
.ºNNNNrL   r  g      à?r²   ).Nr  ©.r   ).N)r  rW   rm   ÚgatherÚexpandr´   r  r+   ÚarangerF   rž   Úfinfor3   Útinyr    Ú	ones_liker¡   ÚmTrB   )r(   r  r  rl   ÚlamÚVÚvÚlam_kÚcolumnsÚothersÚgapÚnonzeroÚinv_gapÚRÚCÚdCÚdvÚfirstÚseconds   &&&&               r/   Ú_symmetric_eigenvectorr7  v  sê  € ð< ×
Ñ
Ó
€CØ×ÑÓ€AÜ�%œ×ÒØˆc�1�eˆmÕˆØ�C˜ Ð$Õ%‰ð �H‰H�R˜˜|Õ,×3Ò3ÐE°Q·W±W¸S¸b°\ÐEÀ1ÓEÓFÀvÕNˆØ—
‘
˜2˜uÓ%ˆÜ˜e×$Ò$ØˆÜ�lŠl˜3Ÿ9™9 R�=°·±Ô<€GØ´*¸UÄC×2HÒ2H˜§¡¨2¥Ö.ÈeÑT€FØ
�+€Cð Ÿ™›	¤E§K¢K°·	±	Ó$:×$?Ñ$?Ñ?Õ@€GÜ�kŠk˜' 3¬¯ª°WÄ5Ç?Â?ÐSVÓCWÓ)XÕ#XÔZ_×ZjÒZjÐknÓZoÓp€GØ	
�\Õ"Õ	" a§d¡dÕ*€AØ�‰�—‘Ó€AØ	
�X‰X‹Z�€BØ	ˆ)�€AØ	�€BØ��F€EØ�u•*Õ §¡¨¥¨q°5­yÕ 9Õ9¸CÀ!½GÀuÇxÁxÐRWÕGWÕ<XÕX€FØ��I˜Õ Õ'Ð'r1   c          
      ó¤   € V ^8„  d   QhR\         P                  R\         P                  R\         P                  R\        R\         P                  /# )r'   r(   rý   r)  rl   r)   r™   )r.   s   "r/   r0   r0   ±  sJ   € ÷ Yñ Y¤%§,¡,ð Y´5·<±<ð YÄEÇLÁLð YÔY\ð YÔaf×amÑamñ Yr1   c                óÜ  € \        V 4      '       g   VP                  4       RRV3,          # V P                  VP                  4      pVP                  4       P	                  4       P                  RRR7      p\        P                  ! V^ 8„  V\        P                  ! V4      4      pWE,          p\        VP                  V,          VP                  4       VR,          ,          ^,          W#4      # )aß  Return the right singular vector ``V[..., :, index]`` of the ``(*, N, D)`` ``input``, differentiably.

``S`` and ``V`` are the singular values and the right singular vectors, as columns, of ``input``. The vector is
the eigenvector of ``X^T X`` with eigenvalue ``S^2``, with the derivatives of :func:`_symmetric_eigenvector`.
``X`` is ``input`` in the dtype of ``V`` divided by its largest magnitude, held constant, which leaves the vector
unchanged and keeps ``X^T X`` in range.
.r  Tr›   )r³   r²   r   )r  r  rB   r3   rž   rŸ   r+   r    r&  r7  r'  )r(   rý   r)  rl   rf   rÛ   s   &&&&  r/   Ú_right_singular_vectorr:  ±  s«   € ô ˜e×$Ò$Ø�x‰x‹z˜#˜q %˜-Õ(Ð(Ø�‰�—‘Ó€AØ�H‰H‹J�N‰NÓ×!Ñ! h¸Ð!Ó=€EÜ�KŠK˜ ™	 5¬%¯/ª/¸%Ó*@ÓA€EØ	�	€AÜ! !§$¡$¨¥(¨Q¯X©X«Z¸%À½-Õ-GÈAÕ,MÈqÓXÐXr1   c                óX   € V ^8„  d   QhR\         P                  R\         P                  /# r&   r”   )r.   s   "r/   r0   r0   Â  s"   € ÷ ñ ¤§¡ð ´%·,±,ñ r1   c                ó´  € \        V R4       \        V P                  4      pV P                  V4      p\	        V4      '       d]   VP                  4       R8¼  dH   \        P                  P                  VP                  4       4      P                  VP                  4      pM\        P                  P                  V4      pVP                  V P                  4      # )a`  Make torch.linalg.svdvals work with other than fp32/64.

The function torch.svd is only implemented for fp32/64 which makes
impossible to be used by fp16 or others. What this function does, is cast
input data type to fp32, apply torch.svd, and cast back to the input dtype.

NOTE: in torch 1.8.1 this function is recommended to use as torch.linalg.svd
rß   r÷   )r!   r’   r3   rB   rj   rù   r+   rá   ÚsvdvalsrH   rF   )r(   r3   rf   r¤   s   &   r/   Ú_torch_linalg_svdvalsr>  Â  s–   € ô ˜5Ð">Ô?Ü,¨U¯[©[Ó9€Eà�‰�‹€Aô ˜!×Ò §¡£¨dÔ!2Ü�l‰l×"Ñ" 1§5¡5£7Ó+×.Ñ.¨q¯x©xÓ8‰ô �l‰l×"Ñ" 1Ó%ˆØ�6‰6�%—+‘+ÓÐr1   c                óx   € V ^8„  d   QhR\         P                  R\         P                  R\         P                  /# )r'   ÚAÚBr)   r”   )r.   s   "r/   r0   r0   Ü  s-   € ÷ ñ œŸ™ð ¬%¯,©,ð ¼5¿<¹<ñ r1   c                óF  € \        V R4       \        VR4       \        V 4      '       d   \        P                  M\        P                  p\        P
                  P                  V P                  V4      VP                  V4      4      pVP                  V P                  4      # )al  Make torch.solve work with other than fp32/64.

For stable operation, the input matrices should be cast to fp64, and the output will
be cast back to the input dtype. However, fp64 is not yet supported on MPS.

This function is actively used in:
- kornia.geometry.transform.imgwarp
- kornia.geometry.transform.thin_plate_spline
- kornia.geometry.epipolar.essential
úA must be torch.TensorúB must be torch.Tensor)	r!   rj   r+   r�   r‘   rá   ÚsolverB   r3   )r@  rA  r3   r¤   s   &&  r/   Ú_torch_solve_castrF  Ü  sm   € ô ˜1Ð6Ô7Ü˜1Ð6Ô7Ü/°×2Ò2ŒE�MŠM¼¿¹€Eä
�,‰,×
Ñ
˜QŸT™T %›[¨!¯$©$¨u«+Ó
6€Cð �6‰6�!—'‘'‹?Ðr1   c                óX   € V ^8„  d   QhR\         P                  R\         P                  /# re   r”   )r.   s   "r/   r0   r0   ñ  s"   € ÷ (ñ (”E—L‘Lð (¤U§\¡\ñ (r1   c                ó^   € V P                  4       P                  R4      P                  R4      # )zYWhether every entry of each trailing matrix of ``x`` is finite, as a mask over its batch.r²   )rÈ   Úallri   s   &r/   Ú_rows_finiterJ  ñ  s$   € à�:‰:‹<×Ñ˜BÓ×#Ñ# BÓ'Ð'r1   c                óX   € V ^8„  d   QhR\         P                  R\         P                  /# ©r'   r@  r)   r”   )r.   s   "r/   r0   r0   ö  s"   € ÷ "7ñ "7”E—L‘Lð "7¤U§\¡\ñ "7r1   c                óÂ  € \         P                  P                  4       '       d7   V P                  \         P                  8H  pV'       d   RMRpV'       d   RMRpMT\         P
                  ! V P                  4      P                  p\         P
                  ! V P                  4      P                  pW P                  4       P                  RRR7      P                  V4      ,          p W P                  4       P                  RRR7      P                  V4      ,          p \        V 4      w  rEVP                  4       ^V P                  R,          ,          V,          V,          8*  # )	a1  Whether each 2x2, 3x3 or 4x4 matrix of ``A`` counts as singular, as a mask over its batch.

One rule decides, the same in eager mode and under graph capture, on every torch version and device,
and unchanged by scaling the matrix: a matrix is singular when its closed-form determinant is within
the rounding error of that determinant,

``|det A| <= 8 * n * eps * perm |A|``,

where ``perm |A|``, the permanent of the absolute values, is the sum of the absolute values of the terms
of the determinant expansion, ``eps`` the machine epsilon of the dtype of ``A`` and ``n`` its order. The
permanent, unlike ``||A||^n``, does not grow with a translation: a homography that moves by 5000 pixels
has ``det 1`` and ``perm 1``. A matrix with a non-finite entry is not flagged; its inverse is not finite
and the callers reject it on that account.

Both sides are linear in every row and every column, so the rule is read on the matrix with each row,
then each column, divided by its largest magnitude. That leaves the ratio unchanged and keeps the
products of ``n`` entries from overflowing or underflowing: unscaled, ``1e10 * I`` of order 4 in float32
reads ``inf <= inf`` and ``1e-13 * I`` reads ``0 <= 0``, and both would count as singular.

Raises:
    NotImplementedError: for shapes other than ``(..., n, n)`` with ``n`` in 2, 3, 4.
g      °<g      €>g       g      8TrÄ   r²   r³   )r+   rN   rO   r3   r‘   r$  r�   r%  rž   rŸ   Ú	clamp_minr¼   r´   )r@  Údoubler�   r%  rÏ   Úperms   &     r/   Ú_is_singularrQ  ö  sî   € ô. ‡y�y×Ñ×Òà—‘œEŸM™MÑ)ˆß'-Ñ#Ð3Iˆß*0Ñ&Ð6L‰ä�kŠk˜!Ÿ'™'Ó"×&Ñ&ˆÜ�{Š{˜1Ÿ7™7Ó#×(Ñ(ˆØ	�E‰E‹G�L‰L˜ TˆLÓ*×4Ñ4°TÓ:Õ:€AØ	�E‰E‹G�L‰L˜ TˆLÓ*×4Ñ4°TÓ:Õ:€AÜ% aÓ(�I€CØ�7‰7‹9˜˜QŸW™W R�[�¨3Õ.°$Õ6Ñ6Ð6r1   c          	      óÌ   € V ^8„  d   QhR\         P                  R\         P                  R\        \         P                  \         P                  \         P                  3,          /# )r'   rA  r@  r)   r°   )r.   s   "r/   r0   r0     sG   € ÷ 97ñ 97œEŸL™Lð 97¬U¯\©\ð 97¼eÄEÇLÁLÔRW×R^ÑR^Ô`e×`lÑ`lÐDlÕ>mñ 97r1   c                ó†  € \        V R4       \        VR4       V P                  pV\        P                  \        P                  39  d   \        P                  p\        V P                  4      p\        VP                  4      pWC,
          ^8X  d   V P                  R4      p VP                  V4      pV P                  V4      pVP                  4       p\        P                  P                  V4      w  r‰p
\        P                  P                  W‰VP                  4       4      pV
^ 8H  \        VP                  V P                  4      4      ,          p\        V4      '       d   V\        V4      ( ,          p\        P                   ! VP                  R,          VP"                  VR7      p\        P$                  ! VR,          W]4      p\        P                  P                  V4      w  ppp\        P                  P                  VVV4      pVP                  V P                  4      VP                  VP                  4      V3# )a÷  Solves the system of equations.

Avoids crashing because of singular matrix input and outputs the mask of valid solution.

A system is valid when ``A`` is not singular and the solution is finite in the dtype of ``B``. A 2x2,
3x3 or 4x4 ``A`` is singular when ``|det A| <= 8 * n * eps * perm |A|``, the closed-form determinant
against the permanent of the absolute values (:func:`_is_singular`), which is the same on every torch
version, or when its LU factorization has a zero pivot; a larger ``A`` by the zero pivot alone. An
invalid system is solved with the identity in place of ``A``, so its row of
``X`` holds ``B`` and its row of the returned LU factor is the identity's. The differentiated solve
therefore never sees a singular matrix, and the gradient with respect to the valid systems (and to
any parameter they share with an invalid one) stays finite.

.. note::
    On MPS this needs torch 2.10 or later, or ``PYTORCH_ENABLE_MPS_FALLBACK=1`` on an older torch; see
    :ref:`MPS linear algebra <mps-linear-algebra>`.

Args:
    B: right-hand side of shape ``(*, N, K)`` or ``(*, N)``.
    A: square matrices of shape ``(*, N, N)``.

Returns:
    The solution ``(*, N, K)``, the LU factor of the solved matrices ``(*, N, N)`` and the
    validity mask ``(*)``.
rD  rC  rM   r²   rÅ   )r!   r3   r+   r�   r‘   Úlenr´   Ú	unsqueezerB   r  rá   Úlu_factor_exÚlu_solverJ  rÁ   rQ  ÚeyerF   r    )rA  r@  r3   Ún_dim_BÚn_dim_AÚA_castÚB_castÚ
A_detachedÚLU_detachedÚpivots_detachedÚinfoÚ
X_detachedÚ
valid_maskrX  ÚA_safeÚA_LUÚpivotsÚ_ÚXs   &&                 r/   Úsafe_solve_with_maskrh    s˜  € ô6 ˜1Ð6Ô7Ü˜1Ð6Ô7ØŸ™€EØ”U—]‘]¤E§M¡MÐ2Ô2Ü—‘ˆä�!—'‘'‹l€GÜ�!—'‘'‹l€GØÕ˜AÔØ�K‰K˜‹Oˆà�T‰T�%‹[€FØ�T‰T�%‹[€Fð —‘“€JÜ).¯©×)BÑ)BÀ:Ó)NÑ&€K $Ü—‘×&Ñ& {ÀVÇ]Á]Ã_ÓU€JØ $¨¡	¬\¸*¿-¹-ÈÏÉÓ:PÓ-QÕQ€JÜ ×"Ò"Ø¤<°
Ó#;Ð";Õ;ˆ
ä
�)Š)�F—L‘L Õ$¨V¯]©]À%Ô
H€CÜ�[Š[˜ OÕ4°fÓB€FÜ—l‘l×/Ñ/°Ó7�O€Dˆ&�!Ü�‰×Ñ˜d F¨FÓ3€Aà�4‰4�—‘‹=˜$Ÿ'™' !§'¡'Ó*¨JÐ6Ð6r1   c                óŽ   € V ^8„  d   QhR\         P                  R\        \         P                  \         P                  3,          /# rL  r°   )r.   s   "r/   r0   r0   W  s0   € ÷ .,ñ .,œeŸl™lð .,¬u´U·\±\Ä5Ç<Á<Ð5OÕ/Pñ .,r1   c                ór  € \        V R4       V P                  p\        V4      pV P                  V4      p\        P
                  ! VP                  R,          VP                  VR7      pVP                  4       p\        4       '       d    \        V 4      '       d�   \        V4      ( p\        \        P                  ! VR,          WT4      4      pV\        VP                  V4      4      ,          p\        \        P                  ! VR,          W44      4      pVP                  V4      V3# \        V4      w  ryV	^ 8H  \        VP                  V4      4      ,          p\        V 4      '       d   V\        V4      ( ,          p\        \        P                  ! VR,          W44      4      w  rŠVP                  V4      V3# )aÆ  Perform inverse.

Avoids crashing because of non-invertable matrix input and outputs the mask of valid solution.

A matrix is valid when it is not singular and its inverse is finite in the dtype of ``A``. A 2x2, 3x3
or 4x4 matrix is singular when ``|det A| <= 8 * n * eps * perm |A|``, the closed-form determinant
against the permanent of the absolute values (:func:`_is_singular`), which is the same in eager mode and
under graph capture and on every torch version, or, in eager mode, when ``inv_ex`` reports a zero
pivot; a larger matrix by the zero pivot alone. An invalid matrix is inverted as the
identity, so its row of the output is the identity. The differentiated inverse therefore never sees a
singular matrix, and the gradient with respect to the valid matrices (and to any parameter they
share with an invalid one) stays finite.

Args:
    A: square matrices of shape ``(*, N, N)``.

Returns:
    The inverse ``(*, N, N)`` and the validity mask ``(*)``.
rC  rM   r²   rÅ   )r!   r3   r’   rB   r+   rX  r´   rF   r  r¨   rÁ   rQ  rÐ   r    rJ  r   )r@  Údtype_originalr3   r[  rX  r]  ÚmaskÚinverse_detachedrà   r`  rf  s   &          r/   Úsafe_inverse_with_maskrn  W  s]  € ô( ˜1Ð6Ô7à—W‘W€NÜ,¨^Ó<€EØ�T‰T�%‹[€FÜ
�)Š)�F—L‘L Õ$¨V¯]©]À%Ô
H€Cð
 —‘“€JÜ×!Ò!Ô&>¸q×&AÒ&Aô ˜ZÓ(Ð(ˆÜ/´·²¸DÀÕ<QÐS]Ó0cÓdÐØ”lÐ#3×#6Ñ#6°~Ó#FÓGÕGˆÜ&¤u§{¢{°4¸Õ3HÈ&Ó'VÓWˆØ�z‰z˜.Ó)¨4Ð/Ð/ä# JÓ/ÑÐØ�A‰IœÐ&6×&9Ñ&9¸.Ó&IÓJÕJ€DÜ ×"Ò"Ø”| JÓ/Ð/Õ/ˆÜœŸš D¨Õ$9¸6ÓGÓH�J€GØ�:‰:�nÓ% tÐ+Ð+r1   c                ó0   € V ^8„  d   QhR\         R\         /# )r'   Úbothr)   r\   )r.   s   "r/   r0   r0   ˆ  s   € ÷ 'ñ 'œdð '¬dñ 'r1   c                ó¤   € V '       d5   \         ;QJ d    R R 4       F  '       g   K   R# 	  R# ! R R 4       4      # \        P                  ! 4       # )aÙ  Report whether a ``torch.autocast`` region is active, for any device type or for torch's default one.

``on = is_autocast_enabled()`` returns whether autocast is enabled for any of the CPU, CUDA, MPS and XPU device
types, so a ``torch.autocast("cpu")`` region counts. ``is_autocast_enabled(both=False)`` returns
``torch.is_autocast_enabled()`` without a device type instead, which never reports CPU autocast, and on torch 2.5.1
does not report MPS autocast either. A region entered with ``enabled=False`` counts as off.

Args:
    both: whether to consider the CPU, CUDA, MPS and XPU device types (``True``) or only the one
        ``torch.is_autocast_enabled()`` reports (``False``).

Returns:
    Whether autocast is enabled.

c              3   óN   "  € T F  p\         P                  ! V4      x € K  	  R # 5i©N)r+   Úis_autocast_enabled)Ú.0Údevice_types   & r/   Ú	<genexpr>Ú&is_autocast_enabled.<locals>.<genexpr>™  s    é € ÐkÑMj¸k”5×,Ò,¨[×9Ð9ÓMjùs   ‚#%TF)rH   rI   rh   Úxpu)Úanyr+   rt  )rp  s   &r/   rt  rt  ˆ  sA   € ÷  ß‹sÑkÑMjÓk�sŒsÐkŠsÐkˆsÑkÑMjÓkÓkÐkä×$Ò$Ó&Ð&r1   c                ó0   € V ^8„  d   QhR\         R\        /# ©r'   rv  r)   )r=   r-   )r.   s   "r/   r0   r0   ž  s   € ÷ 
ñ 
¤Sð 
¬Tñ 
r1   c                óf   € V R8X  d   R#  \         P                  ! V 4      #   \         d     R# i ; i)zmReturn whether a caller's autocast region is on for ``device_type``; a device type without autocast has none.ÚmetaF)r+   rt  ÚRuntimeError©rv  s   &r/   Ú_caller_autocast_onr�  ž  s7   € ð
 �fÔÙðÜ×(Ò(¨Ó5Ð5øÜô Úðús   ‹! ¡0¯0c                óF   € V ^8„  d   QhR\         R\        \        ,          /# r|  ©r=   r   r   )r.   s   "r/   r0   r0   «  s    € ÷ 
ñ 
¤Cð 
Ô,BÄ3Õ,Gñ 
r1   c                óh   € \        V 4      '       d   \        P                  ! V RR7      # \        4       # )aµ  Return a context that turns off the caller's autocast region for ``device_type``, if one is on.

Outside autocast it returns a ``nullcontext``: entering ``torch.autocast(enabled=False)`` anyway costs a few
microseconds per call, a few percent of a small solve, and raises for a device type without autocast, such as
``meta``. Every device type torch has an autocast region for is covered, ``xla``, ``hpu`` and a PrivateUse1 backend
too.
F)rv  Úenabled)r�  r+   Úautocastr   r€  s   &r/   Ú_autocast_disabledr‡  «  s(   € ô ˜;×'Ò'Ü�~Š~¨+¸uÔEÐEÜ‹=Ðr1   c                óF   € V ^8„  d   QhR\         R\        \        ,          /# r|  rƒ  )r.   s   "r/   r0   r0   ¸  s    € ÷ +ñ +¬sð +Ô7MÌcÕ7Rñ +r1   c                óZ   € V R8X  d   \        4       '       d   \        4       # \        V 4      # )aâ  Return :func:`_autocast_disabled` for a convolution, except under ``torch.compile`` on MPS.

A deliberate, scoped exception to running compiled and eager code alike (#6601). Compiled in an MPS autocast
region, a convolution under a nested ``torch.autocast(enabled=False)`` raises ``expected dtype torch.float32 but
got torch.bfloat16`` (or ``torch.float16``) on torch 2.14, 2.15 and the 2.16.0.dev20261106 nightly, with no kornia
code involved: compiled code on MPS drops the nested region (pytorch/pytorch#201630), and Inductor's check of the
convolution's output dtype then raises. The same convolution without the nested region runs. Skipping
the guard there returns those compiled calls to their earlier behaviour: they run, with the convolution in the
autocast dtype, as before the guard. Every other device, and every eager call on MPS, keeps the guard.

Scope: only the convolutions that build sampling positions or pyramid levels, in ``elastic_transform2d`` and
the two ``pyrdown`` calls of ``extract_patches_from_pyramid``. Cost, measured on an M1 with torch 2.15: those
compiled calls stay off the eager result by what the region rounds, 0.017 (bfloat16) and 0.0018 (float16) for
``elastic_transform2d`` and 0.0027 and 0.00032 for ``extract_patches_from_pyramid`` on a ``[0, 1]`` image.
Retire this, and use :func:`_autocast_disabled` directly, once the oldest supported torch has the fix of
pytorch/pytorch#201630 (pytorch/pytorch#202422, which makes compiled code honour MPS autocast regions).
rh   )rR   r   r‡  r€  s   &r/   Ú_convolution_outside_autocastrŠ  ¸  s%   € ð$ �eÔ¤§¢Ü‹}ÐÜ˜kÓ*Ð*r1   c                ót   € V ^8„  d   QhR\         \        P                  ,          R\        \        R3,          /# )r'   rŒ   r)   .)r   r+   r,   r   r   )r.   s   "r/   r0   r0   Ï  s/   € ÷ Sñ S¬´·±Õ(>ð SÄ5ÌÈcÈÅ?ñ Sr1   c                 ó¼  € RpRpV  Ft  pVf   K	  VP                   \        P                  \        P                  \        P                  39  d   V u # Vf   TpT;'       g    VP                   VP                   8g  pKv  	  Ve.   V'       d&   \        VP                  P                  4      '       g   V # \        ;QJ d    . R V  4       F  NK  	  5# ! R V  4       4      # )aö  Return ``tensors`` in float32 if a caller's autocast region would have cast them to one dtype, else unchanged.

A matrix product in an autocast region casts its float16, bfloat16 and float32 operands to the autocast dtype, so a
half-precision matrix from a model under AMP multiplies with a float32 one there, and raises under
:func:`_autocast_disabled`. Call this before leaving the region: such operands then meet in float32, which also
keeps the arithmetic accurate. Autocast does not cast float64 or integer operands, so a mismatch with those, a
mismatch outside autocast, and operands of one dtype all return unchanged and behave as they did. ``None`` entries
pass through. TorchScript cannot compile this; a scripted call stays in the caller's region.
NFc              3   óL   "  € T F  qf   R MVP                  4       x € K  	  R # 5irs  )rA   )ru  rE   s   & r/   rw  Ú,_reconcile_under_autocast.<locals>.<genexpr>å  s   é € ÐRÉ'Àš‘¨V¯\©\«^Ô;Ë'ùs   ‚"$)	r3   r+   r�   r4   r5   r�  rF   rP   Útuple)rŒ   r5  Ú
mismatchedrE   s   *   r/   Ú_reconcile_under_autocastr‘  Ï  s­   € ð €EØ€JÛˆØŠ>ÙØ�<‰<¤§¡¬u¯}©}¼e¿n¹nÐMÔMØŠNØŠ=ØˆEØ×>Ð> 6§<¡<°5·;±;Ñ#>Š
ñ ð ‚}ŸZÔ,?ÀÇÁ×@QÑ@Q×,RÒ,RØˆßŒ5ÑRÉ'ÓR�5ÐRˆ5ÑRÉ'ÓRÓRÐRr1   rR   r®   c                ó0   € V ^8„  d   QhR\         R\        /# )r'   Úframer)   )r
   r-   )r.   s   "r/   r0   r0   í  s   € ÷ \ñ \œyð \¬Tñ \r1   c                ó€   € \        V P                  P                  RR4      4      P                  R^4      ^ ,          R9   # )zgWhether ``frame`` runs code of torch or kornia, to attribute a warning to the first frame outside them.Ú__name__Ú r…   )r+   Úkornia)r=   Ú	f_globalsÚgetÚsplit)r“  s   &r/   Ú_in_torch_or_korniar›  í  s6   € äˆu�‰×"Ñ" :¨rÓ2Ó3×9Ñ9¸#¸qÓAÀ!ÕDÐH[Ñ[Ð[r1   c                ó(   € V ^8„  d   QhR\         RR/# )r'   Úmessager)   N)r=   )r.   s   "r/   r0   r0   ò  s   € ÷ 
Vñ 
VœSð 
V Tñ 
Vr1   c                óÒ   € ^p\         P                  ! ^4      pVe(   \        V4      '       d   VP                  V^,           rK+  \        P
                  ! T \        Ve   TM^R7       R# )a  Warn with a ``UserWarning`` attributed to the first frame outside kornia and torch.

For a warning raised where no fixed ``stacklevel`` names the user's line: inside a ``forward`` that
``nn.Module.__call__`` reaches through torch frames, or in code that other kornia classes call too.
N)Ú
stacklevel)r}   Ú	_getframer›  Úf_backÚwarningsÚwarnÚUserWarning)r�  Úlevelr“  s   &  r/   Ú_warn_at_callerr¦  ò  sO   € ð €EÜ!$§¢¨qÓ!1€EØ
Ò
Ô 3°E× :Ò :Ø—|‘| U¨Q¥YŠuÜ‡M‚M�'œ;¸EÒ<M±5ÐST×Ur1   c                ó$   € V ^8„  d   QhR\         /# r[   r\   )r.   s   "r/   r0   r0      s   € ÷ Uñ U”dñ Ur1   c                 ó<   € \         e   \        \        4       4      # R# )z«Whether execution is inside ``torch.compile`` or ``torch.export`` capture.

Falls back to Torch's older private Dynamo spelling when the public compiler helper is absent.
F)Ú_torch_is_compilingr-   rb   r1   r/   rR   rR   ÿ  s   € ô +>Ò*IŒ4Ô#Ó%Ó&ÐTÈuÐTr1   c                ó$   € V ^8„  d   QhR\         /# r[   r\   )r.   s   "r/   r0   r0   	  s   € ÷ ñ œTñ r1   c                  óL   € \         e   \        \        4       4      # \        4       # rs  )Ú_torch_is_exportingr-   rR   rb   r1   r/   Ú_is_exporting_eagerr­    s!   € äÒ&ÜÔ'Ó)Ó*Ð*ô
 ‹>Ðr1   c                ó$   € V ^8„  d   QhR\         /# r[   r\   )r.   s   "r/   r0   r0     s   € ÷ !ñ !”dñ !r1   c                 ób   € \         P                  P                  4       '       d   R# \        4       # )a€  Whether execution is inside a graph capture by ``torch.export`` or the dynamo ONNX exporter.

Used to switch to export-safe arithmetic (closed-form inverses, ``sort``-based medians, ...) and
to skip in-``forward`` side effects (e.g. stashing per-call state on ``self``) that
``torch.export`` rejects, without changing the captured output. Always ``False`` inside
TorchScript, so the guard is safe to call from scripted functions.

The flag is export-specific, not capture-specific: that is what Torch reports from 2.12 on (CI
checks 2.14), and it is the meaning kornia relies on. Releases before 2.12 also report it inside a
``torch.compile`` trace (2.9.1, and 2.5.1 through the fallback above), so a compiled call can take
different paths across versions (#5037). The call sites that keep this predicate run their eager
checks and routes inside ``torch.compile`` from 2.12 on, so some inputs of those operators do not
compile with ``fullgraph=True`` there. It is false under ``torch.jit.trace`` and the legacy ONNX exporter. Where
the intent is "inside any Dynamo capture" - skipping a data-dependent check that breaks
``fullgraph`` - use :func:`is_compiling`, which covers ``torch.compile`` and ``torch.export`` alike
on every supported release. Keep this predicate for what only an export needs:
:func:`crop_by_indices` routing to its dedicated export implementation, where letting a compiled
call take that route changes the sampling the eager and compiled paths agree on, and skipping
per-call state on ``self`` that ``torch.export`` rejects but a compiled call records and a caller
reads back afterwards, such as the ``transform_matrix`` of an augmentation.
F)r+   rN   rO   r­  rb   r1   r/   r®   r®     s#   € ô, ‡y�y×Ñ×ÒÙÜÓ Ð r1   c                ó|   € V ^8„  d   QhR\         P                  P                  R\        R\         P                  RR/# )r'   ÚmoduleÚnamerf   r)   N)r+   ÚnnÚModuler=   r,   )r.   s   "r/   r0   r0   .  s5   € ÷  ñ  ¤%§(¡(§/¡/ð  ¼ð  ÄÇÁð  ÐRVñ  r1   c                ó’  € \        V\        P                  P                  4      '       gz   VP	                  4       '       gd   VP                  4       '       gN   \        \        V 4      P                   RVP                  R4      : RVP                   R2VP                  R7      h\        V\        P                  P                  4      '       gE   \        P                  P                  4       '       gÊ   \        4       '       gº   \        4       '       gª   \        V\        P                  P                  4      '       g!   VP                  f_   VP                   '       gM   \        V\        P                  P                  4      '       d   TM\        P                  P                  V4      pMV P#                  W4       R# \%        WV4       R# )a‰  Store tensor ``x`` on ``module`` as ``name`` so it is optimizable, movable and serializable.

``x`` must be a floating-point or complex tensor, or an existing ``nn.Parameter``: an integer or bool tensor can
neither require grad nor follow the module's dtype conversions, so it raises ``TypeCheckError`` naming its dtype.
An existing ``nn.Parameter`` is kept, and a tensor that takes no part in autograd (no ``grad_fn`` and
``requires_grad=False``) becomes an ``nn.Parameter``, so the module is optimizable. ``nn.Parameter(x)`` would
re-root any other tensor as a new leaf: a group built from ``Se3.exp(v)`` would stop propagating gradients to
``v``, and a group built from the caller's own leaf that requires grad would take its gradient away from that
leaf. Such a tensor is registered as a buffer instead, which keeps it and its history while ``.to()``,
``state_dict()`` and ``load_state_dict()`` still reach it under the same key. Under graph capture
(``torch.jit.trace``, ``torch.compile``, ``torch.export`` and the dynamo ONNX exporter) neither a parameter nor a
buffer can be created inside the traced region, so the tensor is kept as a plain attribute of the module being
built. torch cannot deep-copy such a buffer, so a module using it takes ``_deepcopy_module_state`` as its
``__deepcopy__``.

Raises:
    TypeCheckError: if ``x`` is neither a floating-point nor a complex tensor, nor an ``nn.Parameter``.

z stores rf  zF as module state, which needs a floating-point or complex tensor; got z-. Cast it first, for example with `.float()`.)rˆ   N)rW   r+   r³  Ú	ParameterÚis_floating_pointÚ
is_complexr$   rP   r•  Úlstripr3   rN   r­   rR   r®   Úgrad_fnr  Úregister_bufferÚsetattr)r±  r²  rf   s   &&&r/   Úregister_module_stater½  .  s(  € ô( �qœ%Ÿ(™(×,Ñ,×-Ò-°×1DÑ1D×1FÒ1FÈ!Ï,É,Ï.Ê.ÜÜ�F‹|×$Ñ$Ð% X¨d¯k©k¸#Ó.>Ñ-Að B#Ø#$§7¡7 )Ð+XðZàŸ™ô
ð 	
ô
 �!”U—X‘X×'Ñ'×(Ò(´·±×1EÑ1E×1GÒ1GÌ<Ï>Ê>Ô]i×]kÒ]kÜ�aœŸ™×+Ñ+×,Ò,°·±Ò1BÈ1Ï?Ï?È?Ü ¤5§8¡8×#5Ñ#5×6Ò6‘¼E¿H¹H×<NÑ<NÈqÓ<Q‰Aà×"Ñ" 4Ô+ÙÜˆF˜!Ör1   c                ó®   € V ^8„  d   QhR\         P                  P                  R\        \        \
        3,          R\         P                  P                  /# )r'   r±  Úmemor)   )r+   r³  r´  r   rm   r   )r.   s   "r/   r0   r0   Q  s9   € ÷ ñ ¤5§8¡8§?¡?ð ¼$¼sÄC¸x½.ð ÌUÏXÉXÏ_É_ñ r1   c                ón  € V P                   P                  4        Uu. uF'  p\        V\        P                  4      '       g   K%  VNK)  	  pp. V P                  RR7      OVO Fh  pVP                  f   K  \        V4      V9  g   K%  VP                  4       P                  4       P                  VP                  4      V\        V4      &   Kj  	  V P                  P                  V P                  4      pWQ\        V 4      &   VP                  \        P                   ! V P                   V4      4       V# u upi )ap  ``copy.deepcopy`` for a module whose state ``register_module_state`` registered.

torch cannot deep-copy a tensor with autograd history, so a buffer holding one would make ``copy.deepcopy``
raise. The copy holds such a buffer as a new leaf that keeps ``requires_grad``, still registered as a buffer,
like a ``torch.save`` / ``torch.load`` round trip; the copy has no history, so no gradient flows
back through it. The same applies to a plain tensor attribute, which is where ``register_module_state``
stores the tensor under graph capture. Everything else is deep-copied as usual. Assign it as the class's
``__deepcopy__``.
F)Úrecurse)Ú__dict__ÚvaluesrW   r+   r,   Úbuffersrº  Úidr  ÚcloneÚrequires_grad_r  Ú	__class__Ú__new__Ú__setstate__ÚcopyÚdeepcopy)r±  r¿  ÚvalueÚ
attributesrE   Úcopieds   &&    r/   Ú_deepcopy_module_staterÐ  Q  sî   € ð &,§_¡_×%;Ñ%;Ô%=ÓaÑ%=˜EÄÈEÔSX×S_ÑS_×A`—%�%Ñ%=€JÐaØ?�F—N‘N¨5�NÓ1Ð?°JÓ?ˆØ�>‰>Ô%¬"¨V«*¸DÖ*@Ø%Ÿ}™}›×4Ñ4Ó6×EÑEÀf×FZÑFZÓ[ˆD”�F“Óñ @ð ×Ñ×%Ñ% f×&6Ñ&6Ó7€FØŒˆF‹Ñà
×ÑœŸš f§o¡o°tÓ<Ô=Ø€Mùò bs   �"D2ÁD2c                ó0   € V ^8„  d   QhR\         R\         /# )r'   Úobjr)   ©r   )r.   s   "r/   r0   r0   f  s   € ÷ ñ œ3ð ¤3ñ r1   c                óF  € \        V 4      '       dN   \        V \        4      '       g8   \        V 4      P	                  4        UUu/ uF  w  rV\        V4      bK  	  upp# \        V \        4      '       d)   \        V R4      '       d   \        V 4      ! R V  4       !  # \        V \        \        34      '       d   \        V 4      ! R V  4       4      # \        V \        4      '       d/   V P	                  4        UUu/ uF  w  rV\        V4      bK  	  upp# V # u uppi u uppi )aü  Recursively convert dataclass instances to dictionaries.

A dataclass becomes a dict of its fields through :func:`dataclasses.asdict`, and lists, tuples,
namedtuples and dicts are rebuilt with their items converted; any other value is returned as it is.
Values reached through a dataclass are deep-copied by :func:`dataclasses.asdict`, tensors included,
so a tensor with autograd history (not a leaf) raises ``RuntimeError``. Outside any dataclass the
containers are rebuilt, but their items are not copied.
Ú_fieldsc              3   ó8   "  € T F  p\        V4      x € K  	  R # 5irs  ©Údataclass_to_dict©ru  Úitems   & r/   rw  Ú$dataclass_to_dict.<locals>.<genexpr>s  s   é € ÐC¹s°tÔ,¨T×2Ð2»sùó   ‚c              3   ó8   "  € T F  p\        V4      x € K  	  R # 5irs  r×  rÙ  s   & r/   rw  rÛ  u  s   é € ÐA¹S°TÔ*¨4×0Ð0»SùrÜ  )
r	   rW   rP   r   ÚitemsrØ  r�  ru   r¶   Údict)rÒ  ÚkeyrÍ  s   &  r/   rØ  rØ  f  sæ   € ô �C×Ò¤¨C´×!6Ò!6Ü@FÀsÃ×@QÑ@QÔ@SÔTÑ@S±*°#�Ô& uÓ-Ò-Ñ@SÒTÐTÜ�#”u×Ò¤'¨#¨y×"9Ò"9ä�CŒyÑC¹sÓCÑDÐDÜ�#œœe�}×%Ò%Ü�CŒyÑA¹SÓAÓAÐAÜ�#”t×ÒØ@CÇ	Á	ÄÔLÁ±*°#�Ô& uÓ-Ò-ÁÒLÐLØ€Jùó Uùó Ms   ÁDÃ:DÚTc                ó<   € V ^8„  d   QhR\         R\        R\        /# )r'   rÍ  Úoriginr)   )r   rP   r-   )r.   s   "r/   r0   r0   ~  s&   € ÷ rñ rœ3ð r¬ð r´ñ rr1   c                ó¨   € \        V 4      \        \        39   ;'       d4    \        V\        4      ;'       d    \        V\
        \        34      '       * # )zcWhether ``value`` is a list or tuple that ``dict_to_dataclass`` converts for a sequence annotation.)rP   r¶   r�  Ú
issubclassr   r=   Úbytes)rÍ  rã  s   &&r/   Ú_is_sequence_ofrç  ~  s?   € ä�‹;œ4¤˜-Ñ'×qÐq¬J°v¼xÓ,H×qÐqÔQ[Ð\bÔehÔjoÐdpÓQqÔMqÐqr1   c                ó<   € V ^8„  d   QhR\         R\         R\        /# ©r'   rÍ  Ú
annotationr)   )r   r-   )r.   s   "r/   r0   r0   ƒ  s!   € ÷ 
ñ 
œCð 
¬Sð 
´Tñ 
r1   c                ó  € \        V4      ;'       g    TpV\        J g   \        V\        4      '       g   R# \	        V4      '       d   \        V \
        V34      #  \        W4      ;'       g    \        W4      #   \         d     R# i ; i)zVWhether ``value`` can be held by ``annotation``, as ``dict_to_dataclass`` converts it.T)r   r   rW   rP   r	   rß  rç  Ú	TypeError)rÍ  rê  Útargets   && r/   Ú_fits_annotationrî  ƒ  sv   € ä˜
Ó#×1Ð1 z€FØ”SÓ¤
¨6´4× 8Ò 8ÙÜ�F×ÒÜ˜%¤$¨ Ó0Ð0ðÜ˜uÓ-×JÐJ´¸EÓ1JÐJøÜô Úðús   ÁA: Á.A: Á:B	ÂB	c                ó<   € V ^8„  d   QhR\         R\         R\         /# ré  rÓ  )r.   s   "r/   r0   r0   �  s!   € ÷ ñ ¤ð ´#ð ¼#ñ r1   c           
     ó´  a€ \        V\        4      '       d0   \        V4      '       d   \        W4      '       d   V # \        W4      # \	        V4      \        V4      upoV\        J g   V\        J dI   S Uu. uF  p\        W4      '       g   K  VNK  	  pp\        V4      ^8X  d   \        W^ ,          4      # T # \        V\        4      '       d	   S'       g   V # \        W4      '       dt   V\        J dO   SR,          \        Jd>   \        S4      \        V 4      8w  d   V # \        V 4      ! R \        V S4       4       4      # \        V 4      ! V3R lV  4       4      # \        V 4      \        J d]   \!        V\"        4      '       dG   \        S4      ^8X  d7   V P%                  4        UUu/ uF  w  rVV\        VS^,          4      bK  	  upp# V # u upi u uppi )zeReturn ``value`` with each dict that ``annotation`` types as a dataclass converted to that dataclass.c              3   ó<   "  € T F  w  r\        W4      x € K  	  R # 5irs  ©Ú_value_for_annotation)ru  rÚ  Úargs   &  r/   rw  Ú(_value_for_annotation.<locals>.<genexpr>Ÿ  s   é € ÐbÑQaÁIÀDÔ4°T×?Ð?ÓQaùs   ‚c              3   óJ   <"  € T F  p\        VS^ ,          4      x € K  	  R# 5i)r   Nrò  )ru  rÚ  Úargss   & €r/   rw  rõ     s    øé € ÐRÉEÀDÔ0°°t¸Aµw×?Ð?ËEùs   ƒ #r²   )rW   rP   r	   Údict_to_dataclassr   r   r   r   rî  rT  ró  rç  r�  ÚEllipsisÚziprß  rå  r   rÞ  )rÍ  rê  rã  rô  Úfittingrà  rÚ  r÷  s   &&     @r/   ró  ró  �  sr  ø€ ä�*œd×#Ò#¬°Z×(@Ò(@Ü" 5×5Ò5ˆuÐ_Ô;LÈUÓ;_Ð_Ü˜jÓ)¬8°JÓ+?€L€FˆDØ”ƒ˜&¤IÓ-á"&ÓG¡$˜3Ô*:¸5×*F—3�3¡$ˆÐGÜ;>¸w»<È1Ô;LÔ$ U°A­JÓ7ÐWÐRWÐWÜ�vœt×$Ò$¯ØˆÜ�u×%Ò%Ø”U‹?˜t B�x¬xÓ7Ü�4‹yœC ›JÔ&Ø�Ü˜”;ÑbÔQTÐUZÐ\`ÔQaÓbÓbÐbÜ�EŒ{ÔRÉEÓRÓRÐRÜˆEƒ{”dÓœz¨&´'×:Ò:¼sÀ4»yÈA¼~ØKPÏ;É;Ì=ÔYÉ=¹i¸c�Ô*¨4°°aµÓ9Ò9É=ÒYÐYØ€Lùò Hùó Zs   Á6GÂGÆ*Gc                ót   € V ^8„  d   QhR\         \        \        3,          R\        \        ,          R\        /# )r'   Údict_objÚdataclass_typer)   )r   r=   r   r   rá  )r.   s   "r/   r0   r0   ¦  s-   € ÷ (.ñ (.¤¤S¬# X¥ð (.ÄÄQÅð (.ÌAñ (.r1   c           
     óÚ  € \        V \        R4       \        \        V4      R4        \	        V4      p\        V4       Uu/ uF3  q3P                  VP                  VP                  VP                  4      bK5  	  ppV P                  4        UUu/ uF   w  rVYUV9   d   \        WdV,          4      MTbK"  	  pppV! R/ VB #   \
        \        \        \        3 d    / p L«i ; iu upi u uppi )aœ  Recursively convert dictionaries to dataclass instances.

A field annotated with a dataclass gets its dict value converted to that dataclass, and so does a
dataclass inside the field's ``Optional[...]`` or other union, the elements of a plain ``list`` or ``tuple``
value under a sequence annotation, or the values of a plain ``dict`` value under a mapping annotation (a
namedtuple or a ``dict`` subclass is kept whole). String annotations, including every annotation
in a module with ``from __future__ import annotations``, are resolved with :func:`typing.get_type_hints`.
A value that is already an instance of the annotated dataclass is kept as it is, and values of other
fields are passed on unchanged.

A union is followed only when exactly one of its members can hold the value: a dict for a
``Union[A, B]`` of two dataclasses, or for ``Union[A, dict]``, stays a dict. When the annotations
cannot be resolved, for example a string that names a class defined inside a function, they are used
as written, and a string annotation converts nothing.

Args:
    dict_obj: the field values, keyed by field name.
    dataclass_type: the dataclass to build.

Returns:
    An instance of ``dataclass_type``.

Raises:
    TypeCheckError: if ``dict_obj`` is not a dict, or a value annotated with a dataclass outside a union
        is neither a dict nor an instance of that dataclass.
    BaseError: if ``dataclass_type`` is not a dataclass.

zInput conf must be dictz"dataclass_type must be a dataclassrb   )r"   rß  r    r	   r   ÚAttributeErrorÚ	NameErrorÚSyntaxErrorrì  r   r²  r™  rP   rÞ  ró  )rý  rþ  ÚhintsÚfÚfield_typesrà  rÍ  Úconstructor_argss   &&      r/   rø  rø  ¦  sä   € ô: �h¤Ð&?Ô@Ü”˜nÓ-Ð/SÔTðÜ˜~Ó.ˆô OUÐUcÔNdÓ"eÑNdÈ§6¡6¨5¯9©9°Q·V±V¸Q¿V¹VÓ+DÒ#DÑNd€KÐ"eð #Ÿ.™.Ô*ôá*‰JˆCð 	ÀkÔ?QÔ" 5°cÕ*:Ô;ÐW\Ò\Ù*ð ñ ñ Ñ-Ð,Ñ-Ð-øô œI¤{´IÐ>ô ØŠðüâ"eùós   ¨B? Á 9C"Â&C'Â?CÃCc                óÄ   € V ^8„  d   QhR\         P                  P                  R\         P                  R\         P                  R\
        R\        R\         P                  /# )r'   ÚmodelrU   rF   Ú
batch_sizeÚkwargsr)   )r+   r³  r´  r,   rF   rm   r   )r.   s   "r/   r0   r0   Ñ  sP   € ÷ 5ñ 5Ü�8‰8�?‰?ð5Ü"'§,¡,ð5Ü8=¿¹ð5ÜRUð5Ügjð5ä
‡\�\ñ5r1   c                ól  a€ \        S^ 8„  V3R l4       V P                  V4      p\        V4      pSpVS8”  d¿   . p\        Wg,          ^,           4      p	\	        V	4       Fc  p
W§,          p\        V
^,           V,          V4      pW¼8¼  d   K-  V! WV P                  V4      3/ VB p\        V4       VP                  V4       Ke  	  \        P                  ! V^ 4      pVP                  VP                  4      # V! VP                  V4      3/ VB p\        V4       VP                  VP                  4      # )a>  Run a model in micro-batches on a chosen device and return the output on the input's device.

``out = batched_forward(model, data, device, batch_size=128)`` moves ``model`` to ``device``, runs it on consecutive
slices of ``batch_size`` samples along the first dimension of ``data``, each moved to ``device``, and concatenates
the outputs along the first dimension. Use it when ``model(data)`` does not fit into device memory. ``model`` stays
on ``device`` afterwards, and gradients are tracked: call it under ``torch.no_grad()`` for inference.

Args:
    model: a module that returns one tensor whose first dimension follows its input's.
    data: the input tensor, ``(B, *)``.
    device: the device to run the model on.
    batch_size: the number of samples per call, a positive integer.
    **kwargs: keyword arguments passed to every call of ``model``.

Returns:
    The concatenated model output, on ``data.device``.

Raises:
    BaseError: if ``batch_size`` is not positive, or the model returns anything but a
        single tensor (e.g. a tuple of tensors).

Example:
    >>> import torch
    >>> from kornia.core.utils import batched_forward
    >>> model = torch.nn.Identity()
    >>> x = torch.rand(300, 2)
    >>> out = batched_forward(model, x, torch.device("cpu"), batch_size=128)
    >>> bool(torch.allclose(out, x))
    True

c                  ó   <€ R S  2# )z!batch_size must be positive, got rb   )r	  s   €r/   Ú<lambda>Ú!batched_forward.<locals>.<lambda>ó  s   ø€ Ð+LÈZÈLÑ)Yr1   )r    rB   rT  rm   rÕ   ræ   Ú_check_batched_forward_outputÚappendr+   ÚcatrF   )r  rU   rF   r	  r
  Ú	model_devrA  ÚbsÚout_listÚ	n_batchesÚ	batch_idxÚstÚendr¤   s   &&&f,         r/   Úbatched_forwardr  Ñ  s  ø€ ôD �˜a‘Ô!YÔZØ—‘˜Ó €IÜ�‹Y€AØ€BØˆ:„~ØˆÜ˜� !�Ó$ˆ	Ü˜yÖ)ˆIØ•ˆBÜ�y 1•}¨Õ*¨AÓ.ˆCØŒyÙÙ˜D C˜LŸO™O¨FÓ3Ñ>°vÑ>ˆCÜ)¨#Ô.Ø�O‰O˜CÖ ñ *ô �iŠi˜ !Ó$ˆØ�v‰v�d—k‘kÓ"Ð"Ù
�D—G‘G˜F“OÑ
. vÑ
.€CÜ! #Ô&Ø�6‰6�$—+‘+ÓÐr1   c                ó(   € V ^8„  d   QhR\         RR/# )r'   Úoutputr)   NrÓ  )r.   s   "r/   r0   r0   	  s   € ÷ ñ ¬#ð °$ñ r1   c                 óX   a € \        \        S \        P                  4      V 3R  l4       R# )c                  ó4   <€ R \        S 4      P                   2# )zBbatched_forward expects a model that returns a single tensor, got )rP   r•  ©r  s   €r/   r  Ú/_check_batched_forward_output.<locals>.<lambda>  s   ø€ ÐTÔUYÐZ`ÓUa×UjÑUjÐTkÑlr1   N)r    rW   r+   r,   r  s   fr/   r  r  	  s   ø€ ÜÜ�6œ5Ÿ<™<Ó(Ülör1   )ÚbilinearÚzerosNrs  )r   )r„   )T)é€   )urË  Úimportlib.utilr_   r~   r}   r¢  Úcollections.abcr   r   Ú
contextlibr   r   Údataclassesr   r   r	   Útypesr
   r   Útypingr   r   r   r   r   r   r   r   r   r   r   r+   Útorch.nn.functionalr³  Ú
functionalr?   Útorch.linalgr   Úkornia.core._small_linalgr   r   r   r   r   r   r   r   Úkornia.core.checkr    r!   r"   Úkornia.core.exceptionsr#   r$   r7   rC   rS   rY   rc   rj   rq   rx   r€   r�   r’   r–   r¥   rª   r¨   r¹   r¼   rÁ   rÐ   rÉ   rã   rê   rô   rð   rø   r  r  r  r7  r:  r>  rF  rJ  rQ  rh  rn  rt  r�  r‡  rŠ  r‘  ÚgetattrÚcompilerÚ_dynamor©  r¬  r›  r¦  rN   ÚunusedrR   r­  r®   r½  rÐ  rØ  rá  rç  rî  ró  rø  r  r  rb   r1   r/   Ú<module>r3     s  ðó& Û Û Û 
Û ß -ß :ß 4Ñ 4ß &ß o× o× oÑ oã ß Ð Ý ÷	÷ 	ó 	÷ VÑ Uß >õ
:÷i÷.31÷l	=õ=õ
"÷
õ4õ(*õ&#1õL	Oõ	÷õ:-0õ`4õwõ võ 3õ
mõDW÷"=õB8÷&N÷& õ69õL÷69õ8)õ
8(õvYõ"õ4õ*(õ
"7õJ97õx.,÷b'õ,
õ
õ+õ.Sñ4 ˜eŸn™n¨n¸dÓC×sÐsÁwÈuÏ}É}Ð^lÐnrÓGsÐ Ù˜eŸn™n¨n¸dÓCÐ õ\õ

Vð ‡�×ÑôUó ðUð ‡�×Ñôó ðõ!õ6 õFõ*ñ* ˆCƒL€õrõ

õõ,(.÷V5÷pr1   