
    wi                     N   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mZmZmZmZmZmZ d dlZd dl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mZm Z m!Z!m"Z"m#Z#m$Z$m%Z%m&Z&m'Z'm(Z(m)Z)m*Z* d	dl+m,Z,m-Z-m.Z. ddl/m0Z0m1Z1m2Z2m3Z3m4Z4  e*j5        e6          Z7 ej8        d          Z9 e)dd          rdZ:ndZ: e(            rd dl;Z;dej        j<        dej=        fdZ>dej        j<        dej?        fdZ@ G d dej        j<        e,          ZA G d deA          ZBdS )    N)OrderedDict)partial)Path)AnyCallableListOptionalTupleUnion)create_repo"split_torch_state_dict_into_shards)validate_hf_hub_args)Tensornn   )__version__)CONFIG_NAMEFLAX_WEIGHTS_NAMESAFE_WEIGHTS_INDEX_NAMESAFETENSORS_WEIGHTS_NAMEWEIGHTS_INDEX_NAMEWEIGHTS_NAME_add_variant_get_checkpoint_shard_files_get_model_file	deprecateis_accelerate_availableis_torch_versionlogging)PushToHubMixinload_or_create_model_cardpopulate_model_card   )_determine_device_map_fetch_index_file_load_state_dict_into_modelload_model_dict_into_metaload_state_dictz(.*?)-\d{5}-of-\d{5}>=1.9.0TF	parameterreturnc                    	 t          j        |                                 |                                           }t	          |          j        S # t          $ rn dt          j        j	        dt          t          t          t          f                  fd}|                     |          }t	          |          }|d         j        cY S w xY w)Nmoduler,   c                 L    d | j                                         D             }|S )Nc                 D    g | ]\  }}t          j        |          ||fS  torch	is_tensor.0kvs      o/root/.openclaw/workspace/chatterbox_venv_py311/lib/python3.11/site-packages/diffusers/models/modeling_utils.py
<listcomp>zHget_parameter_device.<locals>.find_tensor_attributes.<locals>.<listcomp>V   0    WWWAEOTUDVDVWq!fWWW    __dict__itemsr.   tupless     r9   find_tensor_attributesz4get_parameter_device.<locals>.find_tensor_attributesU   (    WW)>)>)@)@WWWFMr<   get_members_fnr#   )	itertoolschain
parametersbuffersnextdeviceStopIterationr3   r   Moduler   r
   strr   _named_members)r+   parameters_and_buffersrB   genfirst_tuples        r9   get_parameter_devicerS   N   s    %!*1E1E1G1GIZIZI\I\!]!]*++22 	% 	% 	%	58? 	tE#v+DV?W 	 	 	 	 &&6L&MM3ii1~$$$$	%s   AA A5CCc                    	 t          |                                           }t          |          dk    r|d         j        S t          |                                           }t          |          dk    r|d         j        S d S # t
          $ rn dt          j        j        dt          t          t          t          f                  fd}|                     |          }t          |          }|d         j        cY S w xY w)Nr   r.   r,   c                 L    d | j                                         D             }|S )Nc                 D    g | ]\  }}t          j        |          ||fS r1   r2   r5   s      r9   r:   zGget_parameter_dtype.<locals>.find_tensor_attributes.<locals>.<listcomp>l   r;   r<   r=   r@   s     r9   rB   z3get_parameter_dtype.<locals>.find_tensor_attributesk   rC   r<   rD   r#   )tuplerH   lendtyperI   rL   r3   r   rM   r   r
   rN   r   rO   rJ   )r+   paramsrI   rB   rQ   rR   s         r9   get_parameter_dtyper[   ^   s   $y++--..v;;??!9?"	))++,,w<<!1:##   	$ 	$ 	$	58? 	tE#v+DV?W 	 	 	 	 &&6L&MM3ii1~####	$s   A B A B A5C>=C>c                       e Zd ZdZeZg dZdZdZdZ	 fdZ
dedef fdZedefd	            Zd.d
Zd.dZdeddfdZd.dZd.dZ	 d/dedee         ddfdZd/dee         ddfdZd.dZ	 	 	 	 	 	 d0deeej        f         dedee         dedee         deeef         defdZe e!deeeej        f                  fd                        Z"e 	 d1d e#deeej        f         d!efd"            Z$e d#             Z%d$efd%Z&ede'j(        fd&            Z(ede'j)        fd'            Z)d2d(ed)edefd*Z*d e#ddfd+Z+d.d,Z,d.d-Z- xZ.S )3
ModelMixina$  
    Base class for all models.

    [`ModelMixin`] takes care of storing the model configuration and provides methods for loading, downloading and
    saving models.

        - **config_name** ([`str`]) -- Filename to save a model to when calling [`~models.ModelMixin.save_pretrained`].
    )_diffusers_version_class_name_name_or_pathFNc                 H    t                                                       d S N)super__init__)self	__class__s    r9   rd   zModelMixin.__init__   s    r<   namer,   c                 V   d| j         v ot          | j         d         |          }|| j         v }|rY|sWd| dt          |           j         d| dt          |           j         d| d}t	          dd	|d
d           | j        |         S t                                          |          S )a~  The only reason we overwrite `getattr` here is to gracefully deprecate accessing
        config attributes directly. See https://github.com/huggingface/diffusers/pull/3129 We need to overwrite
        __getattr__ here in addition so that we don't trigger `torch.nn.Module`'s __getattr__':
        https://pytorch.org/docs/stable/_modules/torch/nn/modules/module.html#Module
        _internal_dictzAccessing config attribute `z` directly via 'z1' object attribute is deprecated. Please access 'z' over 'z,'s config object instead, e.g. 'unet.config.z'.zdirect config name accessz1.0.0F   )standard_warn
stacklevel)r>   hasattrtype__name__r   ri   rc   __getattr__)re   rg   is_in_configis_attributedeprecation_messagerf   s        r9   rp   zModelMixin.__getattr__   s    (4=8kWT]ScEdfj=k=kt}, 	- 	- #u  #u  #uW[\`WaWaWj  #u  #u  ^b  #u  #u  lp  qu  lv  lv  l  #u  #u  mq  #u  #u  #u17<O_dqrssss&t,, ww""4(((r<   c                 X    t          d |                                 D                       S )zT
        Whether gradient checkpointing is activated for this model or not.
        c              3   D   K   | ]}t          |d           o|j        V  dS )gradient_checkpointingN)rm   rv   )r6   ms     r9   	<genexpr>z7ModelMixin.is_gradient_checkpointing.<locals>.<genexpr>   s6      mmYZ71677TA<Tmmmmmmr<   )anymodulesre   s    r9   is_gradient_checkpointingz$ModelMixin.is_gradient_checkpointing   s.    
 mm^b^j^j^l^lmmmmmmr<   c                     | j         st          | j        j         d          |                     t          | j        d                     dS )z
        Activates gradient checkpointing for the current model (may be referred to as *activation checkpointing* or
        *checkpoint activations* in other frameworks).
        z) does not support gradient checkpointing.TvalueN) _supports_gradient_checkpointing
ValueErrorrf   ro   applyr   _set_gradient_checkpointingr{   s    r9   enable_gradient_checkpointingz(ModelMixin.enable_gradient_checkpointing   sT    
 4 	d 7bbbccc

74;4HHHIIIIIr<   c                 j    | j         r+|                     t          | j        d                     dS dS )z
        Deactivates gradient checkpointing for the current model (may be referred to as *activation checkpointing* or
        *checkpoint activations* in other frameworks).
        Fr~   N)r   r   r   r   r{   s    r9   disable_gradient_checkpointingz)ModelMixin.disable_gradient_checkpointing   sD    
 0 	OJJwt?uMMMNNNNN	O 	Or<   validc                     dt           j        j        ffd|                                 D ],}t	          |t           j        j                  r |           -dS )z=
        Set the switch for the npu flash attention.
        r.   c                     t          | d          r|                                |                                 D ]} |           d S )Nset_use_npu_flash_attention)rm   r   children)r.   child$fn_recursive_set_npu_flash_attentionr   s     r9   r   zTModelMixin.set_use_npu_flash_attention.<locals>.fn_recursive_set_npu_flash_attention   sa    v<== :225999** < <44U;;;;< <r<   Nr3   r   rM   r   
isinstance)re   r   r.   r   s    ` @r9   r   z&ModelMixin.set_use_npu_flash_attention   s}    
	< 	< 	< 	< 	< 	< 	< 	< mmoo 	= 	=F&%(/22 =44V<<<	= 	=r<   c                 0    |                      d           dS )z<
        Enable npu flash attention from torch_npu

        TNr   r{   s    r9   enable_npu_flash_attentionz%ModelMixin.enable_npu_flash_attention   s    
 	((.....r<   c                 0    |                      d           dS )z=
        disable npu flash attention from torch_npu

        FNr   r{   s    r9   disable_npu_flash_attentionz&ModelMixin.disable_npu_flash_attention   s    
 	((/////r<   attention_opc                     dt           j        j        ffd|                                 D ],}t	          |t           j        j                  r |           -d S )Nr.   c                     t          | d          r|                                |                                 D ]} |           d S )N+set_use_memory_efficient_attention_xformers)rm   r   r   )r.   r   r   fn_recursive_set_mem_effr   s     r9   r   zXModelMixin.set_use_memory_efficient_attention_xformers.<locals>.fn_recursive_set_mem_eff   sd    vLMM XBB5,WWW** 0 0((////0 0r<   r   )re   r   r   r.   r   s    `` @r9   r   z6ModelMixin.set_use_memory_efficient_attention_xformers   s    	0UX_ 	0 	0 	0 	0 	0 	0 	0 	0 mmoo 	1 	1F&%(/22 1((000	1 	1r<   c                 2    |                      d|           dS )uE  
        Enable memory efficient attention from [xFormers](https://facebookresearch.github.io/xformers/).

        When this option is enabled, you should observe lower GPU memory usage and a potential speed up during
        inference. Speed up during training is not guaranteed.

        <Tip warning={true}>

        ⚠️ When memory efficient attention and sliced attention are both enabled, memory efficient attention takes
        precedent.

        </Tip>

        Parameters:
            attention_op (`Callable`, *optional*):
                Override the default `None` operator for use as `op` argument to the
                [`memory_efficient_attention()`](https://facebookresearch.github.io/xformers/components/ops.html#xformers.ops.memory_efficient_attention)
                function of xFormers.

        Examples:

        ```py
        >>> import torch
        >>> from diffusers import UNet2DConditionModel
        >>> from xformers.ops import MemoryEfficientAttentionFlashAttentionOp

        >>> model = UNet2DConditionModel.from_pretrained(
        ...     "stabilityai/stable-diffusion-2-1", subfolder="unet", torch_dtype=torch.float16
        ... )
        >>> model = model.to("cuda")
        >>> model.enable_xformers_memory_efficient_attention(attention_op=MemoryEfficientAttentionFlashAttentionOp)
        ```
        TNr   )re   r   s     r9   *enable_xformers_memory_efficient_attentionz5ModelMixin.enable_xformers_memory_efficient_attention   s!    D 	88|LLLLLr<   c                 0    |                      d           dS )zs
        Disable memory efficient attention from [xFormers](https://facebookresearch.github.io/xformers/).
        FNr   r{   s    r9   +disable_xformers_memory_efficient_attentionz6ModelMixin.disable_xformers_memory_efficient_attention  s     	88?????r<   T10GBsave_directoryis_main_processsave_functionsafe_serializationvariantmax_shard_sizepush_to_hubc           	      
    t           j                            |          r t                              d| d           dS |rt
          nt          }	t          |	|          }	|	                    d          }
t          |
          dv r*|
d         dz   d
                    |
dd                   z   }nt          d	|	 d
          t          j        |d           |r|                    dd          }|                    dd          }|                    dd          }|                    dd          }|                    d|                    t           j        j                  d                   }t          |d||          j        }| }|r|                    |           |                                 t'           ||          }|r"t          j        |          D ]}||j                                        v rt           j        
                    ||          }t           j                            |          s_|                    dd                              dd          }|                    dd          }|                    dd                              dd          }|                    |          r.t2                              |          t          j        |           |j                                        D ]o\  }} fd|D             }t           j        
                    ||          }|r%t:          j                            ||ddi           Zt=          j         ||           p|j!        r|j"        |j#        d}|rtH          ntJ          }t           j        
                    |t          ||                    }tM          |dd !          5 }tO          j(        |d"d#          d$z   }|)                    |           ddd           n# 1 swxY w Y   t          *                    d%| d&t          |j                   d'| d           n=t           j        
                    ||	          }t          *                    d(|            |rqtW          ||)          }tY          |          }|                     t[          |d*          .                                           | /                    |||||+           dS dS ),a	  
        Save a model and its configuration file to a directory so that it can be reloaded using the
        [`~models.ModelMixin.from_pretrained`] class method.

        Arguments:
            save_directory (`str` or `os.PathLike`):
                Directory to save a model and its configuration file to. Will be created if it doesn't exist.
            is_main_process (`bool`, *optional*, defaults to `True`):
                Whether the process calling this is the main process or not. Useful during distributed training and you
                need to call this function on all processes. In this case, set `is_main_process=True` only on the main
                process to avoid race conditions.
            save_function (`Callable`):
                The function to use to save the state dictionary. Useful during distributed training when you need to
                replace `torch.save` with another method. Can be configured with the environment variable
                `DIFFUSERS_SAVE_MODE`.
            safe_serialization (`bool`, *optional*, defaults to `True`):
                Whether to save the model using `safetensors` or the traditional PyTorch way with `pickle`.
            variant (`str`, *optional*):
                If specified, weights are saved in the format `pytorch_model.<variant>.bin`.
            max_shard_size (`int` or `str`, defaults to `"10GB"`):
                The maximum size for a checkpoint before being sharded. Checkpoints shard will then be each of size
                lower than this size. If expressed as a string, needs to be digits followed by a unit (like `"5GB"`).
                If expressed as an integer, the unit is bytes. Note that this limit will be decreased after a certain
                period of time (starting from Oct 2024) to allow users to upgrade to the latest version of `diffusers`.
                This is to establish a common default size for this argument across different libraries in the Hugging
                Face ecosystem (`transformers`, and `accelerate`, for example).
            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 fileN.)r   rj   r   z	{suffix}.r#   zInvalid z
 provided.T)exist_okcommit_messageprivateF	create_prtokenrepo_id)r   r   r   )r   filename_patternz.bin z.safetensorsz{suffix}c                 "    i | ]}||         S r1   r1   )r6   tensor
state_dicts     r9   
<dictcomp>z.ModelMixin.save_pretrained.<locals>.<dictcomp>o  s     FFFFVZ/FFFr<   formatpt)metadata)r   
weight_mapwzutf-8)encodingr   )indent	sort_keys
z:The model is bigger than the maximum size per checkpoint (z) and is going to be split in z^ checkpoint shards. You can find where each parameters has been saved in the index located at zModel weights saved in )r   z	README.md)r   r   r   )0ospathisfileloggererrorr   r   r   splitrX   joinr   makedirspopsepr   r   save_configr   r   listdirfilename_to_tensorskeysreplace
startswith_REGEX_SHARD	fullmatchremover?   safetensorsr3   	save_filesave
is_shardedr   tensor_to_filenamer   r   openjsondumpswriteinfor!   r"   r   as_posix_upload_folder)!re   r   r   r   r   r   r   r   kwargsweights_nameweight_name_splitweights_name_patternr   r   r   r   r   model_to_savestate_dict_splitfilenamefull_filenameweights_without_extfilename_without_exttensorsshardfilepathindexsave_index_filefcontentpath_to_weights
model_cardr   s!                                   @r9   save_pretrainedzModelMixin.save_pretrained
  s   X 7>>.)) 	LL^>^^^___F3EW//<#L'::(..s33 !!V++#4Q#7+#EQbcdceceQfHgHg#g  @@@@AAA
NT2222 	`#ZZ(8$??NjjE22G

;66IJJw--EjjN,@,@,M,Mb,QRRG!'D'QVWWW_G   	6%%n555 #--//
 >~H\
 
 

  	-J~66 - -/CHHJJJJ "^X F Fw~~m44 &:&B&B62&N&N&V&VWegi&j&j#&9&A&A*b&Q&Q#'/'7'7'C'C'K'KN\^'_'_$ ''(;<<-$../CDDPIm,,,!1!E!K!K!M!M 	, 	,HgFFFFgFFFEw||NH==H! , !++E8xQUFV+WWWW
5(++++& 	E,5.A E :Lc55QcO gll><Y`;a;abbOosW=== !*U1EEEL   ! ! ! ! ! ! ! ! ! ! ! ! ! ! ! KK7^ 7 7 0 DEE7 7$37 7 7    !gll><HHOKKC/CCDDD 	27%HHHJ,Z88JOOD==FFHHIII-#       	 	s   0PP Ppretrained_model_name_or_pathc                 J  , |                     dd          }|                     dd          }|                     dd          }|                     dd          }|                     dd          }|                     dd          }|                     d	d          }	|                     d
d          }
|                     dd          }|                     dd          }|                     dd          }|                     dd          }|                     dd          }|                     dd          }|                     dd          }|                     dd          }|                     dt                    }|                     dd          }|                     dd          }d}|d}d}|r*t                      sd}t                              d           |t                      st          d          |t          dd          st          d          |du rt          dd          st          d          |du r|t          d| d          t          |t          j
                  rd|i}nt          |t                    r=|d vr9	 dt          j
        |          i}nO# t          $ r t          d!| d"          w xY wt          |t                    r|d#k     rt          d$          d|i}||d}n|st          d%          |r!|t          dd&          st          d'          |}t          d(d)d*} | j        |f|dd||||
||||d+|\  }}}d}d}t           j                            |          }t'          |||pd|||||||
||||,          }||                                rd}|r|rt          d-          d}|rBt+          |t,          |||||
|||||.          } | j        |fi |} d/d0lm}!  |!| |          } n|rt5          ||||||
||||pd1
  
        \  }"}#n|r|s	 t+          |t7          t8          |          |||||
|||||.          }nT# t:          $ rG}$t                              d2| d3|$            |s t                              d4           Y d}$~$nd}$~$ww xY w|0|s.t+          |t7          t>          |          |||||
|||||.          }|rTtA          j!                    5   | j        |fi |} ddd           n# 1 swxY w Y   |?|s<d5}%tE          ||6          }&| #                    |&           tI          | %                                &                                          tI          |&&                                          z
  }'tO          |'          d#k    r,t          d7|  d8| d9d:(                    |'           d;          tS          | |&|%||<          }(| j*        | j*        D ],,fd=|(D             }(tO          |(          d#k    r9t                              d>| j+         d?d:(                    |(          g            ntY          | |||          }	 tA          j-        | |s|n|"|||||dd@	  	         n# t\          $ r}$dAt          |$          v rrt                              dBt          |$           dC| dD           | /                                 tA          j-        | ||||||E           | 0                                 n|$Y d}$~$nd}$~$ww xY wg g g g dF})n[ | j        |fi |} tE          ||6          }&| #                    |&           | 1                    | |&|||G          \  } }'}(}*}+|'|(|*|+dF})|<t          |t          j2                  s"t          | dHtg          |           d"          || 4                    |          } | 5                    |I           | 6                                 |	r| |)fS | S )JuH  
        Instantiate a pretrained PyTorch model from a pretrained model configuration.

        The model is set in evaluation mode - `model.eval()` - by default, and dropout modules are deactivated. To
        train the model, set it back in training mode with `model.train()`.

        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 the model weights saved
                      with [`~ModelMixin.save_pretrained`].

            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.
            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.
            resume_download:
                Deprecated and ignored. All downloads are now resumed by default when possible. Will be removed in v1
                of Diffusers.
            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.
            from_flax (`bool`, *optional*, defaults to `False`):
                Load the model weights from a Flax checkpoint save file.
            subfolder (`str`, *optional*, defaults to `""`):
                The subfolder location of a model file within a larger model repository on the Hub or locally.
            mirror (`str`, *optional*):
                Mirror source to resolve accessibility issues if you're downloading a model in China. We do not
                guarantee the timeliness or safety of the source, and you should refer to the mirror site for more
                information.
            device_map (`str` or `Dict[str, Union[int, str, torch.device]]`, *optional*):
                A map that specifies where each submodule should go. It doesn't need to be defined for each
                parameter/buffer name; once a given module name is inside, every submodule of it will be sent to the
                same device.

                Set `device_map="auto"` to have 🤗 Accelerate automatically compute the most optimized `device_map`. For
                more information about each option see [designing a device
                map](https://hf.co/docs/accelerate/main/en/usage_guides/big_modeling#designing-a-device-map).
            max_memory (`Dict`, *optional*):
                A dictionary device identifier for the maximum memory. Will default to the maximum memory available for
                each GPU and the available CPU RAM if unset.
            offload_folder (`str` or `os.PathLike`, *optional*):
                The path to offload weights if `device_map` contains the value `"disk"`.
            offload_state_dict (`bool`, *optional*):
                If `True`, temporarily offloads the CPU state dict to the hard drive to avoid running out of CPU RAM if
                the weight of the CPU state dict + the biggest shard of the checkpoint does not fit. Defaults to `True`
                when there is some disk offload.
            low_cpu_mem_usage (`bool`, *optional*, defaults to `True` if torch version >= 1.9.0 else `False`):
                Speed up model loading only loading the pretrained weights and not initializing the weights. This also
                tries to not use more than 1x model size in CPU memory (including peak memory) while loading the model.
                Only supported for PyTorch >= 1.9.0. If you are using an older version of PyTorch, setting this
                argument to `True` will raise an error.
            variant (`str`, *optional*):
                Load weights from a specified `variant` filename such as `"fp16"` or `"ema"`. This is ignored when
                loading `from_flax`.
            use_safetensors (`bool`, *optional*, defaults to `None`):
                If set to `None`, the `safetensors` weights are downloaded if they're available **and** if the
                `safetensors` library is installed. If set to `True`, the model is forcibly loaded from `safetensors`
                weights. If set to `False`, `safetensors` weights are not loaded.

        <Tip>

        To use private or [gated models](https://huggingface.co/docs/hub/models-gated#gated-models), log-in with
        `huggingface-cli login`. You can also activate the special
        ["offline-mode"](https://huggingface.co/diffusers/installation.html#offline-mode) to use this method in a
        firewalled environment.

        </Tip>

        Example:

        ```py
        from diffusers import UNet2DConditionModel

        unet = UNet2DConditionModel.from_pretrained("runwayml/stable-diffusion-v1-5", subfolder="unet")
        ```

        If you get the error message below, you need to finetune the weights for your downstream task:

        ```bash
        Some weights of UNet2DConditionModel were not initialized from the model checkpoint at runwayml/stable-diffusion-v1-5 and are newly initialized because the shapes did not match:
        - conv_in.weight: found shape torch.Size([320, 4, 3, 3]) in the checkpoint and torch.Size([320, 9, 3, 3]) in the model instantiated
        You should probably TRAIN this model on a down-stream task to be able to use it for predictions and inference.
        ```
        	cache_dirNignore_mismatched_sizesFforce_download	from_flaxresume_downloadproxiesoutput_loading_infolocal_files_onlyr   revisiontorch_dtype	subfolder
device_map
max_memoryoffload_folderoffload_state_dictlow_cpu_mem_usager   use_safetensorsTa,  Cannot initialize model with low cpu memory usage because `accelerate` was not found in the environment. Defaulting to `low_cpu_mem_usage=False`. It is strongly recommended to install `accelerate` for faster and less memory-intense model loading. You can do so with: 
```
pip install accelerate
```
.zLoading and dispatching requires `accelerate`. Please make sure to install accelerate or set `device_map=None`. You can install accelerate with `pip install accelerate`.r)   r*   ztLoading and dispatching requires torch >= 1.9.0. Please either update your PyTorch version or set `device_map=None`.z~Low memory initialization requires torch >= 1.9.0. Please either update your PyTorch version or set `low_cpu_mem_usage=False`.zEYou cannot set `low_cpu_mem_usage` to `False` while using device_map=zO for loading and dispatching. Please make sure to set `low_cpu_mem_usage=True`.r   )autobalancedbalanced_low_0
sequentialzWhen passing device_map as a string, the value needs to be a device name (e.g. cpu, cuda:0) or 'auto', 'balanced', 'balanced_low_0', 'sequential' but found r   r   znYou can't pass device_map as a negative int. If you want to put the model on the cpu, pass device_map = 'cpu' z>Passing along a `device_map` requires `low_cpu_mem_usage=True`z1.10z=`low_cpu_mem_usage` and `device_map` require PyTorch >= 1.10.modelpytorch	diffusers	file_type	frameworkr   return_unused_kwargsreturn_commit_hashr   r   r   r   r   r   r   
user_agent)is_localr   r   r  r   r   r   r   r   r   r   r   r  commit_hashzFLoading of sharded checkpoints is not supported when `from_flax=True`.)r   r   r   r   r   r   r   r   r   r  r  r#   )%load_flax_checkpoint_in_pytorch_model)r   r   r   r   r   r  r   r   z(An error occurred while trying to fetch : zXDefaulting to unsafe serialization. Pass `allow_pickle=False` to raise an error instead.cpu)r   zCannot load z from z+ because the following keys are missing: 
 z, z. 
 Please make sure to pass `low_cpu_mem_usage=False` and `device_map=None` if you want to randomly initialize those weights or else make sure your checkpoint file is correct.)rK   rY   model_name_or_pathc                 >    g | ]}t          j        |          |S rb   )research)r6   r7   pats     r9   r:   z.ModelMixin.from_pretrained.<locals>.<listcomp>  s,    .g.g.gQRYWZ\]M^M^MfqMfMfMfr<   zESome weights of the model checkpoint were not used when initializing z: 
 )r   r  r  rY   force_hooksstrictz#'Attention' object has no attributezTaking `z@` while using `accelerate.load_checkpoint_and_dispatch` to mean a   was saved with deprecated attention block weight names. We will load it with the deprecated attention block names and convert them on the fly to the new attention block format. Please re-save the model after this conversion, so we don't have to do the on the fly renaming in the future. If the model is from a hub checkpoint, please also re-upload it or open a PR on the original repository.)r   r  r  rY   )missing_keysunexpected_keysmismatched_keys
error_msgs)r   zA needs to be of type `torch.dtype`, e.g. `torch.float16`, but is )r`   )7r   _LOW_CPU_MEM_USAGE_DEFAULTr   r   warningNotImplementedErrorr   r   r   r3   rK   rN   RuntimeErrorintr   load_configr   r   isdirr%   is_filer   r   from_configmodeling_pytorch_flax_utilsr  r   r   r   IOErrorr   r   
accelerateinit_empty_weightsr(   $_convert_deprecated_attention_blockssetr   r   rX   r   r'   "_keys_to_ignore_on_load_unexpectedro   r$   load_checkpoint_and_dispatchAttributeError1_temp_convert_self_to_deprecated_attention_blocks6_undo_temp_convert_self_to_deprecated_attention_blocks_load_pretrained_modelrY   rn   toregister_to_configeval)-clsr   r   r   r   r   r   r   r   r   r   r   r   r   r   r   r   r  r  r  r   r  allow_pickleconfig_pathr  configunused_kwargsr  r   
index_filer  
model_filer	  r  sharded_ckpt_cached_foldersharded_metadataeparam_devicer   r  r   loading_infor!  r"  r  s-                                               @r9   from_pretrainedzModelMixin.from_pretrained  s   V JJ{D11	"(**-F"N"N$4e<<JJ{E22	 **%6==**Y--$jj)>FF!::&8$??

7D))::j$//jj55JJ{D11	ZZd33
ZZd33
$4d;;#ZZ(<eDD"JJ':<VWW**Y-- **%6==""OL 	%<%>%> 	 %NN.   !*A*C*C!%`   !*:4*I*I!%&  
 $$-=dG-L-L$%.  
 %%**@RXb R R R   j%,// 	.j)JJ
C(( 	.Z?s-s-s %,z":":;

    bT^b b b  
 
C(( 	.A~~  E   !*-
! ($(!!& c !abbb 	b%.>tV.L.L% !`aaa 4 % "
 

 .=S_.
!%#)+-!.
 .
 .
 .
*{" 

7==!>??&*Go2+)+-!#
 
 

  !j&8&8&:&:!J 	g) 	gefff 
 {	(-.#- /!1!#%'  J $COF<<m<<E [ZZZZZ99%LLEE %?Z1'#$3%5)%'o2@ @ @<*,<,< !  !05%12JG%T%T"+'5(7 ')9#!)"+#-$/" " "JJ    LL!pLi!p!pmn!p!pqqq' NNr       	 !*!,1!-lG!D!D'#1$3#%5%') +  
 ! n244 E E+COFDDmDDEE E E E E E E E E E E E E E E %j%#(L!0W!M!M!MJ>>zJJJ#&u'7'7'9'9'>'>'@'@#A#AC
HYHYDZDZ#ZL<((1,,(`3 ` `6S ` `,0IIl,C,C` ` `   '@"+)+H' ' 'O =I#&#I h hC.g.g.g.g/.g.g.gOO?++a// Vdgdp  V  Vx|  yB  yB  CR  yS  yS  xT  V  V   "7uj*Va!b!bJ*$"?!.8XJJ>X&'1+9/A"-(,#'
 
 
 
 
 * $ $ $ ACFFJJ"NN!e3q66 !e !e  tQ !e !e !e   "SSUUU&C % * *+5/=3E&1    "XXZZZZ"#G [ZZZZ9$B %'')')"$	    (@@-@@,ZIII
:::FFFTWTnTn1,C Uo U UQ|_oz %1'6'6",	    ":k5;+O+O"uuaefqararuuu   $HH[))E  /L MMM 	

 	',&&sO   J) )K7.Q& &
R70=R22R7TT!$T!=!Z 
\8)B\33\8r   r   c                 <   |                                 }t          |                                          }t          |                                          }|}	t          t          |          t          |          z
            }
t          t          |          t          |          z
            }|}d }| ||||	|          }t	          ||          }t          |          dk    r=d                    |          }d|v r|dz  }t          d|j        j	         d|           t          |          dk    rIt                              d| d	|j        j	         d
| d|j        j	         d|j        j	         d           n(t                              d|j        j	         d           t          |
          dk    r/t                              d|j        j	         d| d|
 d           nKt          |          dk    r8t                              d|j        j	         d| d|j        j	         d           t          |          dk    rMd                    d |D                       }t                              d|j        j	         d| d| d           ||
|||fS )Nc                     g }|rX|D ]U}|}||v rM| |         j         ||         j         k    r1|                    || |         j         ||         j         f           | |= V|S rb   )shapeappend)r   model_state_dictloaded_keysr   r!  checkpoint_key	model_keys          r9   _find_mismatched_keysz@ModelMixin._load_pretrained_model.<locals>._find_mismatched_keysx  s     !O& 7&1 
7 
7N .I "%555&~6<@PQZ@[@aaa'..+Z-G-MO_`iOjOpq   '~6""r<   r   z
	zsize mismatchz_
	You may consider adding `ignore_mismatched_sizes=True` in the model `from_pretrained` method.z#Error(s) in loading state_dict for z:
	z(Some weights of the model checkpoint at z! were not used when initializing r  z,
- This IS expected if you are initializing z from the checkpoint of a model trained on another task or with another architecture (e.g. initializing a BertForSequenceClassification model from a BertForPreTraining model).
- This IS NOT expected if you are initializing z from the checkpoint of a model that you expect to be exactly identical (initializing a BertForSequenceClassification model from a BertForSequenceClassification model).z9All model checkpoint weights were used when initializing z.
zSome weights of z3 were not initialized from the model checkpoint at z and are newly initialized: zo
You should probably TRAIN this model on a down-stream task to be able to use it for predictions and inference.zAll the weights of z/ were initialized from the model checkpoint at zf.
If your task is similar to the task the model of the checkpoint was trained on, you can already use z* for predictions without further training.r   c           	      .    g | ]\  }}}d | d| d| dS )z- z: found shape z in the checkpoint and z in the model instantiatedr1   )r6   keyshape1shape2s       r9   r:   z5ModelMixin._load_pretrained_model.<locals>.<listcomp>  sJ       +VV nmmFmm6mmm  r<   z= and are newly initialized because the shapes did not match:
)r   listr   r1  r&   rX   r   r&  rf   ro   r   r$  r   )r;  r	  r   resolved_archive_filer   r   rL  rM  expected_keysoriginal_loaded_keysr  r   model_to_loadrP  r!  r"  	error_msgmismatched_warnings                     r9   r7  z!ModelMixin._load_pretrained_modela  sm    !++--:??,,---224455*C..[1A1AABBs;//#m2D2DDEE 	# 	# 	#* !33 $'	 O 5]JOOJz??QJ//I)++w	 oU_E]oodmooppp!##NN9;X 9 9!&!99 9=L9 9!&!99 9
 O,9 9 9	 	 	 	 KKqTYTcTlqqqrrr|q  NNn5?#; n n1n nO[n n n   
 !!Q&&KK-eo&> - -1- -CH?C[- - -   !##!% />  " " NNA5?#; A A1A A.A A A   lO_jPPr<   c                 "   t          j        |j                  j        }d |                                D             }t          d |                                D                       }t          |                                          dhz
  }||fS )Nc                 D    i | ]\  }}|j         t          j        k    ||S r1   defaultinspect_emptyr5   s      r9   r   z2ModelMixin._get_signature_keys.<locals>.<dictcomp>  s.    bbb1aiSZSaFaFaq!FaFaFar<   c                 B    h | ]\  }}|j         t          j        k    |S r1   r^  r5   s      r9   	<setcomp>z1ModelMixin._get_signature_keys.<locals>.<setcomp>  s,    "c"c"cAqyT[TbGbGb1GbGbGbr<   re   )r`  	signaturerd   rH   r?   r1  r   )r;  objrH   required_parametersoptional_parametersexpected_moduless         r9   _get_signature_keyszModelMixin._get_signature_keys  s    &s|44?
bb
0@0@0B0Bbbb!"c"c1A1A1C1C"c"c"cdd27799::fXE!444r<   r   c                    t                      }| g}t          |          dk    r|                    d          }|j        j        |vrvt          |t                    r=|j        t          |j        j         d| d          |t          |j                  z  }|t          |
                                          z  }t          |          dk    t          |          S )a  
        Get the modules of the model that should not be spit when using device_map. We iterate through the modules to
        get the underlying `_no_split_modules`.

        Args:
            device_map (`str`):
                The device map value. Options are ["auto", "balanced", "balanced_low_0", "sequential"]

        Returns:
            `List[str]`: List of modules that should not be split
        r   r   Nz does not support `device_map='z_'`. To implement support, the model class needs to implement the `_no_split_modules` attribute.)r1  rX   r   rf   ro   r   r]   _no_split_modulesr   rU  r   )re   r   rk  modules_to_checkr.   s        r9   _get_no_split_modulesz ModelMixin._get_no_split_modules  s     EE 6"##a''%))"--F(0AAAfj11 ^/7(%/8 Z ZYc Z Z Z  
 ->FD\@]@],]) D):):$;$;;  "##a'' %&&&r<   c                      t          |           S )z
        `torch.device`: The device on which the module is (assuming that all the module parameters are on the same
        device).
        )rS   r{   s    r9   rK   zModelMixin.device  s     $D)))r<   c                      t          |           S )zw
        `torch.dtype`: The dtype of the module (assuming that all the module parameters have the same dtype).
        )r[   r{   s    r9   rY   zModelMixin.dtype  s    
 #4(((r<   only_trainableexclude_embeddingsc                    |rYd |                                  D             fd|                                 D             }t          fd|D                       S t          fd|                                 D                       S )a  
        Get number of (trainable or non-embedding) parameters in the module.

        Args:
            only_trainable (`bool`, *optional*, defaults to `False`):
                Whether or not to return only the number of trainable parameters.
            exclude_embeddings (`bool`, *optional*, defaults to `False`):
                Whether or not to return only the number of non-embedding parameters.

        Returns:
            `int`: The number of parameters.

        Example:

        ```py
        from diffusers import UNet2DConditionModel

        model_id = "runwayml/stable-diffusion-v1-5"
        unet = UNet2DConditionModel.from_pretrained(model_id, subfolder="unet")
        unet.num_parameters(only_trainable=True)
        859520964
        ```
        c                 \    g | ])\  }}t          |t          j        j                  $| d *S )z.weight)r   r3   r   	Embedding)r6   rg   module_types      r9   r:   z-ModelMixin.num_parameters.<locals>.<listcomp>  sJ     % % %%D+k58+=>>%   % % %r<   c                 "    g | ]\  }}|v	|S r1   r1   )r6   rg   r+   embedding_param_namess      r9   r:   z-ModelMixin.num_parameters.<locals>.<listcomp>  s/     ( ( (-dIDXmLmLm	LmLmLmr<   c              3   R   K   | ]!}|j         s|                                V  "d S rb   requires_gradnumelr6   prp  s     r9   rx   z,ModelMixin.num_parameters.<locals>.<genexpr>!  s8      llQaol]klqwwyyllllllr<   c              3   R   K   | ]!}|j         s|                                V  "d S rb   ry  r|  s     r9   rx   z,ModelMixin.num_parameters.<locals>.<genexpr>#  s8      eeQqeVdeqwwyyeeeeeer<   )named_modulesnamed_parameterssumrH   )re   rp  rq  non_embedding_parametersrw  s    `  @r9   num_parameterszModelMixin.num_parameters  s    2  	f% %)-););)=)=% % %!
( ( ( (151F1F1H1H( ( ($ llll*Blllllleeee$//*;*;eeeeeer<   c                    g fd d|            D ]+}| d|v r|                     | d          || d<   | d|v r|                     | d          || d<   | d|v r|                     | d          || d<   | d	|v r|                     | d	          || d
<   | d|v r|                     | d          || d<   | d|v r|                     | d          || d<   | d|v r|                     | d          || d<   | d|v r|                     | d          || d<   -d S )Nc                     t          |d          r|j        r                    |            |                                D ] \  }}| dk    r|n|  d| } ||           !d S )N_from_deprecated_attn_blockr   r   )rm   r  rK  named_children)rg   r.   sub_name
sub_module deprecated_attention_block_pathsrecursive_find_attn_blocks       r9   r  zRModelMixin._convert_deprecated_attention_blocks.<locals>.recursive_find_attn_block(  s    v<== >&Bd >077===(.(=(=(?(? @ @$*'+rzz88$7K7K7K7K))(J????@ @r<   r   z.query.weightz.to_q.weightz.query.biasz
.to_q.biasz.key.weightz.to_k.weightz	.key.biasz
.to_k.biasz.value.weightz.to_v.weightz.value.biasz
.to_v.biasz.proj_attn.weightz.to_out.0.weightz.proj_attn.biasz.to_out.0.bias)r   )re   r   r   r  r  s      @@r9   r0  z/ModelMixin._convert_deprecated_attention_blocks%  sK   +-(	@ 	@ 	@ 	@ 	@ 	@ 	"!"d+++ 5 	_ 	_D %%%334>NNdCYCYCY4Z4Z
d0001###z112<..DAUAUAU2V2V
d.../ ###z114>NNdCWCWCW4X4X
d0001!!!Z//2<..DASASAS2T2T
d.../ %%%334>NNdCYCYCY4Z4Z
d0001###z112<..DAUAUAU2V2V
d.../ )))Z778B$GaGaGa8b8b
d4445''':556@nnE]E]E]6^6^
d22233	_ 	_r<   c                     g fd |            D ]@}|j         |_        |j        |_        |j        |_        |j        d         |_        |` |`|`|`Ad S )Nc                     t          | d          r| j        r                    |            |                                 D ]} |           d S Nr  rm   r  rK  r   r.   r  "deprecated_attention_block_modulesr  s     r9   r  z_ModelMixin._temp_convert_self_to_deprecated_attention_blocks.<locals>.recursive_find_attn_blockT  m    v<== B&Bd B299&AAA$oo// 6 6
))*55556 6r<   r   )to_qqueryto_krR  to_vr   to_out	proj_attnre   r.   r  r  s     @@r9   r5  z<ModelMixin._temp_convert_self_to_deprecated_attention_blocksQ  s    -/*	6 	6 	6 	6 	6 	6 	"!$'''8 	 	F!;FLFJ!;FL%}Q/F 	 	r<   c                    g dfd |            D ]e}|j         |_        |j        |_        |j        |_        t          j        |j        t          j	        |j
                  g          |_        |` |`|`|`fd S )Nr,   c                     t          | d          r| j        r                    |            |                                 D ]} |           d S r  r  r  s     r9   r  zdModelMixin._undo_temp_convert_self_to_deprecated_attention_blocks.<locals>.recursive_find_attn_blocko  r  r<   r,   N)r  r  rR  r  r   r  r   
ModuleListr  Dropoutdropoutr  r  s     @@r9   r6  zAModelMixin._undo_temp_convert_self_to_deprecated_attention_blocksl  s    -/*	6 	6 	6 	6 	6 	6 	6 	"!$'''8 		! 		!F ,FK *FK ,FKM6+;RZ=W=W*XYYFM
  		! 		!r<   r  rb   )TNTNr   F)F)FF)/ro   
__module____qualname____doc__r   config_name_automatically_saved_argsr   r2  rk  rd   rN   r   rp   propertyboolr|   r   r   r   r   r   r	   r   r   r   r   r   r   PathLiker'  r   classmethodr   rG  r   r7  ri  rm  r3   rK   rY   r  r0  r5  r6  __classcell__)rf   s   @r9   r]   r]   t   s         K V V V',$)-&    ) ) ) ) ) ) ) )$ n4 n n n XnJ J J JO O O O= =$ = = = = / / / /0 0 0 0 ?C1 11)1();1	1 1 1 1""M "MxPXGY "Mei "M "M "M "MH@ @ @ @ !%,0#'!%*0!N Nc2;./N N  )	N
 !N #N c3hN N N N N` CHU3PRP[K[E\<] C C C  [CJ  ).eQ eQ  eQ
 (-S"+-='>eQ "&eQ eQ eQ [eQN 5 5 [5' ' ' ' ': * * * * X* )u{ ) ) ) X)$f $fT $ft $f`c $f $f $f $fL*_{ *_t *_ *_ *_ *_X   6! ! ! ! ! ! ! !r<   r]   c                   d    e Zd ZdZeedeeee	j
        f                  fd                        ZdS )LegacyModelMixinz
    A subclass of `ModelMixin` to resolve class mapping from legacy classes (like `Transformer2DModel`) to more
    pipeline-specific classes (like `DiTTransformer2DModel`).
    r   c                     ddl m} |                                }|                    dd           }|                    dd          }|                    dd           }|                    dd           }|                    dd           }	|                    d	d           }
|                    d
d           }|                    dd           }|}t          ddd} | j        |f|dd||||	|
|||d|\  }}} |||           } |j        |fi |S )Nr#   )_fetch_remapped_cls_from_configr   r   Fr   r   r   r   r   r   r	  r
  r  Tr  )model_loading_utilsr  copyr   r   r(  rG  )r;  r   r   r  kwargs_copyr   r   r   r   r   r   r   r   r=  r  r>  _remapped_classs                     r9   rG  z LegacyModelMixin.from_pretrained  sc    	IHHHHH kkmmJJ{D11	$4e<< **%6==**Y--!::&8$??

7D))::j$//JJ{D11	 4 % "
 

 's
!%#)+-!
 
 
 
1  98EE-~-.K[[{[[[r<   N)ro   r  r  r  r  r   r	   r   rN   r   r  rG  r1   r<   r9   r  r    sj         
 ,\HU3PRP[K[E\<] ,\ ,\ ,\  [,\ ,\ ,\r<   r  )Cr`  rF   r   r   r  collectionsr   	functoolsr   pathlibr   typingr   r   r   r	   r
   r   r   r3   huggingface_hubr   r   huggingface_hub.utilsr   r   r   r   r   utilsr   r   r   r   r   r   r   r   r   r   r   r   r   utils.hub_utilsr    r!   r"   r  r$   r%   r&   r'   r(   
get_loggerro   r   compiler   r#  r.  rM   rK   rS   rY   r[   r]   r  r1   r<   r9   <module>r     sF  "       				 				 # # # # # #             > > > > > > > > > > > > > > > >      K K K K K K K K 6 6 6 6 6 6                                                    
              
	H	%	%rz122 D'"" '!%!&  %EHO % % % % % $58? $u{ $ $ $ $,M! M! M! M! M!. M! M! M!` 4\ 4\ 4\ 4\ 4\z 4\ 4\ 4\ 4\ 4\r<   