
    shA:                         S r SSKJrJrJr  SSKrSSKJs  Jr	  SSK
Jr  / SQr " S S5      r " S S	5      r " S
 S5      r\" S\S9r    SS\S\S\S\S\\   S\4S jjrSS\S\S\4S jjrg)z=Spectral Normalization from https://arxiv.org/abs/1802.05957.    )AnyOptionalTypeVarN)Module)SpectralNorm SpectralNormLoadStateDictPreHookSpectralNormStateDictHookspectral_normremove_spectral_normc                   4   \ rS rSr% Sr\\S'   \\S'   \\S'   \\S'   \\S'       SS\S\S\S\S	S
4
S jjr	S\
R                  S	\
R                  4S jrS\S\S	\
R                  4S jrS\S	S
4S jrS\S\S	S
4S jrS r\S\S\S\S\S\S	S 4S j5       rSrg
)r         _versionnamedimn_power_iterationsepsweightreturnNc                 \    Xl         X0l        US::  a  [        SU 35      eX l        X@l        g )Nr   zGExpected n_power_iterations to be positive, but got n_power_iterations=)r   r   
ValueErrorr   r   )selfr   r   r   r   s        p/Users/tiagomarins/Projetos/claudeai/copy_bank/venv/lib/python3.13/site-packages/torch/nn/utils/spectral_norm.py__init__SpectralNorm.__init__"   s@     	"**<)=?  #5    c                 "   UnU R                   S:w  aV  UR                  " U R                   /[        UR                  5       5       Vs/ s H  o3U R                   :w  d  M  UPM     snQ76 nUR                  S5      nUR	                  US5      $ s  snf )Nr   )r   permuterangesizereshape)r   r   
weight_matdheights        r   reshape_weight_to_matrix%SpectralNorm.reshape_weight_to_matrix3   s    
88q=#++',Z^^-='>P'>!txx-A'>PJ #!!&"-- Qs   B
B
moduledo_power_iterationc           	      @   [        XR                  S-   5      n[        XR                  S-   5      n[        XR                  S-   5      nU R                  U5      nU(       a  [        R                  " 5          [        U R                  5       H|  n[        R                  " [        R                  " UR                  5       U5      SU R                  US9n[        R                  " [        R                  " Xe5      SU R                  US9nM~     U R                  S:  a:  UR                  [        R                  S9nUR                  [        R                  S9nS S S 5        [        R                  " U[        R                  " Xe5      5      nX8-  nU$ ! , (       d  f       N?= f)N_orig_u_vr   )r   r   out)memory_format)getattrr   r&   torchno_gradr    r   F	normalizemvtr   clonecontiguous_formatdot)	r   r(   r)   r   uvr#   _sigmas	            r   compute_weightSpectralNorm.compute_weight=   s0   < W!45FII,-FII,-226:
t667A 3aA EHHZ$;VWXA 8 **Q.e.E.EFAe.E.EFA ! 		!UXXj45! !s   6C F
Fc                    [         R                  " 5          U R                  USS9nS S S 5        [        XR                  5        [        XR                  S-   5        [        XR                  S-   5        [        XR                  S-   5        UR                  U R                  [         R                  R                  WR                  5       5      5        g ! , (       d  f       N= f)NFr)   r,   r-   r+   )	r1   r2   r>   delattrr   register_parameternn	Parameterdetach)r   r(   r   s      r   removeSpectralNorm.removes   s    ]]_((E(JF 		"		D()		D()		G+,!!$))UXX-?-?-PQ _s   C
C"inputsc           	      `    [        UU R                  U R                  XR                  S95        g )NrA   )setattrr   r>   training)r   r(   rI   s      r   __call__SpectralNorm.__call__|   s)    II??K	
r   c           
      n   [         R                  R                  UR                  5       R	                  U5      R                  5       UR                  5       UR                  S5      /5      R                  S5      nUR                  U[         R                  " U[         R                  " X5      5      -  5      $ )Nr   )r1   linalg	multi_dotr6   mmpinverse	unsqueezesqueezemul_r9   r5   )r   r#   r:   target_sigmar;   s        r   _solve_v_and_rescale!SpectralNorm._solve_v_and_rescale   s     LL""\\^z*335z||~q{{ST~V

'!* 	
 vvlUYYq%((:2I%JJKKr   c                    U R                   R                  5        H8  n[        U[        5      (       d  M  UR                  U:X  d  M,  [        SU 35      e   [        XX45      nU R                  U   nUc  [        SU S35      e[        U[        R                  R                  R                  5      (       a  [        S5      e[        R                  " 5          UR                  U5      nUR                  5       u  p[        R                   " UR#                  U	5      R%                  SS5      SUR&                  S9n[        R                   " UR#                  U
5      R%                  SS5      SUR&                  S9nS S S 5        [)        XR                  5        U R+                  UR                  S-   U5        [-        XR                  UR.                  5        U R1                  UR                  S	-   W5        U R1                  UR                  S
-   W5        U R3                  U5        U R5                  [7        U5      5        U R9                  [;        U5      5        U$ ! , (       d  f       N= f)Nz>Cannot register two spectral_norm hooks on the same parameter z/`SpectralNorm` cannot be applied as parameter `z	` is NonezThe module passed to `SpectralNorm` can't have uninitialized parameters. Make sure to run the dummy forward before applying spectral normalizationr   r   )r   r   r+   r,   r-   )_forward_pre_hooksvalues
isinstancer   r   RuntimeError_parametersr   r1   rD   	parameterUninitializedParameterr2   r&   r!   r3   r4   	new_emptynormal_r   rB   rC   rK   dataregister_bufferregister_forward_pre_hook_register_state_dict_hookr	   "_register_load_state_dict_pre_hookr   )r(   r   r   r   r   hookfnr   r#   hwr:   r;   s                r   applySpectralNorm.apply   s    --446D$--$))t2C"TUYTZ[  7 $C=##D)>A$yQ  fehh00GGHH\ 
 ]]_44V<J??$DAF,,Q/771=1"&&QAF,,Q/771=1"&&QA  	 !!"''G"3V< 	-rww~q1rww~q1((,(()B2)FG112RSU2VW	- _s   B"I
I()r   r   r   r   )r   r   r   -q=)__name__
__module____qualname____firstlineno__r   int__annotations__strfloatr   r1   Tensorr&   r   boolr>   rG   r   rM   rX   staticmethodrm   __static_attributes__ r   r   r   r      s   
 Hc
 I	H	J "#   	
  
".u|| . .4V 4 4%,, 4lRV R R
v 
s 
t 
L ++!+7:+AD+KP+	+ +r   r   c                   ,    \ rS rSrSS jr  SS jrSrg)r      Nc                     Xl         g Nrj   r   rj   s     r   r   )SpectralNormLoadStateDictPreHook.__init__       r   c                   ^^ U R                   nUR                  S0 5      R                  UR                  S-   S 5      n	U	b  U	S:  a  X(R                  -   mU	c"  [        UU4S jS 5       5      (       a  TT;  a  g Sn
S H,  nTU-   nUT;  d  M  Sn
U(       d  M  UR	                  U5        M.     U
(       a  g [
        R                  " 5          TTS	-      nTR                  T5      nX-  R                  5       nUR                  U5      nTTS
-      nUR                  UUU5      nUTTS-   '   S S S 5        g g ! , (       d  f       g = f)Nr
   .versionr   c              3   4   >#    U  H  nTU-   T;   v   M     g 7fr   r|   ).0s
state_dict
weight_keys     r   	<genexpr><SpectralNormLoadStateDictPreHook.__call__.<locals>.<genexpr>   s     T>S
Q*4>Ss   )r+   r,   r-   F)r+    r,   Tr+   r,   r-   )rj   getr   allappendr1   r2   popmeanr&   rX   )r   r   prefixlocal_metadatastrictmissing_keysunexpected_keys
error_msgsrj   versionhas_missing_keyssuffixkeyweight_origr   r=   r#   r:   r;   r   s    `                 @r   rM   )SpectralNormLoadStateDictPreHook.__call__   sF    WW $$_b9==GGj $
 ?gk'')JT>STTTj0
 $- 6)j('+$v$++C0 .  (g)=>#
3$-33588E
zD01++J5A01
:,- !) *( !s   A D55
Er   r   Nrp   rq   rr   rs   r   rM   r{   r|   r   r   r   r      s    )2 
)2r   r   c                   (    \ rS rSrSS jrSS jrSrg)r	      Nc                     Xl         g r   r   r   s     r   r   "SpectralNormStateDictHook.__init__   r   r   c                     SU;  a  0 US'   U R                   R                  S-   nXTS   ;   a  [        SU 35      eU R                   R                  US   U'   g )Nr
   r   z-Unexpected key in metadata['spectral_norm']: )rj   r   r^   r   )r   r(   r   r   r   r   s         r   rM   "SpectralNormStateDictHook.__call__   s]    .0.0N?+ggllZ'11!NseTUU/3ww/?/?',r   r   r   r   r|   r   r   r	   r	      s    @r   r	   T_module)boundr(   r   r   r   r   r   c                     Uca  [        U [        R                  R                  [        R                  R                  [        R                  R
                  45      (       a  SnOSn[        R                  XX$U5        U $ )a  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}

Spectral normalization stabilizes the training of discriminators (critics)
in Generative Adversarial Networks (GANs) by rescaling the weight tensor
with spectral norm :math:`\sigma` of the weight matrix calculated using
power iteration method. If the dimension of the weight tensor is greater
than 2, it is reshaped to 2D in power iteration method to get spectral
norm. This is implemented via a hook that calculates spectral norm and
rescales weight before every :meth:`~Module.forward` call.

See `Spectral Normalization for Generative Adversarial Networks`_ .

.. _`Spectral Normalization for Generative Adversarial Networks`: https://arxiv.org/abs/1802.05957

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

Returns:
    The original module with the spectral norm hook

.. note::
    This function has been reimplemented as
    :func:`torch.nn.utils.parametrizations.spectral_norm` using the new
    parametrization functionality in
    :func:`torch.nn.utils.parametrize.register_parametrization`. Please use
    the newer version. This function will be deprecated in a future version
    of PyTorch.

Example::

    >>> m = spectral_norm(nn.Linear(20, 40))
    >>> m
    Linear(in_features=20, out_features=40, bias=True)
    >>> m.weight_u.size()
    torch.Size([40])

r   r   )r]   r1   rD   ConvTranspose1dConvTranspose2dConvTranspose3dr   rm   )r(   r   r   r   r   s        r   r
   r
   	  sj    p {((((((
 
 CCv%7cBMr   c                    U R                   R                  5        HL  u  p#[        U[        5      (       d  M  UR                  U:X  d  M.  UR                  U 5        U R                   U	   O   [        SU SU  35      eU R                  R                  5        HE  u  p#[        U[        5      (       d  M  UR                  R                  U:X  d  M8  U R                  U	   O   U R                  R                  5        HF  u  p#[        U[        5      (       d  M  UR                  R                  U:X  d  M8  U R                  U	   U $    U $ )zRemove the spectral normalization reparameterization from a module.

Args:
    module (Module): containing module
    name (str, optional): name of weight parameter

Example:
    >>> m = spectral_norm(nn.Linear(40, 10))
    >>> remove_spectral_norm(m)
zspectral_norm of 'z' not found in )r[   itemsr]   r   r   rG   r   _state_dict_hooksr	   rj   _load_state_dict_pre_hooksr   )r(   r   kri   s       r   r   r   Q  s    ,,224dL))dii4.?KK))!,	 5 -dV?6(KLL++113d566477<<4;O((+ 4
 44::<d<==$'',,RVBV11!4M =
 Mr   )r   r   ro   N)r   )__doc__typingr   r   r   r1   torch.nn.functionalrD   
functionalr3   torch.nn.modulesr   __all__r   r   r	   r   rv   rt   rw   r
   r   r|   r   r   <module>r      s    C ) )    #e eT62 62v@ @ :V,
 EE
E E 
	E
 
#E EP  H r   