o
    pi7                  
   @   s$  d dl Z d dlZd dlZd dlmZ d dlmZ d dlmZ ddl	m
Z
mZmZ ddlmZmZmZmZmZmZmZmZmZmZmZmZmZmZ eeZe r\d d	lm Z  dd
l!m"Z" deieedddideeddeededddeideiedddZ#dd Z$dd Z%G dd dZ&dS )    N)nullcontext)Optional)validate_hf_hub_args   )	deprecateis_accelerate_availablelogging   )SingleFileComponentError+convert_animatediff_checkpoint_to_diffusersconvert_controlnet_checkpoint0convert_flux_transformer_checkpoint_to_diffusersconvert_ldm_unet_checkpointconvert_ldm_vae_checkpoint/convert_sd3_transformer_checkpoint_to_diffusers4convert_stable_cascade_unet_single_file_to_diffusers+create_controlnet_diffusers_config_from_ldm%create_unet_diffusers_config_from_ldm$create_vae_diffusers_config_from_ldmfetch_diffusers_configfetch_original_configload_single_file_checkpoint)init_empty_weights)load_model_dict_into_metacheckpoint_mapping_fnunetnum_in_channelsin_channels)r   config_mapping_fndefault_subfolderlegacy_kwargsvae)r   r   r   )r   r   transformer)r   r   )StableCascadeUNetUNet2DConditionModelAutoencoderKLControlNetModelSD3Transformer2DModelMotionAdapterSparseControlNetModelFluxTransformer2DModelc                 C   s>   t tdd }tD ]}t||}t| |r|  S qd S )N.r   )	importlibimport_module__name__splitSINGLE_FILE_LOADABLE_CLASSESgetattr
issubclass)clsdiffusers_moduleloadable_class_strloadable_class r7   a/home/ubuntu/SoloSpeech/.venv/lib/python3.10/site-packages/diffusers/loaders/single_file_model.py'_get_single_file_loadable_mapping_classX   s   

r9   c                 K   s2   t | j}i }|D ]}||v r|| ||< q
|S N)inspect	signature
parameters)
mapping_fnkwargsr=   mapping_kwargs	parameterr7   r7   r8   _get_mapping_function_kwargsc   s   rB   c                   @   s,   e Zd ZdZeeddee fddZdS )FromOriginalModelMixinz]
    Load pretrained weights saved in the `.ckpt` or `.safetensors` format into a model.
    N%pretrained_model_link_or_path_or_dictc           !   	      sl  t | }|du rtddt  dd}|dur(d}tdd| |}dd}dd}|dur@|dur@td	d
d}dd}	dd}
dd}dd}dd}dd}dd}t|t	rx|}nt
|||	|
|||d}t| }|d }|rd|v r|d }nd}|du rtd| dt|trt||d}t|fi }|d+||d|}nd|rt|tr|}ntdt|}|d }d|v r|d }|p|dd}| j|||d}| | \ d|v r|d }| D ]\}}|v r||< q fdd D }|| t|fi }|d+||d!|}|sCtd"| d#t rItnt}|  | |}W d   n	1 s_w   Y  t rpt|||d$}n	|j|dd%\} }|jdur|jD ]fd&d'|D }qt|d(krtd)| j d*d|g  |dur|| |   |S ),a  
        Instantiate a model from pretrained weights saved in the original `.ckpt` or `.safetensors` format. The model
        is set in evaluation mode (`model.eval()`) by default.

        Parameters:
            pretrained_model_link_or_path_or_dict (`str`, *optional*):
                Can be either:
                    - A link to the `.safetensors` or `.ckpt` file (for example
                      `"https://huggingface.co/<repo_id>/blob/main/<path_to_file>.safetensors"`) on the Hub.
                    - A path to a local *file* containing the weights of the component model.
                    - A state dict containing the component model weights.
            config (`str`, *optional*):
                - A string, the *repo id* (for example `CompVis/ldm-text2im-large-256`) of a pretrained pipeline hosted
                  on the Hub.
                - A path to a *directory* (for example `./my_pipeline_directory/`) containing the pipeline component
                  configs in Diffusers format.
            subfolder (`str`, *optional*, defaults to `""`):
                The subfolder location of a model file within a larger model repository on the Hub or locally.
            original_config (`str`, *optional*):
                Dict or path to a yaml file containing the configuration for the model in its original format.
                    If a dict is provided, it will be used to initialize the model configuration.
            torch_dtype (`str` or `torch.dtype`, *optional*):
                Override the default `torch.dtype` and load the model with another dtype. If `"auto"` is passed, the
                dtype is automatically derived from the model's weights.
            force_download (`bool`, *optional*, defaults to `False`):
                Whether or not to force the (re-)download of the model weights and configuration files, overriding the
                cached versions if they exist.
            cache_dir (`Union[str, os.PathLike]`, *optional*):
                Path to a directory where a downloaded pretrained model configuration is cached if the standard cache
                is not used.

            proxies (`Dict[str, str]`, *optional*):
                A dictionary of proxy servers to use by protocol or endpoint, for example, `{'http': 'foo.bar:3128',
                'http://hostname': 'foo.bar:4012'}`. The proxies are used on each request.
            local_files_only (`bool`, *optional*, defaults to `False`):
                Whether to only load local model weights and configuration files or not. If set to True, the model
                won't be downloaded from the Hub.
            token (`str` or *bool*, *optional*):
                The token to use as HTTP bearer authorization for remote files. If `True`, the token generated from
                `diffusers-cli login` (stored in `~/.huggingface`) is used.
            revision (`str`, *optional*, defaults to `"main"`):
                The specific model version to use. It can be a branch name, a tag name, a commit id, or any identifier
                allowed by Git.
            kwargs (remaining dictionary of keyword arguments, *optional*):
                Can be used to overwrite load and saveable variables (for example the pipeline components of the
                specific pipeline class). The overwritten components are directly passed to the pipelines `__init__`
                method. See example below for more information.

        ```py
        >>> from diffusers import StableCascadeUNet

        >>> ckpt_path = "https://huggingface.co/stabilityai/stable-cascade/blob/main/stage_b_lite.safetensors"
        >>> model = StableCascadeUNet.from_single_file(ckpt_path)
        ```
        Nz9FromOriginalModelMixin is currently only compatible with z, pretrained_model_link_or_pathzUPlease use `pretrained_model_link_or_path_or_dict` argument instead for model classesz1.0.0configoriginal_configzz`from_single_file` cannot accept both `config` and `original_config` arguments. Please provide only one of these argumentsforce_downloadFproxiestoken	cache_dirlocal_files_only	subfolderrevisiontorch_dtype)rH   rI   rJ   rK   rL   rN   r   r   z(`original_config` has been provided for z~ but no mapping functionwas found to convert the original config to a Diffusers config in`diffusers.loaders.single_file_utils`)rL   )rG   
checkpointzqInvalid `config` argument. Please provide a string representing a repo idor path to a local Diffusers model repo.pretrained_model_name_or_pathr   )rQ   rM   rL   r    c                    s(   i | ]}| v s|v r| |qS r7   )get.0k)expected_kwargsr?   optional_kwargsr7   r8   
<dictcomp>  s   ( z;FromOriginalModelMixin.from_single_file.<locals>.<dictcomp>)rF   rP   zFailed to load zD. Weights for this component appear to be missing in the checkpoint.)dtype)strictc                    s    g | ]}t  |d u r|qS r:   )researchrS   )patr7   r8   
<listcomp>2  s     z;FromOriginalModelMixin.from_single_file.<locals>.<listcomp>r   zESome weights of the model checkpoint were not used when initializing z: 
 r7   )!r9   
ValueErrorjoinr0   keysrR   r   pop
isinstancedictr   strr   rB   r   load_config_get_signature_keysitemsupdater
   r   r   r   from_configr   load_state_dict"_keys_to_ignore_on_load_unexpectedlenloggerwarningr.   toeval)!r3   rD   r?   mapping_class_namerE   deprecation_messagerF   rG   rH   rI   rJ   rK   rL   rM   rN   rO   rP   mapping_functionsr   r   config_mapping_kwargsdiffusers_model_config$default_pretrained_model_config_namer    
legacy_keynew_keymodel_kwargscheckpoint_mapping_kwargsdiffusers_format_checkpointctxmodelunexpected_keys_r7   )rV   r?   rW   r]   r8   from_single_files   s   ;












z'FromOriginalModelMixin.from_single_filer:   )	r.   
__module____qualname____doc__classmethodr   r   re   r   r7   r7   r7   r8   rC   n   s
    rC   )'r,   r;   r[   
contextlibr   typingr   huggingface_hub.utilsr   utilsr   r   r   single_file_utilsr
   r   r   r   r   r   r   r   r   r   r   r   r   r   
get_loggerr.   rn   
accelerater   models.modeling_utilsr   r0   r9   rB   rC   r7   r7   r7   r8   <module>   sR   @
	&