
    bi                     \   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mZmZ d	d
lmZ  e       rd dlmZm Z m!Z!m"Z" ddl#m$Z$m%Z%m&Z&m'Z'm(Z(m)Z)m*Z*  ejV                  e,      Z- G d d      Z. G d d      Z/ G d d      Z0 G d d      Z1y)    )Path)DictListOptionalUnionN)validate_hf_hub_args)	safe_open   )_LOW_CPU_MEM_USAGE_DEFAULTload_state_dict)USE_PEFT_BACKEND_get_detailed_type_get_model_file_is_valid_typeis_accelerate_availableis_torch_versionis_transformers_availablelogging   )_maybe_expand_lora_scales)CLIPImageProcessorCLIPVisionModelWithProjectionSiglipImageProcessorSiglipVisionModel)AttnProcessorAttnProcessor2_0IPAdapterAttnProcessorIPAdapterAttnProcessor2_0IPAdapterXFormersAttnProcessorJointAttnProcessor2_0!SD3IPAdapterJointAttnProcessor2_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y	)IPAdapterMixinMixin for handling IP Adapters.%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        |      k7  rt        d      t        |      t        |      k7  rt        d      |j	                  dd      }|j	                  dd      }|j	                  dd      }|j	                  d	d      }	|j	                  d
d      }
|j	                  dd      }|j	                  dt
              }|r!t               sd}t        j                  d       |du rt        dd      st        d      ddd}g }t        |||      D ]  \  }}}t        |t              st        ||||||	|
|||
      }|j                  d      ri i d}t        |dd      5 }|j!                         D ]t  }|j#                  d      r(|j%                  |      |d   |j'                  dd      <   <|j#                  d      sN|j%                  |      |d   |j'                  dd      <   v 	 ddd       nt)        |      }n|}t        |j!                               }d|vrd|vrt        d       |j+                  |       t-        | d!      rt/        | d!d      |t        |t              st        j1                  d"|        |j3                  d#      d$k(  rt5        ||      j7                         }nt5        |      j7                         }t9        j:                  |||||	| j<                  %      j?                  | j@                        }| jC                  |&       n t        d'      t        j                  d(       t-        | d)      s8t/        | d)d      Gd*}| jD                   | jD                  jF                  jH                  n|}tK        ||+      }| jC                  |,        t-        | d-      st/        | | jL                        n| jN                  }|jQ                  ||.       |jS                  |      }|i k7  rxtT        st        j                  d/       yt/        |d0i       }|jW                         D ];  \  }}d1| |vs| jY                  |d1| 2       | j[                  d1| gd3g4       = yy# 1 sw Y   xY w)5a  
        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
                `subfolder`.
            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.

            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   T`weight_name` and `pretrained_model_name_or_path_or_dict` must have the same length.8`weight_name` and `subfolder` must have the same length.	cache_dirNforce_downloadFproxieslocal_files_onlytokenrevisionlow_cpu_mem_usage,  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
```
.T>=1.9.0~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/   r0   r1   r&   
user_agent.safetensors
image_proj
ip_adapterptcpur;   deviceimage_proj.rA    ip_adapter.rB   NRequired keys are (`image_proj` and `ip_adapter`) missing from the state dict.image_encoderloading image_encoder from /r   r&   r2   r,   r/   torch_dtyperK   a`image_encoder` cannot be loaded because `pretrained_model_name_or_path_or_dict` is a state dict.image_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   size	crop_sizerS   unetr2   /PEFT backend is required to load these weights.peft_configfaceid_adapter_name      ?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dtypetorF   register_modulesrK   config
image_sizer   	unet_namerY   _load_ip_adapter_weights_load_ip_adapter_lorasr   itemsload_lora_weightsset_adapters)selfr%   r&   r'   r(   kwargsr,   r-   r.   r/   r0   r1   r2   r>   state_dicts
model_file
state_dictfkeyrn   image_encoder_subfolderrK   default_clip_sizeclip_image_sizerS   rY   extra_lorasr\   kloras                                 W/home/cdr/jupyterlab/.venv/lib/python3.12/site-packages/diffusers/loaders/ip_adapter.pyload_ip_adapterzIPAdapterMixin.load_ip_adapter9   s"   x +t,&-K?F5Z4[145:4Y\_`k\l4l1)T*"Iy>Q!C$44I{s#HIIstt{s9~-WXX JJ{D1	$4e<**Y-!::&8$?

7D)::j$/"JJ':<VW%<%> %NN. $-=dG-L%. 
 $8iP
MP1;	N
 H	KI1;	 CTJ,9!,'#1#%5%')
 ''702"!EJ":eL mPQ#$668 mC"~~m<[\[g[ghk[l
< 8]TV9W X!$!>[\[g[ghk[l
< 8]TV9W X	mm m "1!<JB

)*D4'L,D !qrrz* t_-'$QU2V2^'3%&KTR&ABgAh$ij/55c:a?6:9FZ6[6d6d6f36:;O6P6Y6Y6[3(E(U(UA&=.?&/-=(,

) "T[[/ & --M-J(  NNg t01gdDWY]6^6f$'!<@<N<N<ZD&&--88`q   %7OWf$g!%%8I%JQH	KV 5<D&4IwtT^^,tyy%%kEV%W11+>"#PQ &dM2>*002 RGAt }K7..tGA3-.P))WQC=/C5)QR {m ms   AS3:)S33S=	c           	         t        | d      st        | | j                        n| j                  }t	        |t
              s|g}t        ||d      }|j                  j                         D ]  \  }}t	        |t        t        t        f      s#t        |      t        |j                        k7  r.t        dt        |       dt        |j                         d      t        |      dk(  r|t        |j                        z  }t        |      D ]^  \  }}t	        |t               r:|j                         D ]&  \  }}	|j#                  |      s|	|j                  |<   ( P||j                  |<   `  y)	  
        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)
        ```
        rY           default_scaleCannot assign  scale_configs to  IP-Adapter.r   N)rs   rt   r~   rY   rc   rd   r   attn_processorsr   r   r   r   re   scalerf   	enumeraterl   ro   )
r   r   rY   scale_configs	attn_nameattn_processoriscale_configr   ss
             r   set_ip_adapter_scalez#IPAdapterMixin.set_ip_adapter_scale   s\   < 5<D&4IwtT^^,tyy%&GE1$SQ)-)=)=)C)C)E 	?%I~!79RTr s }%^-A-A)BB$(]);(<<NsSaSgSgOhNiiuv  '1,$1C8L8L4M$MM'0'? ?OA|!,5$0$6$6$8 <DAq(33A6:; 4 4Q 7< 3?,,Q/?	?    c                 x   t        | d      r(t        | dd      d| _        | j                  ddg       t        | d      s4t        | d      r(t        | dd      d| _        | j                  ddg       d| j
                  _        d| j
                  j                  _        t        | j
                  d      rg| j
                  j                  Q| j
                  j                  | j
                  _        d| j
                  _	        d| j
                  j                  _        i }| j
                  j                  j                         D ]Y  \  }}t        t        d	      r
t               n	t               }t        |t         t"        t$        f      r|n|j'                         ||<   [ | j
                  j)                  |       y)

        Unloads the IP Adapter weights

        Examples:

        ```python
        >>> # Assuming `pipeline` is already loaded with the IP Adapter weights.
        >>> pipeline.unload_ip_adapter()
        >>> ...
        ```
        rK   NrP   safety_checkerrS   rX   text_encoder_hid_proj	text_projscaled_dot_product_attention)rs   rt   rK   register_to_configrS   rY   encoder_hid_projr|   encoder_hid_dim_typer   r   r   Fr   r   rc   r   r   r   	__class__set_attn_processorr   
attn_procsnamevalueattn_processor_classs        r   unload_ip_adapterz IPAdapterMixin.unload_ip_adapter1  s    4)gdOT.R.^!%D##4,#? t-.t01gdDWY]6^6j)-&''4,'G &*		"04		- 49956499;Z;Z;f)-)H)HDII&.2DII+4?DII1 
9944::< 
	KD%&-a1O&P "VcVe !
 24MOmn % __& t	
	 			$$Z0r   NrP   )__name__
__module____qualname____doc__r   r   strr   r   torchTensorr   r   r   r    r   r   r#   r#   6   s    ) />@R/4S$s)T#u||J[E\5\/]@R d3i(@R 3S	>*	@R
 'sm@R @RD3?j/1r   r#   c            
           e Zd ZdZedeeee   eee	j                  f   f   deeee   f   deeee   f   fd       Zd Zd Zy)	ModularIPAdapterMixinr$   r%   r&   r'   c                    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        |      k7  rt        d      t        |      t        |      k7  rt        d      |j	                  dd      }|j	                  dd      }|j	                  dd      }|j	                  d	d      }|j	                  d
d      }	|j	                  dd      }
|j	                  dt
              }|r!t               sd}t        j                  d       |du rt        dd      st        d      ddd}g }t        |||      D ]-  \  }}}t        |t              st        |||||||	|
||
      }|j                  d      ri i d}t        |dd      5 }|j!                         D ]t  }|j#                  d      r(|j%                  |      |d   |j'                  dd      <   <|j#                  d      sN|j%                  |      |d   |j'                  dd      <   v 	 ddd       nt)        |      }n|}t        |j!                               }d|vrd|vrt        d       |j+                  |       0 t-        | d!d"      }t-        | |      }|j/                  ||#       |j1                  |      }|i k7  rxt2        st        j                  d$       yt-        |d%i       }|j5                         D ];  \  }}d&| |vs| j7                  |d&| '       | j9                  d&| gd(g)       = yy# 1 sw Y   xY w)*a  
        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
                `subfolder`.
            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.

            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   r*   r+   r,   Nr-   Fr.   r/   r0   r1   r2   r3   Tr4   r5   r6   r7   r8   r9   r<   r?   r@   rC   rD   rE   rG   rA   rH   rI   rB   rJ   r~   rY   rZ   r[   r\   r]   r^   r`   ra   )rc   rd   re   rf   rg   r   r   rh   ri   r   rj   rk   rl   r   rm   r	   rn   ro   rp   rq   r   rr   rt   r   r   r   r   r   r   )r   r%   r&   r'   r   r,   r-   r.   r/   r0   r1   r2   r>   r   r   r   r   r   rn   r~   rY   r   r\   r   r   s                            r   r   z%ModularIPAdapterMixin.load_ip_adapterf  s   h +t,&-K?F5Z4[145:4Y\_`k\l4l1)T*"Iy>Q!C$44I{s#HIIstt{s9~-WXX JJ{D1	$4e<**Y-!::&8$?

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

 MP1;	N
 !	+I1;	 CTJ,9!,'#1#%5%')
 ''702"!EJ":eL mPQ#$668 mC"~~m<[\[g[ghk[l
< 8]TV9W X!$!>[\[g[ghk[l
< 8]TV9W X	mm m "1!<JB

)*D4'L,D !qrrz*C!	+F D+v6	tY'%%kEV%W11+>"#PQ &dM2>*002 RGAt }K7..tGA3-.P))WQC=/C5)QR -m ms   AM6:)M66N 	c           	         t        | dd      }t        | |      }t        |t              s|g}t        ||d      }|j                  j                         D ]  \  }}t        |t        t        t        f      s#t        |      t        |j                        k7  r.t        dt        |       dt        |j                         d      t        |      dk(  r|t        |j                        z  }t        |      D ]^  \  }}t        |t              r:|j                         D ]&  \  }	}
|j                  |	      s|
|j                  |<   ( P||j                  |<   `  y	)
r   r~   rY   r   r   r   r   r   r   N)rt   rc   rd   r   r   r   r   r   r   re   r   rf   r   rl   ro   )r   r   r~   rY   r   r   r   r   r   r   r   s              r   r   z*ModularIPAdapterMixin.set_ip_adapter_scale  sW   < D+v6	tY'%&GE1$SQ)-)=)=)C)C)E 	?%I~!79RTr s }%^-A-A)BB$(]);(<<NsSaSgSgOhNiiuv  '1,$1C8L8L4M$MM'0'? ?OA|!,5$0$6$6$8 <DAq(33A6:; 4 4Q 7< 3?,,Q/?	?r   c                    | j                   yd| j                   _        d| j                   j                  _        t	        | j                   d      rg| j                   j
                  Q| j                   j
                  | j                   _        d| j                   _        d| j                   j                  _        i }| j                   j                  j                         D ]Y  \  }}t	        t        d      r
t               n	t               }t        |t        t        t        f      r|n|j                         ||<   [ | j                   j!                  |       y)r   Nr   r   r   )rY   r   r|   r   rs   r   r   r   r   r   r   rc   r   r   r   r   r   r   s        r   r   z'ModularIPAdapterMixin.unload_ip_adapter3  s    99%)		"04		- 49956499;Z;Z;f)-)H)HDII&.2DII+4?DII1 
9944::< 
	KD%&-a1O&P "VcVe !
 24MOmn % __& t	
	 			$$Z0r   N)r   r   r   r   r   r   r   r   r   r   r   r   r   r   r   r   r   r   r   c  s    )TR/4S$s)T#u||J[E\5\/]TR d3i(TR 3S	>*	TR TRl4?l'1r   r   c                       e Zd ZdZedddej                  fdeee	e   e
eej                  f   f   deee	e   f   deeee	e   f      dee   dee   d	ej                  fd
       Zdeee	e   e	e	e      f   fdZd Zy)FluxIPAdapterMixinz$Mixin for handling Flux IP Adapters.rH   rK   r%   r'   r&   +image_encoder_pretrained_model_name_or_pathr   image_encoder_dtypec                    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        |      k7  rt        d      t        |      t        |      k7  rt        d      |j	                  dd      }|j	                  dd      }	|j	                  dd      }
|j	                  d	d      }|j	                  d
d      }|j	                  dd      }|j	                  dt
              }|r!t               sd}t        j                  d       |du rt        dd      st        d      ddd}g }t        |||      D ]  \  }}}t        |t              s<t        ||||	|
|||||
      }|j                  d      r	i i d}t        |dd      5 }ddg}ddg}|j!                         D ]  t#        fd|D              r;d j%                  j'                  d       dd       }|j)                        |d!   |<   Rt#        fd"|D              sgd j%                  j'                  d       dd       j+                  d#d$      j+                  d%d&      j+                  d'd(      }|j)                        |d)   |<    	 ddd       nt-        |      }n|}t        |j!                               }|d!d)gk7  rt        d*      |j/                  |       t1        | d+      rt3        | d+d      |t        |t              smt        j5                  d,|        t7        j8                  ||||||-      j;                  | j<                        j?                         }| jA                  |.       n t        d/      t        j                  d0       t1        | d1      sYt3        | d1d      hd2}| jB                   | jB                  jD                  jF                  n|}tI        ||3      }| jA                  |4        | jJ                  jM                  ||5       y# 1 sw Y   xY w)6a  
        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_pretrained_model_name_or_path (`str`, *optional*, defaults to `./image_encoder`):
                Can be either:

                    - A string, the *model id* (for example `openai/clip-vit-large-patch14`) 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.
            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.
            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   r*   r+   r,   Nr-   Fr.   r/   r0   r1   r2   r3   Tr4   r5   r6   r7   r8   r9   r<   r?   r@   rC   rD   rE   zip_adapter_proj_model.rG   zdouble_blocks.rI   c              3   @   K   | ]  }j                  |        y wNro   .0prefixr   s     r   	<genexpr>z5FluxIPAdapterMixin.load_ip_adapter.<locals>.<genexpr>  s     "Xf3>>&#9"X   .rA   c              3   @   K   | ]  }j                  |        y wr   r   r   s     r   r   z5FluxIPAdapterMixin.load_ip_adapter.<locals>.<genexpr>  s     $ZS^^F%;$Zr   ip_adapter_double_stream_k_projto_k_ipip_adapter_double_stream_v_projto_v_ipz
processor.rH   rB   rJ   rK   rL   rN   rP   rQ   rR   rS   rT   rU   rX   rZ   )'rc   rd   re   rf   rg   r   r   rh   ri   r   rj   rk   rl   r   rm   r	   rn   anyjoinsplitrp   rq   r   rr   rs   rt   ru   r   rx   rz   rF   evalr{   rK   r|   r}   r   transformerr   )r   r%   r'   r&   r   r   r   r   r,   r-   r.   r/   r0   r1   r2   r>   r   r   r   r   image_proj_keysip_adapter_keysdiffusers_namern   rK   r   r   rS   r   s                               @r   r   z"FluxIPAdapterMixin.load_ip_adapter`  s   | +t,&-K?F5Z4[145:4Y\_`k\l4l1)T*"Iy>Q!C$44I{s#HIIstt{s9~-WXX JJ{D1	$4e<**Y-!::&8$?

7D)::j$/"JJ':<VW%<%> %NN. $-=dG-L%. 
 $8iP
MP1;	N
 P	KI1;	 CTJ,9!,'#1#%5%')
 ''702"!EJ":eL ]PQ+C]*S+;]*K#$668 ]C""X"XX14#))C.:L1MKL<<X[K\
< 8 H!$$Z/$Z!Z$'HHSYYs^AB-?$@%,W-NPY%Z%,W-NPY%Z%,W\2%>	 !/ LM<<X[K\
< 8 H]] ]  "1!<JB

)*Dl33 !qrrz* t_-'$QU2V2^>J%&KTR&ABmAn$op9II K*A2C*31A,?  R_!TV & --M-J(  NNg t01gdDWY]6^6f$'!<@<N<N<ZD&&--88`q   %7OWf$g!%%8I%JaP	Kf 	11+Qb1cC] ]s   A?Q#A,Q##Q-	r   c           	        	 t         t        t        f   }| j                  j                  j
                  }| j                  j                  j                  	t        ||      rt        |      D cg c]  }| }}nWt        |t        |         r	|dk(  r|g}n;t        |t        t         |t        |   f            st        dt        |       d      t        |      |k7  rt        dt        |       d| d      t!        	fd|D              rV|D ch c]  }t        |t"              st        |        c}	hz
  }t        d	 d	d
j%                  d |D               d      |D cg c]  }t        ||      r|g	z  n| }}t'        | j                  j(                  j+                         g| D ]  ^}}||_         yc c}w c c}w c c}w )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 list.

        `float` is converted to list and repeated for the number of blocks and the number of IP adapters. `List[float]`
        length match the number of blocks, it is repeated for each IP adapter. `List[List[float]]` must match the
        number of IP adapters and each must match the number of blocks.

        Example:

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


        def LinearStrengthModel(start, finish, size):
            return [(start + (finish - start) * (i / (size - 1))) for i in range(size)]


        ip_strengths = LinearStrengthModel(0.3, 0.92, 19)
        pipeline.set_ip_adapter_scale(ip_strengths)
        ```
        r   zUnexpected type z for scale.r   z scales to z IP-Adapters.c              3   \   K   | ]#  }t        |t              st        |      k7   % y wr   )rc   rd   re   )r   r   
num_layerss     r   r   z:FluxIPAdapterMixin.set_ip_adapter_scale.<locals>.<genexpr>K  s#     JjD6Is1v#Js   ,,zExpected list of z scales, got z, c              3   2   K   | ]  }t        |        y wr   )r   )r   xs     r   r   z:FluxIPAdapterMixin.set_ip_adapter_scale.<locals>.<genexpr>N  s     FkRSs1vFks   r   N)r   intfloatr   r   num_ip_adaptersr|   r   rc   ranger   r   	TypeErrorr   re   rf   r   rd   r   rk   r   valuesr   )
r   r   
scale_typer   _r   invalid_scale_sizesr   r   r   s
            @r   r   z'FluxIPAdapterMixin.set_ip_adapter_scale   s   4 3:&
**;;KK%%,,77
 eZ($)/$:;qU;E;E4
#34A9MGEtE*d:>N2N,O'PQ./A%/H.IUVVu:(~c%j\_DUUbcddJUJJ38"PaJq$<O3q6"PT^S_"_#J<}TYYFkWjFk=k<llmn 
 X]]RSZ:-F!z)AM]] '*$*:*:*J*J*Q*Q*S&dVc&d 	)"NU#(N 	)+ < #Q ^s   .	GG(G(Gc                 6   ddl m}m} t        | d      r(t	        | dd      d| _        | j                  ddg       t        | d      s4t        | d      r(t	        | dd      d| _        | j                  ddg       d| j                  _	        d| j                  j                  _        i }| j                  j                  j                         D ]-  \  }} |       }t        ||      r|n|j                         ||<   / | j                  j!                  |       y)	r   r
   )FluxAttnProcessorFluxIPAdapterAttnProcessorrK   NrP   r   rS   rX   )$models.transformers.transformer_fluxr   r   rs   rt   rK   r   rS   r   r   r|   r   r   r   rc   r   r   )r   r   r   r   r   r   r   s          r   r   z$FluxIPAdapterMixin.unload_ip_adapterX  s    	i 4)gdOT.R.^!%D##4,#? t-.t01gdDWY]6^6j)-&''4,'G -1)7;4 
++;;AAC 	KD%#4#6 (25:T(U$[`[j[j[l t	
 	++J7r   N)r   r   r   r   r   r   float16r   r   r   r   r   r   ry   r   r   r   r   r   r   r   r   r   ]  s    .
 68ET13+0==}d/4S$s)T#u||J[E\5\/]}d 3S	>*}d E#tCy.12	}d
 6>c]}d "*#}d #[[}d }d~6)%tE{DeDU0U*V 6)p&8r   r   c                       e Zd ZdZedefd       Ze	 	 	 ddee	e
e	ej                  f   f   de	dee	   dee	   ddf
d	       Zd
eddfdZddZy)SD3IPAdapterMixinz1Mixin for handling StableDiffusion 3 IP Adapters.returnc                     | j                   j                  j                         D cg c]  }t        |t              r|j
                    }}t        |      dkD  xr t        d |D              S c c}w )a7  Checks if IP-Adapter is loaded and scale > 0.

        IP-Adapter scale controls the influence of the image prompt versus text prompt. When this value is set to 0,
        the image context is irrelevant.

        Returns:
            `bool`: True when IP-Adapter is loaded and any layer has scale > 0.
        r   c              3   &   K   | ]	  }|d kD    yw)r   Nr   )r   r   s     r   r   z9SD3IPAdapterMixin.is_ip_adapter_active.<locals>.<genexpr>  s     &EUuqy&Es   )r   r   r   rc   r!   r   re   r   )r   	attn_procscaless      r   is_ip_adapter_activez&SD3IPAdapterMixin.is_ip_adapter_active  sj     "--==DDF
)%FG OO
 
 6{QE3&Ef&E#EE
s   #A.Nr%   r'   r&   r(   c                 2   |j                  dd      }|j                  dd      }|j                  dd      }|j                  dd      }	|j                  dd      }
|j                  dd      }|j                  d	t              }|r!t               sd}t        j	                  d
       |du rt        dd      st        d      ddd}t        |t              st        ||||||	|
|||
      }|j                  d      ri i d}t        |dd      5 }|j                         D ]t  }|j                  d      r(|j                  |      |d   |j                  dd      <   <|j                  d      sN|j                  |      |d   |j                  dd      <   v 	 ddd       nt!        |      }n|}t#        |j                               }d|vrd|vrt%        d      t'        | d      rt)        | dd      |t        |t              st        j+                  d|        |j-                  d       d!k(  rt/        ||      j1                         }nt/        |      j1                         }|||	d"}| j3                  t5        j6                  |fi |t9        j6                  |fd#| j:                  i|j=                  | j>                        $       n t%        d%      t        j	                  d&       | j@                  jC                  ||'       y# 1 sw Y   gxY w)(a  
        Parameters:
            pretrained_model_name_or_path_or_dict (`str` or `os.PathLike` or `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).
            weight_name (`str`, defaults to "ip-adapter.safetensors"):
                The name of the weight file to load. If a list is passed, it should have the same length as
                `subfolder`.
            subfolder (`str`, *optional*):
                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`.
            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.
            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,   Nr-   Fr.   r/   r0   r1   r2   r3   Tr4   r5   r6   r7   r8   r9   r<   r?   r@   rC   rD   rE   rG   rA   rH   rI   rB   rJ   rK   rL   rM   r   )r2   r,   r/   rO   )rS   rK   rQ   rR   rZ   )"rg   r   r   rh   ri   r   rj   rc   rl   r   rm   r	   rn   ro   rp   rq   r   rd   rf   rs   rt   ru   rv   r   rw   r{   r   rx   r   ry   rz   rF   r   r   )r   r%   r'   r&   r(   r   r,   r-   r.   r/   r0   r1   r2   r>   r   r   r   r   rn   r   s                       r   r   z!SD3IPAdapterMixin.load_ip_adapter  s2   r JJ{D1	$4e<**Y-!::&8$?

7D)::j$/"JJ':<VW%<%> %NN. $-=dG-L%. 
 $8iP
?F(5(#-!1!#%J ##N3,.bA
zT%H iA vvx i>>-8WXWcWcdgWhJ|4S[[PR5ST ^^M:WXWcWcdgWhJ|4S[[PR5ST	ii i -Z8
>JJOO%&t#D(@mnn 4)gdOT.R.Z#/!"GNKK"=>c=d ef+11#6!;26yBV2W2`2`2b/267K2L2U2U2W/ .?%.,<F ))*>*N*NOf*qjp*q&7&G&G3'AE'OU'"T[[/	 *  %{  c 	11*Pa1bci is   AL.)LLr   c                     | j                   j                  j                         D ]  }t        |t              s||_         y)am  
        Set IP-Adapter scale, which controls image prompt conditioning. A value of 1.0 means the model is only
        conditioned on the image prompt, and 0.0 only conditioned by the text prompt. Lowering this value encourages
        the model to produce more diverse images, but they may not be as aligned with the image prompt.

        Example:

        ```python
        >>> # Assuming `pipeline` is already loaded with the IP Adapter weights.
        >>> pipeline.set_ip_adapter_scale(0.6)
        >>> ...
        ```

        Args:
            scale (float):
                IP-Adapter scale to be set.

        N)r   r   r   rc   r!   r   )r   r   r   s      r   r   z&SD3IPAdapterMixin.set_ip_adapter_scale*  s;    & #..>>EEG 	-N.*KL',$	-r   c           	         t        | d      r&t        | dd      d| _        | j                  d       t        | d      r&t        | dd      d| _        | j                  d       d| j
                  _        | j
                  j                  j                         D ci c]0  \  }}|t        |t              r
t               n|j                         2 }}}| j
                  j                  |       yc c}}w )z
        Unloads the IP Adapter weights.

        Example:

        ```python
        >>> # Assuming `pipeline` is already loaded with the IP Adapter weights.
        >>> pipeline.unload_ip_adapter()
        >>> ...
        ```
        rK   NrP   rS   rX   )rs   rt   rK   r   rS   r   rA   r   r   rc   r!   r    r   r   )r   r   r   r   s       r   r   z#SD3IPAdapterMixin.unload_ip_adapterA  s     4)gdOT.R.^!%D##$#7 4,-'$@SUY2Z2f%)D"##d#; '+#  $//??EEG	
 e +5e=^+_%'ejetetevw

 
 	++J7
s   5C1)zip-adapter.safetensorsNrK   )r   N)r   r   r   r   propertyboolr   r   r   r   r   r   r   r   r   r   r   r   r   r   r   r   r     s    ;Fd F F"  4#'.=Qc/4S$sELL?P:Q5Q/RQc Qc C=	Qc
 'smQc 
Qc Qcf-% -D -. 8r   r   )2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   r   r   unet_loader_utilsr   transformersr   r   r   r   models.attention_processorr   r   r   r   r   r    r!   
get_loggerr   rh   r#   r   r   r   r   r   r   <module>r     s     . .    6 ! O	 	 	 9 ww   
		H	%j1 j1Z	w1 w1ta8 a8H	`8 `8r   