
    wiA                        d dl mZ d dlmZmZmZmZ d dlZd dlm	c m
Z d dlmZ d dlmZ ddlmZmZ ddlmZmZmZmZmZmZ d	d
lmZ  e            rd dlmZmZ ddlm Z m!Z!m"Z"m#Z#  ej$        e%          Z& G d d          Z'dS )    )Path)DictListOptionalUnionN)validate_hf_hub_args)	safe_open   )_LOW_CPU_MEM_USAGE_DEFAULTload_state_dict)USE_PEFT_BACKEND_get_model_fileis_accelerate_availableis_torch_versionis_transformers_availablelogging   )_maybe_expand_lora_scales)CLIPImageProcessorCLIPVisionModelWithProjection)AttnProcessorAttnProcessor2_0IPAdapterAttnProcessorIPAdapterAttnProcessor2_0c                       e Zd ZdZe	 ddeeee         eee	j
        f         f         deeee         f         deeee         f         dee         fd            Zd Zd	 Zd
S )IPAdapterMixinzMixin for handling IP Adapters.image_encoder%pretrained_model_name_or_path_or_dict	subfolderweight_nameimage_encoder_folderc                    t          |t                    s|g}t          |t                    s|g}t          |          dk    r|t          |          z  }t          |t                    s|g}t          |          dk    r|t          |          z  }t          |          t          |          k    rt          d          t          |          t          |          k    rt          d          |                    dd          }|                    dd          }|                    dd          }|                    d	d          }	|                    d
d          }
|                    dd          }|                    dd          }|                    dt
                    }|r*t                      sd}t                              d           |du rt          dd          st          d          ddd}g }t          |||          D ]\  }}}t          |t                    st          ||||||	|
||||          }|                    d          ri i d}t          |dd          5 }|                                D ]}|                    d          r3|                    |          |d         |                    dd          <   J|                    d          r2|                    |          |d          |                    dd          <   	 ddd           n# 1 swxY w Y   nt)          |          }n|}t          |                                          }|dd gk    rt          d!          |                    |           t-          | d"          rt/          | d"d          |t          |t                    st                              d#|            |                    d$          d%k    r#t5          ||                                          }n!t5          |                                          }t9          j        |||&                              | j        | j         '          }| !                    |(           n)t          d)          t                              d*           t-          | d+          r5t/          | d+d          $tE                      }| !                    |,           t-          | d-          st/          | | j#                  n| j$        }|%                    ||.           |&                    |          }|i k    rtN          st                              d/           dS t/          |d0i           }|(                                D ]D\  }}d1| |vr6| )                    |d1| 2           | *                    d1| gd3g4           CdS dS )5ac  
        Parameters:
            pretrained_model_name_or_path_or_dict (`str` or `List[str]` or `os.PathLike` or `List[os.PathLike]` or `dict` or `List[dict]`):
                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`].
                    - A [torch state
                      dict](https://pytorch.org/tutorials/beginner/saving_loading_models.html#what-is-a-state-dict).
            subfolder (`str` or `List[str]`):
                The subfolder location of a model file within a larger model repository on the Hub or locally. If a
                list is passed, it should have the same length as `weight_name`.
            weight_name (`str` or `List[str]`):
                The name of the weight file to load. If a list is passed, it should have the same length as
                `weight_name`.
            image_encoder_folder (`str`, *optional*, defaults to `image_encoder`):
                The subfolder location of the image encoder within a larger model repository on the Hub or locally.
                Pass `None` to not load the image encoder. If the image encoder is located in a folder inside
                `subfolder`, you only need to pass the name of the folder that contains image encoder weights, e.g.
                `image_encoder_folder="image_encoder"`. If the image encoder is located in a folder other than
                `subfolder`, you should pass the path to the folder that contains image encoder weights, for example,
                `image_encoder_folder="different_subfolder/image_encoder"`.
            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.
            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.
            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.
            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.
        r   zT`weight_name` and `pretrained_model_name_or_path_or_dict` must have the same length.z8`weight_name` and `subfolder` must have the same length.	cache_dirNforce_downloadFresume_downloadproxieslocal_files_onlytokenrevisionlow_cpu_mem_usagea,  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
```
.Tz>=z1.9.0z~Low memory initialization requires torch >= 1.9.0. Please either update your PyTorch version or set `low_cpu_mem_usage=False`.attn_procs_weightspytorch)	file_type	framework)
weights_namer#   r$   r%   r&   r'   r(   r)   r   
user_agentz.safetensors)
image_proj
ip_adapterptcpu)r.   devicezimage_proj.r1    zip_adapter.r2   zNRequired keys are (`image_proj` and `ip_adapter`) missing from the state dict.r   zloading image_encoder from /r   )r   r*   )dtyper   za`image_encoder` cannot be loaded because `pretrained_model_name_or_path_or_dict` is a state dict.zimage_encoder is not loaded since `image_encoder_folder=None` passed. You will not be able to use `ip_adapter_image` when calling the pipeline with IP-Adapter.Use `ip_adapter_image_embeds` to pass pre-generated image embedding instead.feature_extractorr:   unet)r*   z/PEFT backend is required to load these weights.peft_configfaceid_)adapter_nameg      ?)adapter_weights)+
isinstancelistlen
ValueErrorpopr   r   loggerwarningr   NotImplementedErrorzipdictr   endswithr	   keys
startswith
get_tensorreplacer   appendhasattrgetattrinfocountr   as_posixr   from_pretrainedtor5   r8   register_modulesr   	unet_namer<   _load_ip_adapter_weights_load_ip_adapter_lorasr   itemsload_lora_weightsset_adapters)selfr   r   r    r!   kwargsr#   r$   r%   r&   r'   r(   r)   r*   r0   state_dicts
model_file
state_dictfkeyrL   image_encoder_subfolderr   r:   r<   extra_lorasr=   kloras                                l/root/.openclaw/workspace/chatterbox_venv_py311/lib/python3.11/site-packages/diffusers/loaders/ip_adapter.pyload_ip_adapterzIPAdapterMixin.load_ip_adapter6   s   | +t,, 	(&-K?FF 	\5Z4[1455::4Y\_`k\l\l4l1)T** 	$"Iy>>Q!C$4$44I{s#HIIIIsttt{s9~~--WXXX JJ{D11	$4e<< **%6==**Y--!::&8$??

7D))::j$//"JJ':<VWW 	%<%>%> 	 %NN.   $$-=dG-L-L$%.   ."
 

 MP1;	N
 N
 A	K A	KI1;	 CTJJ C,9!,'#1$3#%5%')  
 ''77 	=02"!E!EJ":eLLL mPQ#$6688 m mC"~~m<< m[\[g[ghk[l[l
< 8]TV9W9W X X!$!>!> m[\[g[ghk[l[l
< 8]TV9W9W X	mm m m m m m m m m m m m m m m "1!<!<JJB

))**Dl333 !qrrrz*** t_-- '$QU2V2V2^'3%&KTRR $iBg$i$ijjj/55c::a??6:9FZ6[6[6d6d6f6f336:;O6P6P6Y6Y6[6[3(E(UA&=.?) ) ) "T[
";;	 &
 --M-JJJJ(   NNg   t011 KgdDWY]6^6^6f$6$8$8!%%8I%JJJ 5<D&4I4IXwtT^,,,ty%%kEV%WWW11+>>"# RPQQQQQ &dM2>>*0022 R RGAt$}}K77..t-A--.PPP))=Q==/C5)QQQ R Rs   0B'L$$L(	+L(	c           	         t          | d          st          | | j                  n| j        }t	          |t
                    s|g}t          ||d          }|j                                        D ]\  }}t	          |t          t          f          rt          |          t          |j                  k    r5t          dt          |           dt          |j                   d          t          |          dk    r|t          |j                  z  }t          |          D ]^\  }}t	          |t                    r:|                                D ]$\  }}	|                    |          r
|	|j        |<   %T||j        |<   _dS )	a  
        Set IP-Adapter scales per-transformer block. Input `scale` could be a single config or a list of configs for
        granular control over each IP-Adapter behavior. A config can be a float or a dictionary.

        Example:

        ```py
        # To use original IP-Adapter
        scale = 1.0
        pipeline.set_ip_adapter_scale(scale)

        # To use style block only
        scale = {
            "up": {"block_0": [0.0, 1.0, 0.0]},
        }
        pipeline.set_ip_adapter_scale(scale)

        # To use style+layout blocks
        scale = {
            "down": {"block_2": [0.0, 1.0]},
            "up": {"block_0": [0.0, 1.0, 0.0]},
        }
        pipeline.set_ip_adapter_scale(scale)

        # To use style and layout from 2 reference images
        scales = [{"down": {"block_2": [0.0, 1.0]}}, {"up": {"block_0": [0.0, 1.0, 0.0]}}]
        pipeline.set_ip_adapter_scale(scales)
        ```
        r<   g        )default_scalezCannot assign z scale_configs to z IP-Adapter.r   N)rQ   rR   rY   r<   rA   rB   r   attn_processorsr\   r   r   rC   scalerD   	enumeraterJ   rM   )
r_   ro   r<   scale_configs	attn_nameattn_processoriscale_configrh   ss
             rj   set_ip_adapter_scalez#IPAdapterMixin.set_ip_adapter_scale   s   < 5<D&4I4IXwtT^,,,ty%&& 	GE1$SQQQ)-)=)C)C)E)E 	? 	?%I~.+AC\*]^^ ?}%%^-A)B)BBB$C]);); C C~344C C C   ''1,,$1C8L4M4M$MM'0'?'? ? ?OA|!,55 ?$0$6$6$8$8 < <DAq(33A66 <:; 4Q 7< 3?,Q//	? 	?    c                    t          | d          r0t          | dd          d| _        |                     ddg           t          | d          s@t          | d          r0t          | dd          d| _        |                     ddg           d| j        _        d| j        _        i }| j        j	        
                                D ]k\  }}t          t          d          rt                      nt                      }t          |t          t           f          r|n|                                ||<   l| j                            |           dS )z
        Unloads the IP Adapter weights

        Examples:

        ```python
        >>> # Assuming `pipeline` is already loaded with the IP Adapter weights.
        >>> pipeline.unload_ip_adapter()
        >>> ...
        ```
        r   Nr9   safety_checkerr:   r;   scaled_dot_product_attention)rQ   rR   r   register_to_configr:   r<   encoder_hid_projconfigencoder_hid_dim_typern   r\   Fr   r   rA   r   r   	__class__set_attn_processor)r_   
attn_procsnamevalueattn_processor_classs        rj   unload_ip_adapterz IPAdapterMixin.unload_ip_adapter,  sp    4)) 	@gdOT.R.R.^!%D##4,#??? t-.. 	Ht011 HgdDWY]6^6^6j)-&''4,'GGG &*	"+/( 
94::<< 	 	KD%&-a1O&P&Pe """VcVeVe !
 e&<>W%XYY'$$__&& t
 		$$Z00000rx   Nr9   )__name__
__module____qualname____doc__r   r   strr   r   torchTensorr   rk   rw   r    rx   rj   r   r   3   s        )) />R R/4S$s)T#u|J[E\5\/]R d3i(R 3S	>*	R
 'smR R R RB2? 2? 2?h'1 '1 '1 '1 '1rx   r   )(pathlibr   typingr   r   r   r   r   torch.nn.functionalnn
functionalr   huggingface_hub.utilsr   safetensorsr	   models.modeling_utilsr   r   utilsr   r   r   r   r   r   unet_loader_utilsr   transformersr   r   models.attention_processorr   r   r   r   
get_loggerr   rF   r   r   rx   rj   <module>r      s         . . . . . . . . . . . .           6 6 6 6 6 6 ! ! ! ! ! ! O O O O O O O O                9 8 8 8 8 8         
            
	H	%	%`1 `1 `1 `1 `1 `1 `1 `1 `1 `1rx   