o
    Gi                     @   s&  d Z ddlZddlZddlZddlZ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ZddlmZmZmZ ddlmZmZmZmZmZ ddlmZ d	d
lmZ d	dlmZm Z m!Z!m"Z"m#Z#m$Z$ e$%e&Z'e(dZ)G dd de	Z*G dd dZ+dd Z,dd Z-G dd de+Z.dS )z%ConfigMixin base class and utilities.    N)OrderedDict)Path)Any)	DDUFEntrycreate_repohf_hub_download)EntryNotFoundErrorHfHubHTTPErrorRepositoryNotFoundErrorRevisionNotFoundErrorvalidate_hf_hub_args)Self   )__version__)HUGGINGFACE_CO_RESOLVE_ENDPOINTDummyObject	deprecateextract_commit_hashhttp_user_agentloggingzconfig\.(.*)\.jsonc                       sT   e Zd Z fddZdd Zdd Zdd Zd	d
 Z fddZ fddZ	  Z
S )
FrozenDictc                    s:   t  j|i | |  D ]
\}}t| || qd| _d S )NT)super__init__itemssetattr_FrozenDict__frozen)selfargskwargskeyvalue	__class__ Q/home/ubuntu/.local/lib/python3.10/site-packages/diffusers/configuration_utils.pyr   9   s   
zFrozenDict.__init__c                 O      t d| jj d)Nz$You cannot use ``__delitem__`` on a 
 instance.	Exceptionr"   __name__r   r   r   r#   r#   r$   __delitem__A      zFrozenDict.__delitem__c                 O   r%   )Nz#You cannot use ``setdefault`` on a r&   r'   r*   r#   r#   r$   
setdefaultD   r,   zFrozenDict.setdefaultc                 O   r%   )NzYou cannot use ``pop`` on a r&   r'   r*   r#   r#   r$   popG   r,   zFrozenDict.popc                 O   r%   )NzYou cannot use ``update`` on a r&   r'   r*   r#   r#   r$   updateJ   r,   zFrozenDict.updatec                    6   t | dr| jrtd| jj dt || d S N__frozenz$You cannot use ``__setattr__`` on a r&   )hasattrr   r(   r"   r)   r   __setattr__r   namer    r!   r#   r$   r4   M      zFrozenDict.__setattr__c                    r0   r1   )r3   r   r(   r"   r)   r   __setitem__r5   r!   r#   r$   r8   R   r7   zFrozenDict.__setitem__)r)   
__module____qualname__r   r+   r-   r.   r/   r4   r8   __classcell__r#   r#   r!   r$   r   8   s    r   c                   @   s  e Zd ZdZdZg ZdZg ZdZe	d,ddZ
dd Zd	ed
efddZd-deejB defddZe		d.deeeef B d
eeeeeef f B fddZe	dd Ze	e		d/deejB d
eeeef eeef f fddZedd Ze	dd Ze	d0deejB deeef dB fdd Zd!d" Z e!d
eeef fd#d$Z"d
efd%d&Z#d'eejB fd(d)Z$e	dedeeef fd*d+Z%dS )1ConfigMixina  
    Base class for all configuration classes. All configuration parameters are stored under `self.config`. Also
    provides the [`~ConfigMixin.from_config`] and [`~ConfigMixin.save_config`] methods for loading, downloading, and
    saving classes that inherit from [`ConfigMixin`].

    Class attributes:
        - **config_name** (`str`) -- A filename under which the config should stored when calling
          [`~ConfigMixin.save_config`] (should be overridden by parent class).
        - **ignore_for_config** (`list[str]`) -- A list of attributes that should not be saved in the config (should be
          overridden by subclass).
        - **has_compatibles** (`bool`) -- Whether the class has compatible classes (should be overridden by subclass).
        - **_deprecated_kwargs** (`list[str]`) -- Keyword arguments that are deprecated. Note that the `init` function
          should only have a `kwargs` argument if at least one argument is deprecated (should be overridden by
          subclass).
    NF	AutoModelc                 C   s"   |dkrt d| d|| _dS )a4  
        Register this class with the given auto class so that it can be loaded with `AutoModel.from_pretrained(...,
        trust_remote_code=True)`.

        When the config is saved, the resulting `config.json` will include an `auto_map` entry mapping the auto class
        to this class's module and class name.

        Args:
            auto_class (`str` or type, *optional*, defaults to `"AutoModel"`):
                The auto class to register this class with. Can be a string (e.g. `"AutoModel"`) or the class itself.
                Currently only `"AutoModel"` is supported.

        Example:

        ```python
        from diffusers import ModelMixin, ConfigMixin


        class MyCustomModel(ModelMixin, ConfigMixin): ...


        MyCustomModel.register_for_auto_class("AutoModel")
        ```
        r=   z$Only 'AutoModel' is supported, got ''.N)
ValueError_auto_class)cls
auto_classr#   r#   r$   register_for_auto_classp   s   
z#ConfigMixin.register_for_auto_classc                 K   st   | j d u rtd| j d|dd  t| ds|}nt| j}i | j|}td| d|  t	|| _d S )NzMake sure that z' has defined a class name `config_name`r   _internal_dictzUpdating config from z to )
config_nameNotImplementedErrorr"   r.   r3   dictrD   loggerdebugr   )r   r   internal_dictprevious_dictr#   r#   r$   register_to_config   s   


zConfigMixin.register_to_configr6   returnc                 C   s   d| j v ot| j d |}|| j v }|r;|s;d| dt| j d| dt| j d| d}tdd	|d
d | j| S tdt| j d| d)aW  The only reason we overwrite `getattr` here is to gracefully deprecate accessing
        config attributes directly. See https://github.com/huggingface/diffusers/pull/3129

        This function is mostly copied from PyTorch's __getattr__ overwrite:
        https://pytorch.org/docs/stable/_modules/torch/nn/modules/module.html#Module
        rD   zAccessing config attribute `z` directly via 'z1' object attribute is deprecated. Please access 'z' over 'z1's config object instead, e.g. 'scheduler.config.r>   zdirect config name access1.0.0Fstandard_warn'z' object has no attribute ')__dict__r3   typer)   r   rD   AttributeError)r   r6   is_in_configis_attributedeprecation_messager#   r#   r$   __getattr__   s   
0
zConfigMixin.__getattr__save_directorypush_to_hubc                 K   s   t j|rtd| dt j|dd t j|| j}| | t	d|  |rm|
dd}|
dd}|
d	d
}|
dd}|
d|t jjd }	t|	d||dj}	|
dd}
| j||	||||
d dS dS )aI  
        Save a configuration object to the directory specified in `save_directory` so that it can be reloaded using the
        [`~ConfigMixin.from_config`] class method.

        Args:
            save_directory (`str` or `os.PathLike`):
                Directory where the configuration JSON file is saved (will be created if it does not exist).
            push_to_hub (`bool`, *optional*, defaults to `False`):
                Whether or not to push your model to the Hugging Face Hub after saving it. You can specify the
                repository you want to push to with `repo_id` (will default to the name of `save_directory` in your
                namespace).
            kwargs (`dict[str, Any]`, *optional*):
                Additional keyword arguments passed along to the [`~utils.PushToHubMixin.push_to_hub`] method.
        zProvided path (z#) should be a directory, not a fileT)exist_okzConfiguration saved in commit_messageNprivate	create_prFtokenrepo_id)r[   r]   r_   	subfolder)r_   r\   r^   rb   )ospathisfileAssertionErrormakedirsjoinrE   to_json_filerH   infor.   splitsepr   r`   _upload_folder)r   rY   rZ   r   output_config_filer\   r]   r^   r_   r`   rb   r#   r#   r$   save_config   s.   

zConfigMixin.save_configconfigc           
      K   s2  d|v r	| d}|du rtdt|tsKd}d| jv r&|d|  d7 }nd| jv r6|d	|  d
|  d7 }tdd|dd | jd|dd|\}}| j|fi |\}}}d|v rb| d|d< | jD ]}||v rr| |||< qe| di |}	d|v r| j|d< |	j	di | i ||}|r|	|fS |	S )a
  
        Instantiate a Python class from a config dictionary.

        Parameters:
            config (`dict[str, Any]`):
                A config dictionary from which the Python class is instantiated. Make sure to only load configuration
                files of compatible classes.
            return_unused_kwargs (`bool`, *optional*, defaults to `False`):
                Whether kwargs that are not consumed by the Python class should be returned or not.
            kwargs (remaining dictionary of keyword arguments, *optional*):
                Can be used to update the configuration object (after it is loaded) and initiate the Python class.
                `**kwargs` are passed directly to the underlying scheduler/model's `__init__` method and eventually
                overwrite the same named arguments in `config`.

        Returns:
            [`ModelMixin`] or [`SchedulerMixin`]:
                A model or scheduler object instantiated from a config dictionary.

        Examples:

        ```python
        >>> from diffusers import DDPMScheduler, DDIMScheduler, PNDMScheduler

        >>> # Download scheduler from huggingface.co and cache.
        >>> scheduler = DDPMScheduler.from_pretrained("google/ddpm-cifar10-32")

        >>> # Instantiate DDIM scheduler class with same config as DDPM
        >>> scheduler = DDIMScheduler.from_config(scheduler.config)

        >>> # Instantiate PNDM scheduler class with same config as DDPM
        >>> scheduler = PNDMScheduler.from_config(scheduler.config)
        ```
        pretrained_model_name_or_pathNzFPlease make sure to provide a config as the first positional argument.zJIt is deprecated to pass a pretrained model name or path to `from_config`.	Schedulerz3If you were trying to load a scheduler, please use z.from_pretrained(...) instead. Otherwise, please make sure to pass a configuration dictionary instead. This functionality will be removed in v1.0.0.Modelz/If you were trying to load a model, please use z.load_config(...) followed by z.from_config(...) instead. Otherwise, please make sure to pass a configuration dictionary instead. This functionality will be removed in v1.0.0.zconfig-passed-as-pathrN   FrO   T)rq   return_unused_kwargsdtype_class_namer#   )
r.   r?   
isinstancerG   r)   r   load_configextract_init_dict_deprecated_kwargsrL   )
rA   rp   rt   r   rW   	init_dictunused_kwargshidden_dictdeprecated_kwargmodelr#   r#   r$   from_config   sB   '






zConfigMixin.from_configc                 O   s,   d|  d}t dd|dd | j|i |S )Nz8 The function get_config_dict is deprecated. Please use zE.load_config instead. This function will be removed in version v1.0.0get_config_dictrN   FrO   )r   rx   )rA   r   r   rW   r#   r#   r$   r   :  s   
zConfigMixin.get_config_dictrq   c                 K   s   | dd}| dd}| dd}| dd}| dd}	| d	d}
| d
d}| dd}| dd}| dd}| di }| dd}i |ddi}t|}t|}| jdu ratd|rr|durktd| ||}ntj|r{|}ntj	|r|durtjtj
||| jrtj
||| j}ntjtj
|| jrtj
|| j}ntd| j d| dzt|| j|||	||
|||||d}W nq ty   t| d ty   t| d| d ty   t| d| j d ty } z
td| d| d}~w ty+   tdt d| d | j d! tyA   td"| d#| d$| j d%w z| j||d&}t|}W n tjtfyb   td'| d(w |sk|sk|S |f}|rv||f7 }|r~||f7 }|S ))a
  
        Load a model or scheduler configuration.

        Parameters:
            pretrained_model_name_or_path (`str` or `os.PathLike`, *optional*):
                Can be either:

                    - A string, the *model id* (for example `google/ddpm-celebahq-256`) of a pretrained model hosted on
                      the Hub.
                    - A path to a *directory* (for example `./my_model_directory`) containing model weights saved with
                      [`~ConfigMixin.save_config`].

            cache_dir (`str | os.PathLike`, *optional*):
                Path to a directory where a downloaded pretrained model configuration is cached if the standard cache
                is not used.
            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.
            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.
            output_loading_info(`bool`, *optional*, defaults to `False`):
                Whether or not to also return a dictionary containing missing keys, unexpected keys and error messages.
            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.
            subfolder (`str`, *optional*, defaults to `""`):
                The subfolder location of a model file within a larger model repository on the Hub or locally.
            return_unused_kwargs (`bool`, *optional*, defaults to `False):
                Whether unused keyword arguments of the config are returned.
            return_commit_hash (`bool`, *optional*, defaults to `False):
                Whether the `commit_hash` of the loaded configuration are returned.

        Returns:
            `dict`:
                A dictionary of all the parameters stored in a JSON configuration file.

        	cache_dirN	local_dirlocal_dir_use_symlinksautoforce_downloadFproxiesr_   local_files_onlyrevisionmirrorrb   
user_agentdduf_entries	file_typerp   z`self.config_name` is not defined. Note that one should not load a config from `ConfigMixin`. Please make sure to define `config_name` in a class inheriting from `ConfigMixin`zDDUF file only allow for 1 level of directory (e.g transformer/model1/model.safetentors is not allowed). Please check the DDUF structurezError no file named z found in directory .)filenamer   r   r   r   r_   r   rb   r   r   r   z is not a local folder and is not a valid model identifier listed on 'https://huggingface.co/models'
If this is a private repository, make sure to pass a token having permission to this repo with `token` or log in with `hf auth login`.z is not a valid git identifier (branch name, tag name or commit id) that exists for this model name. Check the model page at 'https://huggingface.co/z' for available revisions.z& does not appear to have a file named z:There was a specific connection error when trying to load z:
zWe couldn't connect to 'zM' to load this model, couldn't find it in the cached files and it looks like z- is not the path to a directory containing a z file.
Checkout your internet connection or see how to run the library in offline mode at 'https://huggingface.co/docs/diffusers/installation#offline-mode'.zCan't load config for 'z'. If you were trying to load it from 'https://huggingface.co/models', make sure you don't have a local directory with the same name. Otherwise, make sure 'z2' is the correct path to a directory containing a z file)r   z"It looks like the config file at 'z' is not a valid JSON file.)r.   r   strrE   r?   _get_config_file_from_ddufrc   rd   re   isdirrh   EnvironmentErrorr   r
   r   r   r	   r   _dict_from_json_filer   jsonJSONDecodeErrorUnicodeDecodeError)rA   rq   rt   return_commit_hashr   r   r   r   r   r   r_   r   r   _rb   r   r   config_fileerrconfig_dictcommit_hashoutputsr#   r#   r$   rx   C  s   5



zConfigMixin.load_configc                 C   s   t tt| jj S N)setrG   inspect	signaturer   
parameterskeys)input_classr#   r#   r$   _get_init_keys  s   zConfigMixin._get_init_keysc              	      s  | dg fdd| D }t| }| | }|d d|v r*|d t| dr:| jD ]}|| q2t| jdkrH|t	| j }t
tdd }| jr_d	d
 |  D }ng }t	  |D ]}| |}	 |	 qf | |    fdd| D }|d| j}
t|
tr|
| jkrt||
rt||
}| || fdd| D }nt|
tst|
ttfstddd | D }dd | D }i |D ])}||v r||v r||||< ||v r|||< q||v r|||< qt|dkrtd| d| j d| j d t	 }t|| dkr4t||  d i ||}fdd| D }||fS )N_use_default_valuesc                    s&   i | ]\}}| vr|d kr||qS )r   r#   .0kv)used_defaultsr#   r$   
<dictcomp>  s   & z1ConfigMixin.extract_init_dict.<locals>.<dictcomp>r   r   _flax_internal_argsr   r   c                 S   s   g | ]	}t |ts|qS r#   )rw   r   )r   cr#   r#   r$   
<listcomp>      z1ConfigMixin.extract_init_dict.<locals>.<listcomp>c                       i | ]\}}| vr||qS r#   r#   r   )expected_keys_comp_clsr#   r$   r         rv   c                    r   r#   r#   r   )unexpected_keys_from_origr#   r$   r   #  r   z\Make sure that the `_class_name` is of type string or list of string (for custom pipelines).c                 S       i | ]\}}| d s||qS r   
startswithr   r#   r#   r$   r   *       c                 S   s   i | ]\}}|d kr||qS )quantization_configr#   r   r#   r#   r$   r   -  r   zThe config attributes z were passed to z?, but are not expected and will be ignored. Please verify your z configuration file.zG was not found in config. Values will be initialized to default values.c                    r   r#   r#   r   )r{   r#   r$   r   Q  r   )getr   rG   r   remover3   r   lenignore_for_configr   	importlibimport_moduler)   rk   has_compatibles_get_compatiblesunionr.   rw   r   getattrlisttupler?   rH   warningrE   r   rj   )rA   r   r   original_dictexpected_keysargdiffusers_librarycompatible_classesr   expected_keys_corig_cls_nameorig_clsr   passed_keysr|   hidden_config_dictr#   )r   r{   r   r   r$   ry     sx   









zConfigMixin.extract_init_dict	json_filer   c                 C   sR   |r	||   }nt|ddd}| }W d    n1 sw   Y  t|S )Nrutf-8encoding)	read_textopenreadr   loads)rA   r   r   textreaderr#   r#   r$   r   U  s   

z ConfigMixin._dict_from_json_filec                 C   s   | j j d|   S )N )r"   r)   to_json_stringr   r#   r#   r$   __repr__^  s   zConfigMixin.__repr__c                 C   s   | j S )z
        Returns the config of the class as a frozen dictionary

        Returns:
            `dict[str, Any]`: Config of the class.
        )rD   r   r#   r#   r$   rp   a  s   zConfigMixin.configc                    s   t | dr| jni }| jj|d< t|d<  fdd d|v r.t|jts)|j n|j|d<  fdd|	 D }|
d	d
 |
dd
 |
dd
}t| dd
d
urr| jjdd }|di }| d| jj || j< ||d< tj|dddd S )z
        Serializes the configuration instance to a JSON string.

        Returns:
            `str`:
                String containing all the attributes that make up the configuration instance in JSON format.
        rD   rv   _diffusers_versionc                    sn   t | tjr|  } | S t | tr|  } | S t| dr't| jr'|  } | S t | t	r5 fdd| D } | S )Nto_dictc                    s   g | ]} |qS r#   r#   )r   r   to_json_saveabler#   r$   r     s    zHConfigMixin.to_json_string.<locals>.to_json_saveable.<locals>.<listcomp>)
rw   npndarraytolistr   as_posixr3   callabler   r   )r    r   r#   r$   r   w  s   

z4ConfigMixin.to_json_string.<locals>.to_json_saveabler   c                    s   i | ]	\}}| |qS r#   r#   r   r   r#   r$   r     r   z.ConfigMixin.to_json_string.<locals>.<dictcomp>_ignore_filesNr   _pre_quantization_dtyper@   r   ra   auto_map   T)indent	sort_keys
)r3   rD   r"   r)   r   rw   r   rG   r   r   r.   r   r9   rk   r   r@   r   dumps)r   r   r   moduler   r#   r   r$   r   k  s&   
zConfigMixin.to_json_stringjson_file_pathc                 C   sB   t |ddd}||   W d   dS 1 sw   Y  dS )z
        Save the configuration instance's parameters to a JSON file.

        Args:
            json_file_path (`str` or `os.PathLike`):
                Path to the JSON file to save a configuration instance's parameters.
        wr   r   N)r   writer   )r   r   writerr#   r#   r$   ri     s   "zConfigMixin.to_json_filec                 C   sB   |dkr| j nd|| j g}||vrtd| d|  |S )N /z#We did not manage to find the file z4 in the dduf file. We only have the following files )rE   rh   r?   r   )rA   rq   r   r   r#   r#   r$   r     s   z&ConfigMixin._get_config_file_from_dduf)r=   )FNF)FFr   )&r)   r9   r:   __doc__rE   r   r   rz   r@   classmethodrC   rL   r   r   rX   rc   PathLikeboolro   r   rG   r   r   r   r   r   rx   staticmethodr   ry   r   r   r   propertyrp   r   ri   r   r#   r#   r#   r$   r<   X   sX    ,[
 *

b(	- r<   c                    s   t   fdd}|S )a  
    Decorator to apply on the init of classes inheriting from [`ConfigMixin`] so that all the arguments are
    automatically sent to `self.register_for_config`. To ignore a specific argument accepted by the init but that
    shouldn't be registered in the config, use the `ignore_for_config` class variable

    Warning: Once decorated, all private arguments (beginning with an underscore) are trashed and not sent to the init!
    c                    s*  dd |  D dd |  D }t| ts!td| jj dt| dg  i t} fddt	|j
  D }t|| D ]\}}||< qC fdd|  D  tt t d	krxtt t d
< i |t| ddi  | g|R i  d S )Nc                 S   r   r   r   r   r#   r#   r$   r     r   z:register_to_config.<locals>.inner_init.<locals>.<dictcomp>c                 S   s    i | ]\}}| d r||qS r   r   r   r#   r#   r$   r     r   &`@register_for_config` was applied to A init method, but this class does not inherit from `ConfigMixin`.r   c                    s,   i | ]\}\}}|d kr| vr||j qS )r   )default)r   ir6   p)ignorer#   r$   r     s    &c                    s.   i | ]\}}| vr|vr| ||qS r#   )r   )r   r   r  r  init_kwargs
new_kwargsr#   r$   r     s
    r   r   rL   r#   )r   rw   r<   RuntimeErrorr"   r)   r   r   r   	enumerater   zipr   r/   r   r   r   )r   r   r   config_init_kwargsr   r   r   r6   initr  r$   
inner_init  s0   



	z&register_to_config.<locals>.inner_init)	functoolswraps)r  r  r#   r  r$   rL     s   	%rL   c                    s&   | j  t  fdd}|| _ | S )Nc                    s&  t | tstd| jj dt| }t| }i }|D ] }|j	| j
v r'qt|jtjkr5d ||j	< qt| |j	||j	< qi ||}d|v rN|d t|D ]\}}	|| j	}
|	||
< qRtt| t| dkr|tt| t| |d< t| ddi |  | g|R i | d S )Nr  r  ru   r   r   rL   r#   )rw   r<   r
  r"   r)   rG   r   dataclassesfieldsr6   r   rS   r  _MISSING_TYPEr   r.   r  r   r   r   r   )r   r   r   r  r  default_kwargsfieldr	  r  r   r6   original_initr#   r$   r    s.   




z%flax_register_to_config.<locals>.init)r   r  r  )rA   r  r#   r  r$   flax_register_to_config  s
   (r  c                       s8   e Zd ZdZeddeeeef B f fddZ	  Z
S )LegacyConfigMixinz
    A subclass of `ConfigMixin` to resolve class mapping from legacy classes (like `Transformer2DModel`) to more
    pipeline-specific classes (like `DiTTransformer2DModel`).
    NFrp   c                    sL   ddl m} ||| }|| u rtt|j||fi |S |j||fi |S )Nr   )_fetch_remapped_cls_from_config)models.model_loading_utilsr  r   r  r   )rA   rp   rt   r   r  remapped_classr!   r#   r$   r     s
   
zLegacyConfigMixin.from_configr   )r)   r9   r:   r   r   r   rG   r   r   r   r;   r#   r#   r!   r$   r    s    *r  )/r   r  r  r   r   r   rc   recollectionsr   pathlibr   typingr   numpyr   huggingface_hubr   r   r   huggingface_hub.utilsr   r	   r
   r   r   typing_extensionsr   r   r   utilsr   r   r   r   r   r   
get_loggerr)   rH   compile_re_configuration_filer   r<   rL   r  r  r#   r#   r#   r$   <module>   s8    


     ^20