o
    èôjµD  ã                   @   s
  d dl Z d dlZd dlmZ d dlmZmZmZ d dlZd dl	m
Z
 d dl	mZmZ d dlmZmZ ddlmZ ddlmZmZ dd	lmZ dd
lmZ d dlmZmZ defdd„ZG dd„ dej
jƒZG dd„ dej
jƒZ G dd„ dej
jedddddg d¢d�
Z!dS )é    N)ÚPath)ÚOptionalÚUnionÚDict)ÚConv1dÚConvTranspose1d)Úweight_normÚremove_weight_normé   )Úactivations)Úinit_weightsÚget_padding©ÚActivation1d)ÚAttrDict)ÚPyTorchModelHubMixinÚhf_hub_downloadÚreturnc                 C   s>   t | ƒ�}| ¡ }W d   ƒ n1 sw   Y  tt |¡ƒS ©N)ÚopenÚreadr   ÚjsonÚloads)ÚpathÚfÚdata© r   úK/var/www/html/academy/tools/voices/clone/seed-vc/modules/bigvgan/bigvgan.pyÚload_hparams_from_json   s   

ÿr   c                       óN   e Zd ZdZ			ddedededed	ef
‡ fd
d„Zdd„ Z	dd„ Z
‡  ZS )Ú	AMPBlock1a»  
    AMPBlock applies Snake / SnakeBeta activation functions with trainable parameters that control periodicity, defined for each layer.
    AMPBlock1 has additional self.convs2 that contains additional Conv1d layers with a fixed dilation=1 followed by each layer in self.convs1

    Args:
        h (AttrDict): Hyperparameters.
        channels (int): Number of convolution channels.
        kernel_size (int): Size of the convolution kernel. Default is 3.
        dilation (tuple): Dilation rates for the convolutions. Each dilation layer has two convolutions. Default is (1, 3, 5).
        activation (str): Activation function type. Should be either 'snake' or 'snakebeta'. Default is None.
    é   ©r
   r!   é   NÚhÚchannelsÚkernel_sizeÚdilationÚ
activationc                    s
  t ƒ  ¡  ˆ| _t ‡‡fdd„|D ƒ¡| _| j t¡ t ‡‡fdd„tt	|ƒƒD ƒ¡| _
| j
 t¡ t	| jƒt	| j
ƒ | _| j dd¡rOddlm} |‰ nt‰ |dkrit ‡ ‡‡fd	d„t| jƒD ƒ¡| _d S |d
kr�t ‡ ‡‡fdd„t| jƒD ƒ¡| _d S tdƒ‚)Nc                    ó*   g | ]}t tˆ ˆ ˆd |tˆ|ƒd�ƒ‘qS ©r
   )Ústrider'   Úpadding©r   r   r   ©Ú.0Úd©r%   r&   r   r   Ú
<listcomp>9   ó    öúÿÿz&AMPBlock1.__init__.<locals>.<listcomp>c                    s*   g | ]}t tˆ ˆ ˆd d tˆd ƒd�ƒ‘qS r*   r-   ©r/   Ú_r1   r   r   r2   J   r3   Úuse_cuda_kernelFr
   r   Úsnakec                    ó"   g | ]}ˆ t jˆˆjd �d�‘qS ©©Zalpha_logscale©r(   ©r   ÚSnakeÚsnake_logscaler4   ©r   r%   r$   r   r   r2   k   ó    ûÿÿÿÚ	snakebetac                    r8   r9   ©r   Ú	SnakeBetar>   r4   r?   r   r   r2   v   r@   úRactivation incorrectly specified. check the config file and look for 'activation'.)ÚsuperÚ__init__r$   ÚnnÚ
ModuleListÚconvs1Úapplyr   ÚrangeÚlenÚconvs2Ú
num_layersÚgetÚ'alias_free_activation.cuda.activation1dr   ÚTorchActivation1dr   ÚNotImplementedError©Úselfr$   r%   r&   r'   r(   ÚCudaActivation1d©Ú	__class__©r   r%   r$   r&   r   rF   ,   sH   
õÿ
õÿ
ÿú
ÿ
ú
ÿÿzAMPBlock1.__init__c           	      C   sn   | j d d d… | j dd d… }}t| j| j||ƒD ]\}}}}||ƒ}||ƒ}||ƒ}||ƒ}|| }q|S )Né   r
   )r   ÚziprI   rM   )	rT   ÚxZacts1Zacts2Úc1Úc2Úa1Úa2Úxtr   r   r   Úforward„   s   "
zAMPBlock1.forwardc                 C   s,   | j D ]}t|ƒ q| jD ]}t|ƒ qd S r   )rI   r	   rM   ©rT   Úlr   r   r   r	   �   s
   



ÿzAMPBlock1.remove_weight_norm©r!   r"   N©Ú__name__Ú
__module__Ú__qualname__Ú__doc__r   ÚintÚtupleÚstrrF   ra   r	   Ú__classcell__r   r   rV   r   r       s$    úþýüûúXr    c                       r   )Ú	AMPBlock2aˆ  
    AMPBlock applies Snake / SnakeBeta activation functions with trainable parameters that control periodicity, defined for each layer.
    Unlike AMPBlock1, AMPBlock2 does not contain extra Conv1d layers with fixed dilation=1

    Args:
        h (AttrDict): Hyperparameters.
        channels (int): Number of convolution channels.
        kernel_size (int): Size of the convolution kernel. Default is 3.
        dilation (tuple): Dilation rates for the convolutions. Each dilation layer has two convolutions. Default is (1, 3, 5).
        activation (str): Activation function type. Should be either 'snake' or 'snakebeta'. Default is None.
    r!   r"   Nr$   r%   r&   r'   r(   c                    sÐ   t ƒ  ¡  ˆ| _t ‡‡fdd„|D ƒ¡| _| j t¡ t| jƒ| _	| j 
dd¡r2ddlm} |‰ nt‰ |dkrLt ‡ ‡‡fdd„t| j	ƒD ƒ¡| _d S |d	krdt ‡ ‡‡fd
d„t| j	ƒD ƒ¡| _d S tdƒ‚)Nc                    r)   r*   r-   r.   r1   r   r   r2   °   r3   z&AMPBlock2.__init__.<locals>.<listcomp>r6   Fr
   r   r7   c                    r8   r9   r<   r4   r?   r   r   r2   Ï   r@   rA   c                    r8   r9   rB   r4   r?   r   r   r2   Ú   r@   rD   )rE   rF   r$   rG   rH   ÚconvsrJ   r   rL   rN   rO   rP   r   rQ   rK   r   rR   rS   rV   rX   r   rF   £   s8   
õÿú
ÿ
ú
ÿÿzAMPBlock2.__init__c                 C   s4   t | j| jƒD ]\}}||ƒ}||ƒ}|| }qd S r   )rZ   ro   r   )rT   r[   ÚcÚar`   r   r   r   ra   è   s
   
ýzAMPBlock2.forwardc                 C   s   | j D ]}t|ƒ qd S r   )ro   r	   rb   r   r   r   r	   î   s   

ÿzAMPBlock2.remove_weight_normrd   re   r   r   rV   r   rn   –   s$    úþýüûúErn   c                       s    e Zd ZdZddedef‡ fdd„Zdd„ Zd	d
„ Zde	ddfdd„Z
eddddœdededededee dededeeedf dededefdd„ƒZ‡  ZS )ÚBigVGANaÃ  
    BigVGAN is a neural vocoder model that applies anti-aliased periodic activation for residual blocks (resblocks).
    New in BigVGAN-v2: it can optionally use optimized CUDA kernels for AMP (anti-aliased multi-periodicity) blocks.

    Args:
        h (AttrDict): Hyperparameters.
        use_cuda_kernel (bool): If set to True, loads optimized CUDA kernels for AMP. This should be used for inference only, as training is not supported with CUDA kernels.

    Note:
        - The `use_cuda_kernel` parameter should be used for inference only, as training with CUDA kernels is not supported.
        - Ensure that the activation function is correctly specified in the hyperparameters (h.activation).
    Fr$   r6   c                    s@  t ƒ  ¡  || _|| jd< | j dd¡rddlm} |}nt}t|jƒ| _	t|j
ƒ| _tt|j|jdddd�ƒ| _|jdkrAt}n|jd	krIt}ntd
|j› �ƒ‚t ¡ | _tt|j
|jƒƒD ])\}\}}| j t tt|jd|  |jd|d   |||| d d�ƒg¡¡ q_t ¡ | _tt| jƒƒD ])}|jd|d   }	tt|j|jƒƒD ]\}
\}}| j |||	|||j d�¡ q©q•|j dkrÌt!j"|	|j#d�n|j dkrÙt!j$|	|j#d�nd }|d u rãt%dƒ‚||d�| _&| dd¡| _'tt|	dddd| j'd�ƒ| _(tt| jƒƒD ]}| j|  )t*¡ �q| j( )t*¡ | dd¡| _+d S )Nr6   Fr
   r   é   r!   )r,   Ú1Ú2z;Incorrect resblock class specified in hyperparameters. Got rY   r;   r7   r:   rA   rD   Úuse_bias_at_finalT)r,   ÚbiasÚuse_tanh_at_final),rE   rF   r$   rO   rP   r   rQ   rL   Zresblock_kernel_sizesÚnum_kernelsZupsample_ratesÚnum_upsamplesr   r   Únum_melsZupsample_initial_channelÚconv_preZresblockr    rn   Ú
ValueErrorrG   rH   ÚupsÚ	enumeraterZ   Zupsample_kernel_sizesÚappendr   Ú	resblocksrK   Zresblock_dilation_sizesr(   r   r=   r>   rC   rR   Úactivation_postrv   Ú	conv_postrJ   r   rx   )rT   r$   r6   rU   r   Zresblock_classÚiÚuÚkÚchÚjr0   r‚   rV   r   r   rF   
  s€   

ÿ


ÿ

ûÿÿÿÿ
ÿÿý

ÿ
ÿú	ÿÿzBigVGAN.__init__c                 C   sÜ   |   |¡}t| jƒD ]E}tt| j| ƒƒD ]}| j| | |ƒ}qd }t| jƒD ]!}|d u r;| j|| j |  |ƒ}q(|| j|| j |  |ƒ7 }q(|| j }q
|  |¡}|  |¡}| j	rdt
 |¡}|S t
j|ddd�}|S )Ng      ð¿g      ð?)ÚminÚmax)r|   rK   rz   rL   r~   ry   r�   r‚   rƒ   rx   ÚtorchÚtanhÚclamp)rT   r[   r„   Zi_upÚxsrˆ   r   r   r   ra   h  s"   



þzBigVGAN.forwardc                 C   sr   z*t dƒ | jD ]}|D ]}t|ƒ qq| jD ]}| ¡  qt| jƒ t| jƒ W d S  ty8   t dƒ Y d S w )NzRemoving weight norm...z3[INFO] Model already removed weight norm. Skipping!)Úprintr~   r	   r�   r|   rƒ   r}   )rT   rc   Zl_ir   r   r   r	   „  s   

ÿ


þzBigVGAN.remove_weight_normÚsave_directoryr   Nc                 C   sf   |d }t  d|  ¡ i|¡ |d }t|dƒ�}tj| j|dd� W d  ƒ dS 1 s,w   Y  dS )zGSave weights and config.json from a Pytorch model to a local directory.úbigvgan_generator.ptÚ	generatorúconfig.jsonÚwé   )ÚindentN)r‹   ÚsaveÚ
state_dictr   r   Údumpr$   )rT   r�   Ú
model_pathÚconfig_pathÚconfig_filer   r   r   Ú_save_pretrained“  s   "ÿzBigVGAN._save_pretrainedÚcpu)Úmap_locationÚstrictr6   Úmodel_idÚrevisionÚ	cache_dirÚforce_downloadÚproxiesÚresume_downloadÚlocal_files_onlyÚtokenrŸ   r    c                K   s  t j |¡rtdƒ t j |d¡}nt|d|||||||d�	}t|ƒ}|r1tdƒ tdƒ tdƒ | ||d�}t j |¡rItdƒ t j |d	¡}ntd
|› �ƒ t|d	|||||||d�	}tj||	d�}z
| 	|d ¡ W |S  t
y‡   tdƒ | ¡  | 	|d ¡ Y |S w )z<Load Pytorch pretrained weights and return the loaded model.z(Loading config.json from local directoryr“   )	Úrepo_idÚfilenamer¢   r£   r¤   r¥   r¦   r¨   r§   zŽ[WARNING] You have specified use_cuda_kernel=True during BigVGAN.from_pretrained(). Only inference is supported (training is not implemented)!zÂ[WARNING] You need nvcc and ninja installed in your system that matches your PyTorch build is using to build the kernel. If not, the model will fail to initialize or generate incorrect waveform!z•[WARNING] For detail, see the official GitHub repository: https://github.com/NVIDIA/BigVGAN?tab=readme-ov-file#using-custom-cuda-kernel-for-synthesis)r6   z$Loading weights from local directoryr‘   zLoading weights from )rŸ   r’   zq[INFO] the pretrained checkpoint does not contain weight norm. Loading the checkpoint after removing weight norm!)Úosr   Úisdirr�   Újoinr   r   r‹   ÚloadÚload_state_dictÚRuntimeErrorr	   )Úclsr¡   r¢   r£   r¤   r¥   r¦   r§   r¨   rŸ   r    r6   Zmodel_kwargsrœ   r$   ÚmodelÚ
model_fileZcheckpoint_dictr   r   r   Ú_from_pretrained�  sj   ÷ÿÿÿ÷ùÿùzBigVGAN._from_pretrained)F)rf   rg   rh   ri   r   ÚboolrF   ra   r	   r   r�   Úclassmethodrl   r   r   r   r´   rm   r   r   rV   r   rr   ó   sB    
^
óýüûúùø	÷
öõôórr   Úbigvganz!https://github.com/NVIDIA/BigVGANz5https://github.com/NVIDIA/BigVGAN/blob/main/README.mdzaudio-to-audioZmit)zneural-vocoderzaudio-generationzarxiv:2206.04658)Úlibrary_nameZrepo_urlZdocs_urlZpipeline_tagÚlicenseÚtags)"r«   r   Úpathlibr   Útypingr   r   r   r‹   Útorch.nnrG   r   r   Ztorch.nn.utilsr   r	   Ú r   Úutilsr   r   Zalias_free_activation.torch.actr   rQ   Úenvr   Úhuggingface_hubr   r   r   ÚModuler    rn   rr   r   r   r   r   Ú<module>   s4   w
]
ø