o
    rri>                     @   s:   d Z ddlZddlZdddZedZ	
	dddZdS )z Ways to make the model stronger.    N   c                 C   s   |   dksJ | jd | jd ksJ | jd }tj||| j| jd}t|D ]}| |}|jddd}|d|  }q(|	 S )zXThis is the power method. batch size is used to try multiple starting point in parallel.   r   r   )devicedtypeT)dimkeepdimg|=)
r   shapetorchrandnr   r   rangemmnormmean)mnitersbsr   b_nr    r   >/home/ubuntu/.local/lib/python3.10/site-packages/demucs/svd.pypower_iteration   s   

r   i  皙?r   FTc
                 C   sz  d}
t  |kr
dS |  D ]}|jddD ]\}}| d |k r#q|r>t|tjjtjj	fr>|
 dv r>|dd }|
 dkrM|t|d	}n|
 d
kr\|t|d	}n
|
 dkrcq|rfq|
 dkssJ ||jf|rtj|ddd d }n/|r|j\}}||k r|| }n| |}t|||	}nt|||d d d}|
|7 }
qq|
| S )a  
    Penalty on the largest singular value for a layer.
    Args:
        - model: model to penalize
        - min_size: minimum size in MB of a layer to penalize.
        - dim: projection dimension for the svd_lowrank. Higher is better but slower.
        - niters: number of iterations in the algorithm used by svd_lowrank.
        - powm: use power method instead of lowrank SVD, my own experience
            is that it is both slower and less stable.
        - convtr: when True, differentiate between Conv and Transposed Conv.
            this is kept for compatibility with older experiments.
        - proba: probability to apply the penalty.
        - conv_only: only apply to conv and conv transposed, not LSTM
            (might not be reliable for other models than Demucs).
        - exact: use exact SVD (slow but useful at validation).
        - bs: batch_size for power method.
    r   g        F)recursei   )      r   r   r   r   )
compute_uv)penalty_rngrandommodulesnamed_parametersnumel
isinstancer	   nnConvTranspose1dConvTranspose2dr   	transpose
contiguousviewlenr   svdpowmaxr   tr   svd_lowrank)modelmin_sizer   r   powmconvtrproba	conv_onlyexactr   totalr   namepestimatear   r   r   r   r   svd_penalty   s@   

r<   )r   r   )	r   r   r   FTr   FFr   )__doc__r   r	   r   Randomr   r<   r   r   r   r   <module>   s   

