ó
    !Eñi¼e  ã                   óD  • S SK JrJr  S SKrS SKJs  Jr  S SKJr  S SK	J
r
  S SKJr  / SQrSS jrS r " S	 S
\5      r " S S\
5      r  SSS.S\
S\S\S-  S\S\
4
S jjjr " S S\
5      rS S\
S\S\4S jjr " S S\
5      r    S!S\
S\S\S\S\S-  S\
4S jjrg)"é    )ÚautoÚEnumN)ÚTensor)ÚModule)Úparametrize)Ú
orthogonalÚspectral_normÚweight_normc                 ó:  • U R                  S5      U R                  S5      p2[        R                  " X0R                  U R                  S9nSU-  [        R
                  " U R                  5      R                  -  n[        R                  " U R                  U -  XAS9$ )Néþÿÿÿéÿÿÿÿ©ÚdtypeÚdeviceg      $@)Úatol)	ÚsizeÚtorchÚeyer   r   ÚfinfoÚepsÚallcloseÚmH)ÚQr   ÚnÚkÚIds        Ú\/home/mande/repo/quber/.venv/lib/python3.13/site-packages/torch/nn/utils/parametrizations.pyÚ_is_orthogonalr      sk   € Ø�6‰6�"‹:�q—v‘v˜b“z€qÜ	�Š�1ŸG™G¨A¯H©HÑ	5€Bà
�‰(”U—[’[ §¡Ó)×-Ñ-Ñ
-€CÜ�>Š>˜!Ÿ$™$ ™( BÑ1Ð1ó    c                 óÒ   • [         R                  " U 5      u  p[         R                  R                  X5      nX1R	                  SSS9R                  5       R                  S5      -  nU$ )z{Assume that A is a tall matrix.

Compute the Q factor s.t. A = QR (A may be complex) and diag(R) is real and non-negative.
r   r   ©Údim1Údim2)r   ÚgeqrfÚlinalgÚhouseholder_productÚdiagonalÚsgnÚ	unsqueeze)ÚAÚXÚtaur   s       r   Ú_make_orthogonalr-      sU   € ô
 �[Š[˜‹^�F€AÜ�‰×(Ñ(¨Ó0€Aà�‰˜ "ˆÐ	%×	)Ñ	)Ó	+×	5Ñ	5°bÓ	9Ñ9€AØ€Hr   c                   ó>   • \ rS rSr\" 5       r\" 5       r\" 5       rSrg)Ú	_OrthMapsé"   © N)	Ú__name__Ú
__module__Ú__qualname__Ú__firstlineno__r   Ú
matrix_expÚcayleyÚhouseholderÚ__static_attributes__r1   r   r   r/   r/   "   s   † Ù“€JÙ‹V€FÙ“&ƒKr   r/   c                   óö   ^ • \ rS rSr% \\S'   SS.S\SS4U 4S jjjrS	\R                  S\R                  4S
 jr	\R                  R                  5       S\R                  S\R                  4S j5       rSrU =r$ )Ú_Orthogonalé(   ÚbaseT©Úuse_trivializationÚorthogonal_mapÚreturnNc                óì   >• [         TU ]  5         UR                  5       (       a  U[        R                  :X  a  [        S5      eUR                  U l        X l        U(       a  U R                  SS 5        g g )NzAThe householder parametrization does not support complex tensors.r=   )	ÚsuperÚ__init__Ú
is_complexr/   r8   Ú
ValueErrorÚshaper@   Úregister_buffer)ÚselfÚweightr@   r?   Ú	__class__s       €r   rD   Ú_Orthogonal.__init__+   si   ø€ ô 	‰ÑÔð ×Ñ×Ñ >´Y×5JÑ5JÓ#JÜØSóð ð —\‘\ˆŒ
Ø,ÔÞØ× Ñ  ¨Õ.ð r   r+   c           	      ó¼  • UR                  S5      UR                  S5      p2X#:  nU(       a  UR                  nX2p2U R                  [        R                  :X  d  U R                  [        R
                  :X  Ga=  UR                  5       nX#:w  aI  [        R                  " XR                  X"U-
  5      R                  " / UR                  S S QSPSP76 /SS9nXR                  -
  nU R                  [        R                  :X  a  [        R                  " U5      nO�U R                  [        R
                  :X  ao  [        R                  " X%R                  UR                  S9n[        R                   R#                  [        R$                  " XuSS9[        R$                  " XuSS95      nX#:w  a	  WSS U24   nOtUR                  SS	9nS
SXU-  R'                  SS9-   -  n[        R                   R)                  XX5      nXaR+                  SSS9R-                  5       R/                  S5      -  n[1        U S5      (       a  U R2                  W-  nU(       a  WR                  nW$ )Nr   r   ©Údimr   g      à¿)Úalphag      à?.)r'   g       @g      ð?r!   r=   )r   ÚmTr@   r/   r6   r7   Útrilr   ÚcatÚ	new_zerosÚexpandrG   r   r   r   r   r%   ÚsolveÚaddÚsumr&   r'   Úintr)   Úhasattrr=   )	rI   r+   r   r   Ú
transposedr*   r   r   r,   s	            r   ÚforwardÚ_Orthogonal.forwardF   sð  € Ø�v‰v�b‹z˜1Ÿ6™6 "›:ˆ1Ø‘Uˆ
ÞØ—‘ˆAØˆqð ×Ñ¤9×#7Ñ#7Ó7Ø×"Ñ"¤i×&6Ñ&6Ô6ð —‘“ˆAØ‹vä—I’IØŸ™ A¨1¡uÓ-×4Ò4ÐK°a·g±g¸c¸r°lÐKÀBÐKÈÒKÐLÐRTñ�ð —D‘D‘ˆAà×"Ñ"¤i×&:Ñ&:Ó:Ü×$Ò$ QÓ'‘Ø×$Ñ$¬	×(8Ñ(8Ó8ä—Y’Y˜q¯©¸¿¹ÑA�Ü—L‘L×&Ñ&Ü—I’I˜b¨4Ñ0´%·)²)¸BÈÑ2Mó�ð ‹và�c˜2˜A˜2�g‘J�øð —‘ �Ð#ˆAØ˜ ¡Ÿ{™{¨r˜{Ð2Ñ2Ñ3ˆCÜ—‘×0Ñ0°Ó8ˆAð —J‘J B¨R�JÐ0×4Ñ4Ó6×@Ñ@ÀÓDÑDˆAä�4˜× Ñ à—	‘	˜A‘ˆAÞà—‘ˆAØˆr   r   c                 ó"  • UR                   U R                   :w  a&  [        SU R                    SUR                    S35      eUnUR                  S5      UR                  S5      pCX4:  nU(       a  UR                  nXCpC[	        U S5      (       d°  U R
                  [        R                  :X  d  U R
                  [        R                  :X  a  [        S5      e[        R                  " U5      u  pgUR                  SSS9R                  5         UR                  SSS9US	:H  ==   S-  ss'   U(       a  UR                  $ U$ X4:X  a-  [        U5      (       d  [        U5      nOuUR!                  5       nOd[        R"                  " UR                  5       S S X3U-
  4-   UR$                  UR&                  S
.6n[        R(                  " X/SS9n[        U5      nXl        [        R,                  " U5      n	U	R                  SSS9R/                  S5        U	$ )Nz0Expected a matrix or batch of matrices of shape z. Got a tensor of shape Ú.r   r   r=   ztIt is not possible to assign to the matrix exponential or the Cayley parametrizations when use_trivialization=False.r!   g        r   rN   g      ð¿)rG   rF   r   rQ   rZ   r@   r/   r7   r6   ÚNotImplementedErrorr   r$   r'   Úsign_r   r-   ÚcloneÚrandnr   r   rS   r=   Ú
zeros_likeÚfill_)
rI   r   ÚQ_initr   r   Ú	transposer*   r,   ÚNÚneg_Ids
             r   Úright_inverseÚ_Orthogonal.right_inversex   sÒ  € à�7‰7�d—j‘jÓ ÜØBÀ4Ç:Á:À,ð O)Ø)*¯©¨	°ð4óð ð
 ˆØ�v‰v�b‹z˜1Ÿ6™6 "›:ˆ1Ø‘Eˆ	ÞØ—‘ˆAØˆqô �t˜V×$Ñ$ð ×#Ñ#¤y×'7Ñ'7Ó7Ø×&Ñ&¬)×*>Ñ*>Ó>ä)ðTóð ô —[’[ “^‰FˆAð �J‰J˜B RˆJÐ(×.Ñ.Ô0ð �J‰J˜B RˆJÐ(¨°©Ó4¸Ñ:Ó4Þ$�1—4‘4Ð+¨!Ð+à‹vä% a×(Ñ(Ü(¨Ó+‘AàŸ™›	‘Aô —K’KØ—f‘f“h˜s �m q¨a©% jÑ0¸¿¹ÈÏÉò�ô —I’I˜q˜f¨"Ñ-�Ü$ QÓ'�ØŒIô ×%Ò% fÓ-ˆFØ�O‰O ¨"ˆOÐ-×3Ñ3°DÔ9ØˆMr   )r=   r@   rG   )r2   r3   r4   r5   r   Ú__annotations__r/   rD   r   r\   ÚautogradÚno_gradrj   r9   Ú__classcell__©rK   s   @r   r;   r;   (   s€   ø‡ Ø
ƒLð HLò/Ø&/ð/à	÷/ð /ð60˜Ÿ™ð 0¨%¯,©,ô 0ðd ‡^�^×ÑÓðE˜uŸ|™|ð E°·±ó Eó öEr   r;   Tr>   ÚmoduleÚnamer@   r?   rA   c                óÂ  • [        XS5      n[        U[        5      (       d  [        SU  SU S35      eUR                  S:  a  [        SUR                   S35      eUc=  UR                  S5      UR                  S	5      :X  d  UR                  5       (       a  S
OSn[        [        US5      nUc  [        SU 35      e[        XEUS9n[        R                  " XUSS9  U $ )a  Apply an orthogonal or unitary parametrization to a matrix or a batch of matrices.

Letting :math:`\mathbb{K}` be :math:`\mathbb{R}` or :math:`\mathbb{C}`, the parametrized
matrix :math:`Q \in \mathbb{K}^{m \times n}` is **orthogonal** as

.. math::

    \begin{align*}
        Q^{\text{H}}Q &= \mathrm{I}_n \mathrlap{\qquad \text{if }m \geq n}\\
        QQ^{\text{H}} &= \mathrm{I}_m \mathrlap{\qquad \text{if }m < n}
    \end{align*}

where :math:`Q^{\text{H}}` is the conjugate transpose when :math:`Q` is complex
and the transpose when :math:`Q` is real-valued, and
:math:`\mathrm{I}_n` is the `n`-dimensional identity matrix.
In plain words, :math:`Q` will have orthonormal columns whenever :math:`m \geq n`
and orthonormal rows otherwise.

If the tensor has more than two dimensions, we consider it as a batch of matrices of shape `(..., m, n)`.

The matrix :math:`Q` may be parametrized via three different ``orthogonal_map`` in terms of the original tensor:

- ``"matrix_exp"``/``"cayley"``:
  the :func:`~torch.matrix_exp` :math:`Q = \exp(A)` and the `Cayley map`_
  :math:`Q = (\mathrm{I}_n + A/2)(\mathrm{I}_n - A/2)^{-1}` are applied to a skew-symmetric
  :math:`A` to give an orthogonal matrix.
- ``"householder"``: computes a product of Householder reflectors
  (:func:`~torch.linalg.householder_product`).

``"matrix_exp"``/``"cayley"`` often make the parametrized weight converge faster than
``"householder"``, but they are slower to compute for very thin or very wide matrices.

If ``use_trivialization=True`` (default), the parametrization implements the "Dynamic Trivialization Framework",
where an extra matrix :math:`B \in \mathbb{K}^{n \times n}` is stored under
``module.parametrizations.weight[0].base``. This helps the
convergence of the parametrized layer at the expense of some extra memory use.
See `Trivializations for Gradient-Based Optimization on Manifolds`_ .

Initial value of :math:`Q`:
If the original tensor is not parametrized and ``use_trivialization=True`` (default), the initial value
of :math:`Q` is that of the original tensor if it is orthogonal (or unitary in the complex case)
and it is orthogonalized via the QR decomposition otherwise (see :func:`torch.linalg.qr`).
Same happens when it is not parametrized and ``orthogonal_map="householder"`` even when ``use_trivialization=False``.
Otherwise, the initial value is the result of the composition of all the registered
parametrizations applied to the original tensor.

.. note::
    This function is implemented using the parametrization functionality
    in :func:`~torch.nn.utils.parametrize.register_parametrization`.


.. _`Cayley map`: https://en.wikipedia.org/wiki/Cayley_transform#Matrix_map
.. _`Trivializations for Gradient-Based Optimization on Manifolds`: https://arxiv.org/abs/1909.09501

Args:
    module (nn.Module): module on which to register the parametrization.
    name (str, optional): name of the tensor to make orthogonal. Default: ``"weight"``.
    orthogonal_map (str, optional): One of the following: ``"matrix_exp"``, ``"cayley"``, ``"householder"``.
        Default: ``"matrix_exp"`` if the matrix is square or complex, ``"householder"`` otherwise.
    use_trivialization (bool, optional): whether to use the dynamic trivialization framework.
        Default: ``True``.

Returns:
    The original module with an orthogonal parametrization registered to the specified
    weight

Example::

    >>> # xdoctest: +REQUIRES(env:TORCH_DOCTEST_LAPACK)
    >>> orth_linear = orthogonal(nn.Linear(20, 40))
    >>> orth_linear
    ParametrizedLinear(
    in_features=20, out_features=40, bias=True
    (parametrizations): ModuleDict(
        (weight): ParametrizationList(
        (0): _Orthogonal()
        )
    )
    )
    >>> # xdoctest: +IGNORE_WANT
    >>> Q = orth_linear.weight
    >>> torch.dist(Q.T @ Q, torch.eye(20))
    tensor(4.9332e-07)
NúModule 'ú(' has no parameter or buffer with name 'Ú'é   z8Expected a matrix or batch of matrices. Got a tensor of z dimensions.r   r   r6   r8   zLorthogonal_map has to be one of "matrix_exp", "cayley", "householder". Got: r>   T©Úunsafe)ÚgetattrÚ
isinstancer   rF   Úndimr   rE   r/   r;   r   Úregister_parametrization)rq   rr   r@   r?   rJ   Ú	orth_enumÚorths          r   r   r   Á   s  € ôv �V 4Ó(€FÜ�fœf×%Ñ%ÜØ�v�hÐFÀtÀfÈAÐNó
ð 	
ð ‡{�{�QƒÜðØ%Ÿ{™{˜m¨<ð9ó
ð 	
ð
 Ñð �{‰{˜2‹ &§+¡+¨b£/Ó1°V×5FÑ5F×5HÑ5Hñ àð 	ô œ	 >°4Ó8€IØÑÜðØ"Ð#ð%ó
ð 	
ô �vÐ=OÑP€DÜ×(Ò(¨°tÀDÒIØ€Mr   c                   óL   ^ • \ rS rSr S	S\S-  SS4U 4S jjjrS rS rSrU =r	$ )
Ú_WeightNormi<  rO   NrA   c                 ó8   >• [         TU ]  5         Uc  SnXl        g )Nr   )rC   rD   rO   )rI   rO   rK   s     €r   rD   Ú_WeightNorm.__init__=  s   ø€ ô 	‰ÑÔØ‰;ØˆCØ�r   c                 óD   • [         R                  " X!U R                  5      $ ©N)r   Ú_weight_normrO   )rI   Úweight_gÚweight_vs      r   r\   Ú_WeightNorm.forwardF  s   € Ü×!Ò! (°d·h±hÓ?Ð?r   c                 óP   • [         R                  " USU R                  5      nUnX#4$ )Nrw   )r   Únorm_except_dimrO   )rI   rJ   r‡   rˆ   s       r   rj   Ú_WeightNorm.right_inverseI  s(   € Ü×(Ò(¨°°D·H±HÓ=ˆØˆàÐ!Ð!r   rN   )r   )
r2   r3   r4   r5   rY   rD   r\   rj   r9   ro   rp   s   @r   r�   r�   <  s8   ø† ð ñà�4‰Zðð 
÷ð ò@÷"ð "r   r�   rO   c                 ó‚   ^• [        U5      n[        R                  " U TUSS9    SU4S jjnU R                  U5        U $ )aÒ  Apply weight normalization to a parameter in the given module.

.. math::
     \mathbf{w} = g \dfrac{\mathbf{v}}{\|\mathbf{v}\|}

Weight normalization is a reparameterization that decouples the magnitude
of a weight tensor from its direction. This replaces the parameter specified
by :attr:`name` with two parameters: one specifying the magnitude
and one specifying the direction.

By default, with ``dim=0``, the norm is computed independently per output
channel/plane. To compute a norm over the entire weight tensor, use
``dim=None``.

See https://arxiv.org/abs/1602.07868

Args:
    module (Module): containing module
    name (str, optional): name of weight parameter
    dim (int, optional): dimension over which to compute the norm

Returns:
    The original module with the weight norm hook

Example::

    >>> m = weight_norm(nn.Linear(20, 40), name='weight')
    >>> m
    ParametrizedLinear(
      in_features=20, out_features=40, bias=True
      (parametrizations): ModuleDict(
        (weight): ParametrizationList(
          (0): _WeightNorm()
        )
      )
    )
    >>> m.parametrizations.weight.original0.size()
    torch.Size([40, 1])
    >>> m.parametrizations.weight.original1.size()
    torch.Size([40, 20])

Trx   c                 ó¦   >• U T S3nU T S3nXp;   a=  X€;   a7  U R                  U5      n	U R                  U5      n
X�U ST S3'   X U ST S3'   g g g )NÚ_gÚ_vzparametrizations.z
.original0z
.original1)Úpop)Ú
state_dictÚprefixÚlocal_metadataÚstrictÚmissing_keysÚunexpected_keysÚ
error_msgsÚg_keyÚv_keyÚ	original0Ú	original1rr   s              €r   Ú_weight_norm_compat_hookÚ-weight_norm.<locals>._weight_norm_compat_hook~  s€   ø€ ð �(˜4˜& Ð#ˆØ�(˜4˜& Ð#ˆØÓ 5Ó#6Ø"Ÿ™ uÓ-ˆIØ"Ÿ™ uÓ-ˆIØGP˜&˜Ð!2°4°&¸
ÐCÑDØGP˜&˜Ð!2°4°&¸
ÐCÒDð	 $7Ðr   )rA   N)r�   r   r}   Ú"_register_load_state_dict_pre_hook)rq   rr   rO   r†   r�   s    `   r   r
   r
   P  sK   ø€ ôV ˜sÓ#€LÜ×(Ò(¨°°|ÈDÒQðQð 
÷Qð" ×-Ñ-Ð.FÔGØ€Mr   c                   óp  ^ • \ rS rSr   SS\R
                  S\S\S\SS4
U 4S jjjrS\R
                  S\R
                  4S	 jr	\R                  R                  5       S
\R
                  S\SS4S j5       rS\R
                  S\R
                  4S jrS\R
                  S\R
                  4S jrSrU =r$ )Ú_SpectralNormi“  rJ   Ún_power_iterationsrO   r   rA   Nc           	      óž  >• [         TU ]  5         UR                  nX5:¼  d  X5* :  a  [        SU SUS-
   SU S35      eUS::  a  [	        SU 35      eUS:¼  a  UOX5-   U l        X@l        US:”  aÞ  X l        U R                  U5      nUR                  5       u  pxUR                  U5      R                  SS5      n	UR                  U5      R                  SS5      n
U R                  S[        R                  " U	SU R                  S	95        U R                  S
[        R                  " U
SU R                  S	95        U R                  US5        g g )Nz5Dimension out of range (expected to be in range of [-z, é   z
] but got Ú)r   zGExpected n_power_iterations to be positive, but got n_power_iterations=Ú_u©rO   r   r�   é   )rC   rD   r|   Ú
IndexErrorrF   rO   r   r¢   Ú_reshape_weight_to_matrixr   Ú	new_emptyÚnormal_rH   ÚFÚ	normalizeÚ_power_method)rI   rJ   r¢   rO   r   r|   Ú
weight_matÚhÚwÚuÚvrK   s              €r   rD   Ú_SpectralNorm.__init__”  sO  ø€ ô 	‰ÑÔØ�{‰{ˆØ‹;˜# ›+ÜðØ�F˜"˜T A™X˜J j°°°Qð8óð ð
  Ó"Üð*Ø*<Ð)=ð?óð ð  ›(‘3¨©
ˆŒØŒØ�!‹8à&8Ô#Ø×7Ñ7¸Ó?ˆJØ—?‘?Ó$‰DˆAà×$Ñ$ QÓ'×/Ñ/°°1Ó5ˆAØ×$Ñ$ QÓ'×/Ñ/°°1Ó5ˆAØ× Ñ  ¤q§{¢{°1¸!ÀÇÁÑ'JÔKØ× Ñ  ¤q§{¢{°1¸!ÀÇÁÑ'JÔKð ×Ñ˜z¨2Õ.ð r   c                 ó  ^ • UR                   S::  a  [        SUR                    35      eT R                  S:w  a>  UR                  " T R                  /U 4S j[	        UR                  5       5       5       Q76 nUR                  S5      $ )Nr¤   z3Expected weight to have more than 1 dimension, got r   c              3   óJ   >#   • U  H  oTR                   :w  d  M  Uv •  M     g 7fr…   rN   )Ú.0ÚdrI   s     €r   Ú	<genexpr>Ú:_SpectralNorm._reshape_weight_to_matrix.<locals>.<genexpr>Ã  s   øé € ÐLÒ': !À4Ç8Á8¹mŸA™AÒ':ùs   ƒ#š	#)r|   ÚAssertionErrorrO   ÚpermuteÚrangeÚflatten)rI   rJ   s   ` r   rª   Ú'_SpectralNorm._reshape_weight_to_matrix¹  su   ø€ à�;‰;˜!ÓÜ ØEÀfÇkÁkÀ]ÐSóð ð �8‰8�q‹=à—^’^Ø—‘ðÜL¤u¨V¯Z©Z«\Ô':ÓLòˆFð �~‰~˜aÓ Ð r   r°   c                 óÆ  • UR                   S::  a  [        SUR                    35      e[        U5       Hª  n[        R                  " [
        R                  " XR                  5      SU R                  U R                  S9U l	        [        R                  " [
        R                  " UR                  U R                  5      SU R                  U R                  S9U l        M¬     g )Nr¤   z7Expected weight_mat to have more than 1 dimension, got r   )rO   r   Úout)r|   r¼   r¾   r­   r®   r   Úmvr�   r   r¦   ÚH)rI   r°   r¢   Ú_s       r   r¯   Ú_SpectralNorm._power_methodÈ  s«   € ðD �?‰?˜aÓÜ ØIÈ*Ï/É/ÐIZÐ[óð ô Ð)Ö*ˆAô —k’kÜ—’˜§W¡WÓ-ØØ—H‘HØ—G‘Gñ	ˆDŒGô —k’kÜ—’˜Ÿ™ t§w¡wÓ/ØØ—H‘HØ—G‘Gñ	ˆDŽGò +r   c                 óÖ  • UR                   S:X  a   [        R                  " USU R                  S9$ U R	                  U5      nU R
                  (       a  U R                  X R                  5        U R                  R                  [        R                  S9nU R                  R                  [        R                  S9n[        R                  " U[        R                  " X$5      5      nX-  $ )Nr¤   r   r§   )Úmemory_format)r|   r­   r®   r   rª   Útrainingr¯   r¢   r¦   rb   r   Úcontiguous_formatr�   ÚvdotrÃ   )rI   rJ   r°   r³   r´   Úsigmas         r   r\   Ú_SpectralNorm.forward   s§   € Ø�;‰;˜!Óä—;’;˜v¨1°$·(±(Ñ;Ð;à×7Ñ7¸Ó?ˆJØ�}�}Ø×"Ñ" :×/FÑ/FÔGà—‘—‘¬E×,CÑ,C�ÐDˆAØ—‘—‘¬E×,CÑ,C�ÐDˆAô —J’J˜q¤%§(¢(¨:Ó"9Ó:ˆEØ‘>Ð!r   Úvaluec                 ó   • U$ r…   r1   )rI   rÎ   s     r   rj   Ú_SpectralNorm.right_inverse  s	   € ð ˆr   )r¦   r�   rO   r   r¢   )r¤   r   çê-�™—q=)r2   r3   r4   r5   r   r   rY   ÚfloatrD   rª   rm   rn   r¯   r\   rj   r9   ro   rp   s   @r   r¡   r¡   “  sß   ø† ð #$ØØñ#/à—‘ð#/ð  ð#/ð ð	#/ð
 ð#/ð 
÷#/ð #/ðJ!°·±ð !ÀÇÁô !ð ‡^�^×ÑÓð5¨¯©ð 5È#ð 5ÐRVó 5ó ð5ðn"˜eŸl™lð "¨u¯|©|ô "ð" 5§<¡<ð °E·L±L÷ ò r   r¡   r¢   r   c           
      óv  • [        XS5      n[        U[        5      (       d  [        SU  SU S35      eUca  [        U [        R
                  R                  [        R
                  R                  [        R
                  R                  45      (       a  SnOSn[        R                  " X[        XRXC5      5        U $ )as  Apply spectral normalization to a parameter in the given module.

.. math::
    \mathbf{W}_{SN} = \dfrac{\mathbf{W}}{\sigma(\mathbf{W})},
    \sigma(\mathbf{W}) = \max_{\mathbf{h}: \mathbf{h} \ne 0} \dfrac{\|\mathbf{W} \mathbf{h}\|_2}{\|\mathbf{h}\|_2}

When applied on a vector, it simplifies to

.. math::
    \mathbf{x}_{SN} = \dfrac{\mathbf{x}}{\|\mathbf{x}\|_2}

Spectral normalization stabilizes the training of discriminators (critics)
in Generative Adversarial Networks (GANs) by reducing the Lipschitz constant
of the model. :math:`\sigma` is approximated performing one iteration of the
`power method`_ every time the weight is accessed. If the dimension of the
weight tensor is greater than 2, it is reshaped to 2D in power iteration
method to get spectral norm.


See `Spectral Normalization for Generative Adversarial Networks`_ .

.. _`power method`: https://en.wikipedia.org/wiki/Power_iteration
.. _`Spectral Normalization for Generative Adversarial Networks`: https://arxiv.org/abs/1802.05957

.. note::
    This function is implemented using the parametrization functionality
    in :func:`~torch.nn.utils.parametrize.register_parametrization`. It is a
    reimplementation of :func:`torch.nn.utils.spectral_norm`.

.. note::
    When this constraint is registered, the singular vectors associated to the largest
    singular value are estimated rather than sampled at random. These are then updated
    performing :attr:`n_power_iterations` of the `power method`_ whenever the tensor
    is accessed with the module on `training` mode.

.. note::
    If the `_SpectralNorm` module, i.e., `module.parametrization.weight[idx]`,
    is in training mode on removal, it will perform another power iteration.
    If you'd like to avoid this iteration, set the module to eval mode
    before its removal.

Args:
    module (nn.Module): containing module
    name (str, optional): name of weight parameter. Default: ``"weight"``.
    n_power_iterations (int, optional): number of power iterations to
        calculate spectral norm. Default: ``1``.
    eps (float, optional): epsilon for numerical stability in
        calculating norms. Default: ``1e-12``.
    dim (int, optional): dimension corresponding to number of outputs.
        Default: ``0``, except for modules that are instances of
        ConvTranspose{1,2,3}d, when it is ``1``

Returns:
    The original module with a new parametrization registered to the specified
    weight

Example::

    >>> # xdoctest: +REQUIRES(env:TORCH_DOCTEST_LAPACK)
    >>> # xdoctest: +IGNORE_WANT("non-deterministic")
    >>> snm = spectral_norm(nn.Linear(20, 40))
    >>> snm
    ParametrizedLinear(
      in_features=20, out_features=40, bias=True
      (parametrizations): ModuleDict(
        (weight): ParametrizationList(
          (0): _SpectralNorm()
        )
      )
    )
    >>> torch.linalg.matrix_norm(snm.weight, 2)
    tensor(1.0081, grad_fn=<AmaxBackward0>)
Nrt   ru   rv   r¤   r   )rz   r{   r   rF   r   ÚnnÚConvTranspose1dÚConvTranspose2dÚConvTranspose3dr   r}   r¡   )rq   rr   r¢   r   rO   rJ   s         r   r	   r	     s®   € ô` �V 4Ó(€FÜ�fœf×%Ñ%ÜØ�v�hÐFÀtÀfÈAÐNó
ð 	
ð �{ÜØä—‘×(Ñ(Ü—‘×(Ñ(Ü—‘×(Ñ(ð÷
ñ 
ð ‰CàˆCÜ×(Ò(Ø”m FÀÓIôð €Mr   r…   )rJ   N)rJ   r   )rJ   r¤   rÑ   N)Úenumr   r   r   Útorch.nn.functionalrÔ   Ú
functionalr­   r   Útorch.nn.modulesr   Útorch.nn.utilsr   Ú__all__r   r-   r/   r;   ÚstrÚboolr   r�   rY   r
   r¡   rÒ   r	   r1   r   r   Ú<module>rà      s'  ðç ã ß Ð Ý Ý #Ý &ò 9€ô2ò	ô�ô ôV�&ô Vðv Ø!%ðxð
  $òxØðxà
ðxð ˜$‘Jðxð
 ðxð öxôv"�&ô "ñ(@˜ð @ cð @¸3õ @ôFA�Fô AðL ØØØñeØðeà
ðeð ðeð 
ð	eð
 
ˆt‰ðeð öer   