
    wi5                     (   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  ej        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Z d Z! G d d          Z"dS )    N)nullcontext)Optional)validate_hf_hub_args   )	deprecateis_accelerate_availablelogging   )SingleFileComponentErrorconvert_controlnet_checkpoint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SD3Transformer2DModelc                 d    t          j        |           j        }i }|D ]}||v r||         ||<   |S N)inspect	signature
parameters)
mapping_fnkwargsr+   mapping_kwargs	parameters        s/root/.openclaw/workspace/chatterbox_venv_py311/lib/python3.11/site-packages/diffusers/loaders/single_file_model.py_get_mapping_function_kwargsr1   K   sJ    ":..9JN : :	(.y(9N9%    c                   L    e Zd ZdZeeddee         f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           
        !"# | j         }|t          vr<t          dd                    t                                                                                   dd          }|d}t          dd|           |}                    dd          }                    dd          }||t          d	                              d
d          }                    dd          }	                    dd          }
                    dd          }                    dd          }                    dd          }                    dd          }                    dd          }                    dd          }t          |t                    r|}nt          |||	|
||||          }t          |         }|d         }|rcd|v r	|d         }nd}|t          d| d          t          |t                    rt          ||          }t          |fi } |d)||d|}n|r't          |t                    r|}nJt          d          t          |          }|d         }d|v r|d         }|p|                    dd          }|                     |||          }|                     |           \  !"d|v r>|d         }|                                D ]!\  }}|v r                    |          |<   "!"fd D             }|                    |           t          |fi } |d)||d!|}|st'          d"| d#          t)                      rt*          nt,          } |            5  |                     |          }ddd           n# 1 swxY w Y   t)                      r~t1          |||$          } |j        |j        D ]##fd%| D             } t5          |           d&k    r9t6                              d'| j          d(d                    |           g            n|                    |           ||                    |           |                                 |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.
            resume_download (`bool`, *optional*, defaults to `False`):
                Whether or not to resume downloading the model weights and configuration files. If set to `False`, any
                incompletely downloaded files are deleted.
            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)
        ```
        z9FromOriginalModelMixin is currently only compatible with z, pretrained_model_link_or_pathNzUPlease 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resume_downloadforce_downloadFproxiestoken	cache_dirlocal_files_only	subfolderrevisiontorch_dtype)r:   r;   r<   r=   r>   r?   rA   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`)r?   )r9   
checkpointzqInvalid `config` argument. Please provide a string representing a repo idor path to a local Diffusers model repo.pretrained_model_name_or_pathr   )rD   r@   r?   r   c                 L    i | ] }|v s|v 
|                     |          !S  )get).0kexpected_kwargsr-   optional_kwargss     r0   
<dictcomp>z;FromOriginalModelMixin.from_single_file.<locals>.<dictcomp>  s;    mmm_@T@TXY]lXlXlAvzz!}}XlXlXlr2   )r8   rC   zFailed to load zD. Weights for this component appear to be missing in the checkpoint.)dtypec                 >    g | ]}t          j        |          |S r(   )research)rH   rI   pats     r0   
<listcomp>z;FromOriginalModelMixin.from_single_file.<locals>.<listcomp>  s+    &_&_&_QRYsTUEVEVE^qE^E^E^r2   r   zESome weights of the model checkpoint were not used when initializing z: 
 rF   ) __name__SINGLE_FILE_LOADABLE_CLASSES
ValueErrorjoinkeysrG   r   pop
isinstancedictr   strr   r1   r   load_config_get_signature_keysitemsupdater   r   r   r   from_configr   "_keys_to_ignore_on_load_unexpectedlenloggerwarningload_state_dicttoeval)$clsr5   r-   
class_namer7   deprecation_messager8   r9   r:   r;   r<   r=   r>   r?   r@   rA   rB   rC   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_keysrJ   rK   rQ   s$     `                              @@@r0   from_single_filez'FromOriginalModelMixin.from_single_file[   s   z \
999|DIIVrVwVwVyVyLzLz||   )/

3RTX(Y(Y%(4g   5w@STTT4Q1Hd++ **%6==/"= M   !**%6==$4e<<**Y--

7D))JJ{D11	!::&8$??JJ{D11	::j$//jj55;TBB 	>JJ45 /-#!1!	 	 	J 9D 12I J =	8"&777$56I$J!!$(! ( @: @ @ @   /3// l"7Zj"k"k"k$@AR$]$]V\$]$]!%6%6 & /J& &J_& &""  fc** ;A88$G   0
;;7=>]7^4&*;;; 12E FI% * *	 &)__.R#!1 &5 & &"
 03/F/Fs/K/K,O_ "333 1/ B+8+>+>+@+@ A A'J!V++*0**Z*@*@wmmmmmmfmmmL")),777$@AV$a$aZ`$a$a!&;&; '
)j'
 '
D]'
 '
# + 	*r*rrr   %<$=$=N  ;SUU 	< 	<OO$:;;E	< 	< 	< 	< 	< 	< 	< 	< 	< 	< 	< 	< 	< 	< 	< #$$ 	?7?ZbmnnnO7C C ` `C&_&_&_&_/&_&_&_OO?##a'' N\_\h  N  Nptpypy  {J  qK  qK  pL  N  N   !!"=>>>"HH[!!!

s   :NN #N r(   )	rS   
__module____qualname____doc__classmethodr   r   r[   rw   rF   r2   r0   r4   r4   V   sa          J JXc] J J J  [J J Jr2   r4   )#r)   rO   
contextlibr   typingr   huggingface_hub.utilsr   utilsr   r   r	   single_file_utilsr   r   r   r   r   r   r   r   r   r   r   r   
get_loggerrS   rc   
accelerater   models.modeling_utilsr   rT   r1   r4   rF   r2   r0   <module>r      s    				 " " " " " "       6 6 6 6 6 6 ? ? ? ? ? ? ? ? ? ?                             
	H	%	%  B------AAAAAA
 	 !U "=B#}
	  "<A"  "?H 
 "Q* +    8  Q Q Q Q Q Q Q Q Q Qr2   