
    wi!                       d dl Z d dlZd dlZd dlZd dlZd dlZd dlmZ d dlm	Z	 d dl
mZmZmZmZmZmZmZmZ d dlZd dlZd dlZd dlZd dlmZmZmZmZmZ d dlm Z m!Z! d dl"m#Z# d dl$m%Z% d d	l&m'Z' d
dl(m)Z) d
dl*m+Z+ d
dl,m-Z- d
dl.m/Z/ d
dl0m1Z1m2Z2 d
dl3m4Z4 d
dl5m6Z6m7Z7m8Z8m9Z9m:Z:m;Z;m<Z<m=Z=m>Z>m?Z?m@Z@ d
dlAmBZBmCZC d
dlDmEZE  e=            rd dlFZFddlGmHZHmIZImJZJmKZKmLZLmMZMmNZNmOZOmPZPmQZQmRZRmSZSmTZTmUZU  e;            rd dlVZVg ZWeKD ]ZXeWY                    eX           dgZZ e?j[        e\          Z]e G d de8                      Z^e G d de8                      Z_ G d de+e9          Z` G d d          ZadS )    N)	dataclass)Path)AnyCallableDictListOptionalUnionget_args
get_origin)	ModelCardcreate_repohf_hub_download
model_infosnapshot_download)OfflineModeIsEnabledvalidate_hf_hub_args)version)	HTTPError)tqdm   )__version__)ConfigMixin)AutoencoderKL)FusedAttnProcessor2_0)_LOW_CPU_MEM_USAGE_DEFAULT
ModelMixin)SCHEDULER_CONFIG_NAME)CONFIG_NAMEDEPRECATED_REVISION_ARGS
BaseOutputPushToHubMixin	deprecateis_accelerate_availableis_accelerate_versionis_torch_npu_availableis_torch_versionloggingnumpy_to_pil)load_or_create_model_cardpopulate_model_card)is_compiled_module   )ALL_IMPORTABLE_CLASSESCONNECTED_PIPES_KEYSCUSTOM_PIPELINE_FILE_NAMELOADABLE_CLASSES_fetch_class_library_tuple_get_custom_pipeline_class_get_final_device_map_get_pipeline_class_unwrap_modelis_safetensors_compatibleload_sub_modelmaybe_raise_or_warnvariant_compatible_siblingswarn_deprecated_model_variantbalancedc                   X    e Zd ZU dZeeej        j                 ej	        f         e
d<   dS )ImagePipelineOutputz
    Output class for image pipelines.

    Args:
        images (`List[PIL.Image.Image]` or `np.ndarray`)
            List of denoised PIL images of length `batch_size` or NumPy array of shape `(batch_size, height, width,
            num_channels)`.
    imagesN)__name__
__module____qualname____doc__r
   r   PILImagenpndarray__annotations__     r/root/.openclaw/workspace/chatterbox_venv_py311/lib/python3.11/site-packages/diffusers/pipelines/pipeline_utils.pyr>   r>   d   s?           $sy'3444444rJ   r>   c                   (    e Zd ZU dZej        ed<   dS )AudioPipelineOutputz
    Output class for audio pipelines.

    Args:
        audios (`np.ndarray`)
            List of denoised audio samples of a NumPy array of shape `(batch_size, num_channels, sample_rate)`.
    audiosN)r@   rA   rB   rC   rF   rG   rH   rI   rJ   rK   rM   rM   r   s,           JrJ   rM   c            	       P    e Zd ZdZdZdZdZg Zg ZdZ	dZ
d Zdedef fdZ	 	 	 d1d
eeej        f         dedee         defdZd Zedej        fd            Zedej        fd            Zeedeeeej        f                  fd                        Zedefd            Zed             Zd Zd2dee          deej        ef         fdZ!d Z"d2dee          deej        ef         fdZ#d Z$eedeeej        f         fd                        Z%ed              Z&ed!             Z'ede(eef         fd"            Z)e*d#             Z+d3d$Z,d% Z-d4d&ee.         fd'Z/d( Z0	 d4d)ed&ee.         ddfd*Z1d5d,eeee f                  fd-Z2d. Z3d,ee          fd/Z4ed0             Z5 xZ6S )6DiffusionPipelinea  
    Base class for all pipelines.

    [`DiffusionPipeline`] stores all components (models, schedulers, and processors) for diffusion pipelines and
    provides methods for loading, downloading and saving models. It also includes methods to:

        - move all PyTorch modules to the device of your choice
        - enable/disable the progress bar for the denoising iteration

    Class attributes:

        - **config_name** (`str`) -- The configuration filename that stores the class and module names of all the
          diffusion pipeline's components.
        - **_optional_components** (`List[str]`) -- List of all optional components that don't have to be passed to the
          pipeline to function (should be overridden by subclasses).
    model_index.jsonNFc                     |                                 D ]f\  }}|$t          |t          t          f          r|d         |di}nt	          |          \  }}|||fi} | j        di | t          | ||           gd S Nr   NNrI   )items
isinstancetuplelistr2   register_to_configsetattr)selfkwargsnamemoduleregister_dictlibrary
class_names          rK   register_modulesz"DiffusionPipeline.register_modules   s    "LLNN 	( 	(LD&~FUDM!B!B~vayGX!%| 4&@&H&H#!%'< = $D#44m444 D$''''	( 	(rJ   r]   valuec                 r   || j         v rt          | j        |          rut          t	          | j        |          t
          t          f          r7|#| j        |         d         t          |          }nd} | j        di ||i n | j        di ||i t                      
                    ||           d S rS   )__dict__hasattrconfigrV   getattrrW   rX   r2   rY   super__setattr__)r[   r]   rc   class_library_tuple	__class__s       rK   rj   zDiffusionPipeline.__setattr__   s    4=  WT[$%?%? '$+t44udmDD 9$T):1)=)I*DU*K*K''*6'''FF41D*EFFFF''884-888D%(((((rJ   Tsave_directorysafe_serializationvariantpush_to_hubc                 6    t           j                  }|                    dd           |                    dd           |                    dd           |                    dd           |r|                    dd          }|                    dd          }|                    d	d          }	|                    d
d          }
|                    d|                    t          j        j                  d                   }t          |d||
          j        } 	                               \  } fdfd|
                                D             }|                                D ]}t           |          }|j        }t          |          rt          |          }|j        }d}t!          j
                    D ]\  }}|t"          j        v rt'          j        |          }n%t*                              | d| d| d|            |
                                D ]2\  }}t          ||d          }|t/          ||          r
|d         } n3| n|Bt*                              d| d| dt3          |           d             j        di |di 1t          ||          }t7          j        |          }d|j        v }d|j        v }i }|r||d<   |r||d<    |t          j                            ||          fi |                      |           |rptA          ||
d          }tC          |          }|"                    t          j                            |d                      #                    |||
||	           dS dS ) a  
        Save all saveable variables of the pipeline to a directory. A pipeline variable can be saved and loaded if its
        class implements both a save and loading method. The pipeline is easily reloaded using the
        [`~DiffusionPipeline.from_pretrained`] class method.

        Arguments:
            save_directory (`str` or `os.PathLike`):
                Directory to save a pipeline to. Will be created if it doesn't exist.
            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`.
            push_to_hub (`bool`, *optional*, defaults to `False`):
                Whether or not to push your model to the Hugging Face model 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.
        _class_nameN_diffusers_version_module_name_or_pathcommit_messageprivateF	create_prtokenrepo_idT)exist_okrw   ry   c                 :    | vrdS | j         v r
|d         dS dS )NFr   T)_optional_components)r]   rc   expected_modulesr[   s     rK   is_saveable_modulez=DiffusionPipeline.save_pretrained.<locals>.is_saveable_module   s5    +++ut000U1X5Eu4rJ   c                 4    i | ]\  }} ||          ||S rI   rI   ).0kvr   s      rK   
<dictcomp>z5DiffusionPipeline.save_pretrained.<locals>.<dictcomp>   s4    bbbTQI[I[\]_`IaIabAqbbbrJ   z is not installed. Cannot save  as z from r   zself.=z	 of type z cannot be saved.rT   rn   ro   )ry   is_pipeline	README.md)ry   rv   rx   rI   )$dictrg   popsplitospathsepr   rz   _get_signature_keysrU   keysrh   rl   r,   r6   r1   sysmodules	importlibimport_moduleloggerinfo
issubclasswarningtyperY   inspect	signature
parametersjoinsave_configr*   r+   save_upload_folder)r[   rm   rn   ro   rp   r\   model_index_dictrv   rw   rx   ry   rz   optional_kwargspipeline_component_name	sub_model	model_clssave_method_namelibrary_namelibrary_classesr`   
base_classsave_load_methodsclass_candidatesave_methodsave_method_signaturesave_method_accept_safesave_method_accept_variantsave_kwargs
model_cardr   r   s   `                            @@rK   save_pretrainedz!DiffusionPipeline.save_pretrained   sm   6  ,,]D11114888Y---_d333 	`#ZZ(8$??NjjE22G

;66IJJw--EjjN,@,@,M,Mb,QRRG!'D'QVWWW_G,0,D,DT,J,J)/	 	 	 	 	 	 cbbb-=-C-C-E-Ebbb'7'<'<'>'> 2	^ 2	^#&=>>I!+I "),, 0))44	%/	#1A1G1I1I  -o3;..'5lCCGGKK'  K  KH_  K  Ket  K  K  }I  K  K   6E5J5J5L5L  1J 1&-gz4&H&HO&2z)_7]7]2+<Q+?(#/E 0  'l3llill$y//lll   ('RR+BL*QRRR!)-=>>K %,$5k$B$B!&:>S>^&^#)26K6V)V&K& G4F01) 1)0I&K^5LMM]]Q\]]]] 	((( 	27%UYZZZJ,Z88JOOBGLLEEFFF-#       	 	rJ   c           
      h    |                     dd          }|                     dd          }|                     dd          }d}d}t          |          dk    rNt          |d         t          j                  r	|d         }n|d         t          j        |d                   nd}nt          |          dk    r\t          |d         t          j                  rt          d	          |d         t          j        |d                   nd}|d         }n"t          |          dk    rt          d
          ||t          d          |p|}||t          d          |p|}d d t          fd j        	                                D                       }|r.|r,t          j        |          j
        dk    rt          d           j        duot           j                  dk    }	|	rt          d          t          fd j        	                                D                       }
|
rg|ret          j        |          j
        dk    rHt                              dd                     j                                                   d                                           \  }} fd|D             }d |D             }|
p|}|D ]}t#          |d          o|j        }|r-|+t                              d|j        j         d| d           |r6|4t                              d|j        j         d| d|j         d           n|                    ||           |j        t          j        k    r/t/          |          d v r|s|st                              d!           ۉ S )"ug  
        Performs Pipeline dtype and/or device conversion. A torch.dtype and torch.device are inferred from the
        arguments of `self.to(*args, **kwargs).`

        <Tip>

            If the pipeline already has the correct torch.dtype and torch.device, then it is returned as is. Otherwise,
            the returned pipeline is a copy of self with the desired torch.dtype and torch.device.

        </Tip>


        Here are the ways to call `to`:

        - `to(dtype, silence_dtype_warnings=False) → DiffusionPipeline` to return a pipeline with the specified
          [`dtype`](https://pytorch.org/docs/stable/tensor_attributes.html#torch.dtype)
        - `to(device, silence_dtype_warnings=False) → DiffusionPipeline` to return a pipeline with the specified
          [`device`](https://pytorch.org/docs/stable/tensor_attributes.html#torch.device)
        - `to(device=None, dtype=None, silence_dtype_warnings=False) → DiffusionPipeline` to return a pipeline with the
          specified [`device`](https://pytorch.org/docs/stable/tensor_attributes.html#torch.device) and
          [`dtype`](https://pytorch.org/docs/stable/tensor_attributes.html#torch.dtype)

        Arguments:
            dtype (`torch.dtype`, *optional*):
                Returns a pipeline with the specified
                [`dtype`](https://pytorch.org/docs/stable/tensor_attributes.html#torch.dtype)
            device (`torch.Device`, *optional*):
                Returns a pipeline with the specified
                [`device`](https://pytorch.org/docs/stable/tensor_attributes.html#torch.device)
            silence_dtype_warnings (`str`, *optional*, defaults to `False`):
                Whether to omit warnings if the target `dtype` is not compatible with the target `device`.

        Returns:
            [`DiffusionPipeline`]: The pipeline converted to specified `dtype` and/or `dtype`.
        dtypeNdevicesilence_dtype_warningsFr-   r   r   zbWhen passing two arguments, make sure the first corresponds to `device` and the second to `dtype`.zPPlease make sure to pass at most two arguments (`device` and `dtype`) `.to(...)`zgYou have passed `dtype` both as an argument and as a keyword argument. Please only pass one of the two.zhYou have passed `device` both as an argument and as a keyword argument. Please only pass one of the two.c                 2   t                      rt          dd          rdS t          | d          ogt          | j        t
          j        j                  pCt          | j        d          o.t          | j        j        d         t
          j        j                  S )N<0.14.0F_hf_hookhooksr   )r$   r%   rf   rV   r   
accelerater   AlignDevicesHookr^   s    rK    module_is_sequentially_offloadedz>DiffusionPipeline.to.<locals>.module_is_sequentially_offloadedw  s    *,, 0Ec80T0T u6:.. 6?J,<,MNN \6?G44 \v4Q79I9Z[[rJ   c                     t                      rt          dd          rdS t          | d          o#t          | j        t
          j        j                  S )Nr   0.17.0.dev0Fr   )r$   r%   rf   rV   r   r   r   
CpuOffloadr   s    rK   module_is_offloadedz1DiffusionPipeline.to.<locals>.module_is_offloaded  sN    *,, 0Ec=0Y0Y u6:..k:fozO_Oj3k3kkrJ   c              3   4   K   | ]\  }} |          V  d S NrI   )r   _r^   r   s      rK   	<genexpr>z'DiffusionPipeline.to.<locals>.<genexpr>  sD       1
 1
9BF,,V441
 1
 1
 1
 1
 1
rJ   cudaa7  It seems like you have activated sequential model offloading by calling `enable_sequential_cpu_offload`, but are now attempting to move the pipeline to GPU. This is not compatible with offloading. Please, move your pipeline `.to('cpu')` or consider removing the move altogether if you use sequential offloading.zIt seems like you have activated a device mapping strategy on the pipeline which doesn't allow explicit device placement using `to()`. You can call `reset_device_map()` first and then call `to()`.c              3   4   K   | ]\  }} |          V  d S r   rI   )r   r   r^   r   s      rK   r   z'DiffusionPipeline.to.<locals>.<genexpr>  s3      #i#iIAv$7$7$?$?#i#i#i#i#i#irJ   a5  It seems like you have activated model offloading by calling `enable_model_cpu_offload`, but are now manually moving the pipeline to GPU. It is strongly recommended against doing so as memory gains from offloading are likely to be lost. Offloading automatically takes care of moving the individual components , z to GPU when needed. To make sure offloading works as expected, you should consider moving the pipeline back to CPU: `pipeline.to('cpu')` or removing the move altogether if you use offloading.c                 2    g | ]}t          |d           S r   rh   r   nr[   s     rK   
<listcomp>z(DiffusionPipeline.to.<locals>.<listcomp>  %    @@@a74D))@@@rJ   c                 P    g | ]#}t          |t          j        j                  !|$S rI   rV   torchnnModuler   ms     rK   r   z(DiffusionPipeline.to.<locals>.<listcomp>  +    HHHAux)G)GH1HHHrJ   is_loaded_in_8bitzThe module 'z,' has been loaded in 8bit and conversion to z9 is not yet supported. Module is still in 8bit precision.z+' has been loaded in 8bit and moving it to z6 via `.to()` is not yet supported. Module is still on .)cpua  Pipelines loaded with `dtype=torch.float16` cannot run with `cpu` device. It is not recommended to move them to `cpu` as running them will fail. Please make sure to use an accelerator to run the pipeline in inference, due to the lack of support for`float16` operations on this device in PyTorch. Please, remove the `torch_dtype=torch.float16` argument, or use another device for inference.)r   lenrV   r   r   r   
ValueErrorany
componentsrU   r   hf_device_mapr   r   r   r   r   rf   r   rl   r@   tofloat16str)r[   argsr\   r   r   r   	dtype_arg
device_arg"pipeline_is_sequentially_offloadedis_pipeline_device_mappedpipeline_is_offloadedmodule_namesr   r   is_offloadedr^   r   r   r   s   `                @@rK   r   zDiffusionPipeline.to/  s   H 

7D))Hd++!',De!L!L	
t99>>$q'5;// T G		6:1g6IU\$q'222t

YY!^^$q'5;//  x   37q'2Ed1g...4JQIIYY]]oppp!6y   "*"8z   %:	 	 		l 	l 	l .1 1
 1
 1
 1
FJoF[F[F]F]1
 1
 1
 .
 .
* . 	& 	U\&=Q=Q=VZ`=`=` J   %)$6d$B$bs4K]G^G^abGb!$ 	 W  
 !$#i#i#i#iQUQ`QfQfQhQh#i#i#i i i  	V 	V0D0D0IV0S0SNN l  IM  IR  IR  SW  Sb  Sg  Sg  Si  Si  Ij  Ij  l  l  l   22488a@@@@<@@@HHgHHH,R0R 	 	F '0C D D aIa  U%6 k6#3#<  k  kjo  k  k  k   ! )V%7 w6#3#<  w  win  w  w  gm  gt  w  w  w    		&%((( --KK7**. +$ + b   rJ   returnc                                                       \  }} fd|D             }d |D             }|D ]
}|j        c S t          j        d          S )zi
        Returns:
            `torch.device`: The torch device on which the pipeline is located.
        c                 2    g | ]}t          |d           S r   r   r   s     rK   r   z,DiffusionPipeline.device.<locals>.<listcomp>  r   rJ   c                 P    g | ]#}t          |t          j        j                  !|$S rI   r   r   s     rK   r   z,DiffusionPipeline.device.<locals>.<listcomp>  r   rJ   r   )r   r   r   r[   r   r   r   r^   s   `    rK   r   zDiffusionPipeline.device  su     22488a@@@@<@@@HHgHHH 	! 	!F=   |E"""rJ   c                                                       \  }} fd|D             }d |D             }|D ]
}|j        c S t          j        S )zg
        Returns:
            `torch.dtype`: The torch dtype on which the pipeline is located.
        c                 2    g | ]}t          |d           S r   r   r   s     rK   r   z+DiffusionPipeline.dtype.<locals>.<listcomp>  r   rJ   c                 P    g | ]#}t          |t          j        j                  !|$S rI   r   r   s     rK   r   z+DiffusionPipeline.dtype.<locals>.<listcomp>  r   rJ   )r   r   r   float32r   s   `    rK   r   zDiffusionPipeline.dtype  sm     22488a@@@@<@@@HHgHHH 	  	 F<}rJ   pretrained_model_name_or_pathc                   9:;<=>?@AB                      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d          }                     dt                    }                     dd          B                     dd          }                     dd          }                     dd          }|r*t                      sd}t                              d           |du rt          dd          st          d          |t          dd          st          d          |t                      st          d          |$t          |t                    st          d           |5|t          vr,t          | d!d"                    t                               |(|t          v rt          d#d$          rt          d%          |du r|t          d&| d'          t          j                            |          sJ|                    d(          d)k    rt          d*| d+           | j        |f|||||||	|
||||B|d,}n|}|                     |          }|                     d-d           i }Bt          j        |          D ]{}t          j                            ||          }t          j                            |          o||v }|o,t)          Bfd.t          j        |          D                       }|rB||<   |d}t          j                            t          j                            || d/                    r$t          j                            || d/          }nt          |d0         t,          t.          f          rt          j                            t          j                            ||d0         d1          d/                    r=t          j                            ||d0         d1          d/          }|d0         d)         }t1          | ||||||2          @|@j        rt          d3          @j        d4k    rpt7          j        t7          j        |d5                   j                  t7          j        d6          k    r)d1d7lm} m }! |!@d8|! d9|  d:| d;}"tC          d<d=|"d>           | "                    @          \  }#}$fd?|#D             >fd@|$D             ? @j#        |fi \  :}%}&:@fdA|$D             }'i |'?}'>fdB<<fdC:$                                D             :|
rdD:v rdD>vrt          dE          tK          |%          d1k    r&t                              dF|% dG@j         dH           d1dIlm&}( d})|"tO          |@>:tP          |||||||||	J          })d}*tS          j*        :$                                dKL          D ]\  }+\  },}-|)2tK          |)          d1k    r|)+                    |+d          }.|.dM|.i}*nd}*|-,                    dN          r
|-dOd         n|-}-t[          |(|,          }/t\          }0d}1|+>v r#t_          |,tP          |-|0>|+|/           >|+         }1njta          dji dP|,dQ|-dR|0dS|(dT|/dU@d|d|d|d|*d|d|d|dV|dW|+d
|
dBd|dX|}1t          1                    dY|+ dZ|- d[|+ d\| d]	           |1|'|+<   @j        r5t          j                            t          j                            |d^                    rte          j3        t          j                            |d^                    ==fd_th          D             }2i d|d|d|d|d|d|d	|	d|d|d|d|d|d|d|d|d|d|B|d`;>?fda99;fdb|2$                                D             }2|2$                                D ]=\  A}3|'5                    Afdc|3j6        $                                D                        >to          |#          to          |'8                                          z
  }4t-          >8                                          }5@j9        }6tK          |4          d1k    r5|4to          |5|6z             k    r|4D ]}7>+                    |7d          |'|7<   ntK          |4          d1k    rlto          t-          |'8                                          t-          >8                                          z             |$z
  }5t          dd@ de|# df|5 dg           @dji |'}8|8:                    |h           |tw          |8di|)           |8S )kus%  
        Instantiate a PyTorch diffusion pipeline from pretrained pipeline weights.

        The pipeline is set in evaluation mode (`model.eval()`) by default.

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

        ```
        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.
        ```

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

                    - A string, the *repo id* (for example `CompVis/ldm-text2im-large-256`) of a pretrained pipeline
                      hosted on the Hub.
                    - A path to a *directory* (for example `./my_pipeline_directory/`) containing pipeline weights
                      saved using
                    [`~DiffusionPipeline.save_pretrained`].
            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.
            custom_pipeline (`str`, *optional*):

                <Tip warning={true}>

                🧪 This is an experimental feature and may change in the future.

                </Tip>

                Can be either:

                    - A string, the *repo id* (for example `hf-internal-testing/diffusers-dummy-pipeline`) of a custom
                      pipeline hosted on the Hub. The repository must contain a file called pipeline.py that defines
                      the custom pipeline.
                    - A string, the *file name* of a community pipeline hosted on GitHub under
                      [Community](https://github.com/huggingface/diffusers/tree/main/examples/community). Valid file
                      names must match the file name and not the pipeline script (`clip_guided_stable_diffusion`
                      instead of `clip_guided_stable_diffusion.py`). Community pipelines are always loaded from the
                      current main branch of GitHub.
                    - A path to a directory (`./my_pipeline_directory/`) containing a custom pipeline. The directory
                      must contain a file called `pipeline.py` that defines the custom pipeline.

                For more information on how to load and create custom pipelines, please have a look at [Loading and
                Adding Custom
                Pipelines](https://huggingface.co/docs/diffusers/using-diffusers/custom_pipeline_overview)
            force_download (`bool`, *optional*, defaults to `False`):
                Whether or not to force the (re-)download of the model weights and configuration files, overriding the
                cached versions if they exist.
            cache_dir (`Union[str, os.PathLike]`, *optional*):
                Path to a directory where a downloaded pretrained model configuration is cached if the standard cache
                is not used.
            resume_download:
                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.
            custom_revision (`str`, *optional*):
                The specific model version to use. It can be a branch name, a tag name, or a commit id similar to
                `revision` when loading a custom pipeline from the Hub. Defaults to the latest stable 🤗 Diffusers
                version.
            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.
            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.
            use_onnx (`bool`, *optional*, defaults to `None`):
                If set to `True`, ONNX weights will always be downloaded if present. If set to `False`, ONNX weights
                will never be downloaded. By default `use_onnx` defaults to the `_is_onnx` class attribute which is
                `False` for non-ONNX pipelines and `True` for ONNX pipelines. ONNX weights include both files ending
                with `.onnx` and `.pb`.
            kwargs (remaining dictionary of keyword arguments, *optional*):
                Can be used to overwrite load and saveable variables (the pipeline components of the specific pipeline
                class). The overwritten components are passed directly to the pipelines `__init__` method. See example
                below for more information.
            variant (`str`, *optional*):
                Load weights from a specified variant filename such as `"fp16"` or `"ema"`. This is ignored when
                loading `from_flax`.

        <Tip>

        To use private or [gated](https://huggingface.co/docs/hub/models-gated#gated-models) models, log-in with
        `huggingface-cli login`.

        </Tip>

        Examples:

        ```py
        >>> from diffusers import DiffusionPipeline

        >>> # Download pipeline from huggingface.co and cache.
        >>> pipeline = DiffusionPipeline.from_pretrained("CompVis/ldm-text2im-large-256")

        >>> # Download pipeline that requires an authorization token
        >>> # For more information on access tokens, please refer to this section
        >>> # of the documentation](https://huggingface.co/docs/hub/security-tokens)
        >>> pipeline = DiffusionPipeline.from_pretrained("runwayml/stable-diffusion-v1-5")

        >>> # Use a different scheduler
        >>> from diffusers import LMSDiscreteScheduler

        >>> scheduler = LMSDiscreteScheduler.from_config(pipeline.scheduler.config)
        >>> pipeline.scheduler = scheduler
        ```
        	cache_dirNresume_downloadforce_downloadFproxieslocal_files_onlyry   revision	from_flaxtorch_dtypecustom_pipelinecustom_revisionprovidersess_options
device_map
max_memoryoffload_folderoffload_state_dictlow_cpu_mem_usagero   use_safetensorsuse_onnxload_connected_pipelinea,  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>=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`.ztLoading and dispatching requires torch >= 1.9.0. Please either update your PyTorch version or set `device_map=None`.zhUsing `device_map` requires the `accelerate` library. Please install it using: `pip install accelerate`.z`device_map` must be a string.z* not supported. Supported strategies are: r   r   z0.28.0zADevice placement requires `accelerate` version `0.28.0` or later.zCYou 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-   z,The provided pretrained_model_name_or_path "zP" is neither a valid local path nor a valid repo id. Please check the parameter.)r   r   r   r   r   ry   r   r   r	  r
  r   r  ro   r  _ignore_filesc              3   t   K   | ]2}|                     d           d                                       V  3dS )r   r-   N)r   
startswith)r   pro   s     rK   r   z4DiffusionPipeline.from_pretrained.<locals>.<genexpr>  sP       3 3<=AGGCLLO..w773 3 3 3 3 3rJ   .pyrr   r   )r  r   ra   r   r   z:`device_map` is not yet supported for connected pipelines.StableDiffusionInpaintPipeliners   z0.5.1)r  $StableDiffusionInpaintPipelineLegacyzeYou are using a legacy checkpoint for inpainting with Stable Diffusion, therefore we are loading the z class instead of z. For better inpainting results, we strongly suggest using Stable Diffusion's official inpainting checkpoint: https://huggingface.co/runwayml/stable-diffusion-inpainting instead or adapting your checkpoint z to the format of https://huggingface.co/runwayml/stable-diffusion-inpainting. Note that we do not actively maintain the {StableDiffusionInpaintPipelineLegacy} class and will likely remove it in version 1.0.0.r  z1.0.0standard_warnc                 D    i | ]}|v |                     |          S rI   r   r   r   r\   s     rK   r   z5DiffusionPipeline.from_pretrained.<locals>.<dictcomp>  *    VVV!v++Avzz!}}+++rJ   c                 D    i | ]}|v |                     |          S rI   r  r  s     rK   r   z5DiffusionPipeline.from_pretrained.<locals>.<dictcomp>  +    WWW11PV;;aA;;;rJ   c                 V    i | ]%}|v |j         v|                    |          &S rI   )r~   r   )r   r   	init_dictpipeline_classs     rK   r   z5DiffusionPipeline.from_pretrained.<locals>.<dictcomp>  sG     
 
 
I~~!>+N"N"N y}}Q"N"N"NrJ   c                 8    |d         dS | v r
|          dS dS )Nr   FTrI   )r]   rc   passed_class_objs     rK   load_modulez6DiffusionPipeline.from_pretrained.<locals>.load_module&  s3    Qxu''',<T,B,Ju4rJ   c                 4    i | ]\  }} ||          ||S rI   rI   )r   r   r   r"  s      rK   r   z5DiffusionPipeline.from_pretrained.<locals>.<dictcomp>-  s0    MMMda;;q!;L;LMQMMMrJ   safety_checkerzThe safety checker cannot be automatically loaded when loading weights `from_flax`. Please, pass `safety_checker=None` to `from_pretrained`, and load the safety checker separately if you need it.zKeyword arguments z are not expected by z and will be ignored.)	pipelines)r  r  r!  r  r`   r  r   cached_folderr   r   r   r   ry   r   zLoading pipeline components...)desc Flax   r   ra   importable_classesr%  is_pipeline_moduler  model_variantsr]   r&  zLoaded r   z from `z` subfolder of r   r   c                 L    i | ] }|t          j        |d g          d         !S )Nr   rh   data)r   prefix	modelcards     rK   r   z5DiffusionPipeline.from_pretrained.<locals>.<dictcomp>  s1    uuuV\vwy~vv'N'Nq'QuuurJ   )ro   r	  c                       fd                                 D             } fd                                 D             }i ||}|S )Nc                     i | ]>\  }}|                     d           d         k    $|                     d d          |?S r   r   r(  r   replacer   r   wr1  s      rK   r   zZDiffusionPipeline.from_pretrained.<locals>.get_connected_passed_kwargs.<locals>.<dictcomp>  s[     . . .7;q![\[b[bcf[g[ghi[jnt[t[tAIIlllB//[t[t[trJ   c                     i | ]>\  }}|                     d           d         k    $|                     d d          |?S r5  r6  r8  s      rK   r   zZDiffusionPipeline.from_pretrained.<locals>.get_connected_passed_kwargs.<locals>.<dictcomp>  s[     0 0 07;q!]^]d]deh]i]ijk]lpv]v]vAIIlllB//]v]v]vrJ   )rU   )r1  connected_passed_class_objconnected_passed_pipe_kwargsconnected_passed_kwargsr!  passed_pipe_kwargss   `   rK   get_connected_passed_kwargszFDiffusionPipeline.from_pretrained.<locals>.get_connected_passed_kwargs  s    . . . .?O?U?U?W?W. . .*0 0 0 0?Q?W?W?Y?Y0 0 0, +i-G*hKg*h'..rJ   c           
      z    i | ]7\  }}||t          j        |fi                                  |          8S r   )rP   from_pretrainedcopy)r   r1  rz   r?  load_kwargss      rK   r   z5DiffusionPipeline.from_pretrained.<locals>.<dictcomp>  sq        $FG&	 )9 *//115P5PQW5X5X  '&&rJ   c                 F    i | ]\  }}d                      |g          |S r   )r   )r   r]   	componentr1  s      rK   r   z5DiffusionPipeline.from_pretrained.<locals>.<dictcomp>  s/    rrr_T9SXXvtn--yrrrrJ   	Pipeline 
 expected , but only z were passed.ru   r   rI   )<r   r   r$   r   r   r'   NotImplementedErrorrV   r   r   SUPPORTED_DEVICE_MAPr   r%   r   r   isdircountdownloadload_configlistdirr   isfilerX   rW   r5   _load_connected_pipesr@   r   parsebase_version	diffusersr  r  r#   r   extract_init_dictrU   r   r%  r4   r`   r(   r   getr  rf   r.   r9   r8   r   r   loadr/   updater   setr   r~   rY   rZ   )Cclsr   r\   r   r   r   r   r   ry   r   r   r   r   r  r  r  r  r  r  r  r  r	  r
  r  r&  config_dictr-  folderfolder_path	is_foldervariant_existscustom_class_namer  r  deprecation_messager   r   unused_kwargsr   init_kwargsr%  final_device_mapcurrent_device_mapr]   r   ra   component_devicer,  r+  loaded_sub_modelconnected_pipesconnected_pipemissing_modulespassed_modulesoptional_modulesr^   modelr?  r  rC  r"  r2  r!  r>  r  r1  ro   sC     `                                                      @@@@@@@@@@rK   rA  z!DiffusionPipeline.from_pretrained  s   j JJ{D11	 **%6==$4e<<**Y--!::&8$??

7D))::j$//JJ{E22	jj55 **%6== **%6==::j$//zz.$77ZZd33
ZZd33
$4d;;#ZZ(<eDD"JJ':<VWW**Y-- **%6==::j$//"(**-F"N"N 	%<%>%> 	 %NN.   $$-=dG-L-L$%.  
 !*:4*I*I!%&  
 !*A*C*C!%z   !*Z*E*E!=>>>!j8L&L&L%jjSgIhIhjj   !j4H&H&H$S(33 o)*mnnn%%**@RV` R R R   w}}:;; 	:,22377!;; fC` f f f   )CL-# /-!1!# /! / /(?   ! MM& :Moom44 	...
 *]33 5 5 gll=&AAGMM+66P6[;P	!* "s 3 3 3 3ACKAXAX3 3 3 0 0 " 5-4N6* !7>>"',,}6M6M6MNNOO 	> gll=_:Q:Q:QRROOM2T5MBB 	>rw~~GLL;}+Ea+H(M(M(MNNH
 H
 	> !gll=[=WXY=Z:_:_:_``O +M :1 =,$;+($
 
 
 !n&J!%&bccc "&FFF7=M+&:;<<IL
 L
]7##L$ L$ gfffffffANp8p pLjp p  =	p p p   <gGZjopppp -0,C,CN,S,S)/VVVV6FVVVWWWWWWW&Fn&F{&]&]V\&]&]#	=!
 
 
 
 
$
 
 

 <;(:;	 	 	 	 	 NMMMioo&7&7MMM	  	)Y66;KSc;c;c%.   }!!NNw]wwI`www  
 	('''''  !4%-!1#%'+- /!1!     $ "07Y__=N=NUu0v0v0v 4	1 4	1,D,<+4D0E0E0I0I#3#7#7d#C#C #/*,.>)?&&)-& ,6+@+@+H+HXABBjJ ")L!A!A!7# ''' $ ':7IK[]acu   $4D#9   $2 $ $ $!-$)z$ (:'9$ (i	$
 (:'9$ $2>$ !,$ &X$ ".$  21$  *z$ $2>$ (:'9$ $2>$ $  (i!$" $G#$$ '8&7%$& #0-'$ * pdpp
pp4ppPmppp   !1K/ 0	BGNN27<<P]_jCkCk4l4l 0	!rw||M;'O'OPPIuuuu`tuuuOY!? !. 7	
 #$4  H { "? "? H  j j !.  %&8!" $%6#$ ##2'  K,	/ 	/ 	/ 	/ 	/ 	/     (7'<'<'>'>	  O +:*?*?*A*A  &""rrrrP^PiPoPoPqPqrrr   
 .//#k6F6F6H6H2I2II.335566)>!##3~P`?`;a;a(a(a) I I&6&:&:64&H&HF##I!!A%% k&6&6&8&8!9!9DAQAVAVAXAX<Y<Y!YZZ]llNpNpp6FppSappp  
 ---- 	  /L MMM!E?,<===rJ   c                 .    t          | j        dd           S )Nru   )rh   rg   r[   s    rK   name_or_pathzDiffusionPipeline.name_or_path  s    t{OT:::rJ   c                    | j                                         D ]\  }}t          |t          j        j                  r	|| j        v r.t          |d          s	| j        c S |	                                D ]U}t          |d          rCt          |j
        d          r.|j
        j        "t          j        |j
        j                  c c S V| j        S )z
        Returns the device on which the pipeline's models will be executed. After calling
        [`~DiffusionPipeline.enable_sequential_cpu_offload`] the execution device can only be inferred from
        Accelerate's module hooks.
        r   execution_device)r   rU   rV   r   r   r   _exclude_from_cpu_offloadrf   r   r   r   rt  )r[   r]   ro  r^   s       rK   _execution_devicez#DiffusionPipeline._execution_device  s      ?0022 	J 	JKD%eUX_55 A_9_9_5*-- #{"""--// J JFJ//J1CDDJ 8D <(HIIIIIIIJ {rJ   c                     | j                                         D ]U\  }}t          |t          j        j                  r1t          |d          r!t          j        	                    |d           Vg | _
        dS )z}
        Removes all hooks that were added when using `enable_sequential_cpu_offload` or `enable_model_cpu_offload`.
        r   T)recurseN)r   rU   rV   r   r   r   rf   r   r   remove_hook_from_module
_all_hooks)r[   r   ro  s      rK   remove_all_hooksz"DiffusionPipeline.remove_all_hooks  sx     --// 	N 	NHAu%11 NgeZ6P6P N 888MMMrJ   r   gpu_idr   c                 `   | j         duot          | j                   dk    }|rt          d          | j        t          d          t	                      rt          dd          rddlm} nt          d	          | 	                                 t          j        |          }|j        }||t          d
| d| d|j                   |p|j        pt          | dd          | _        |j        }t          j        | d| j                   }|| _        |                     dd           t          t          |j        d          }t%          |d          r(|                                r|                                 d | j                                        D             }	g | _        d}
| j                            d          D ]c}|	                    |d          }t5          |t          j        j                  s8 ||||
          \  }}
| j                            |
           d|	                                D ]m\  }}t5          |t          j        j                  s%|| j        v r|                    |           D |||          \  }}
| j                            |
           ndS )av  
        Offloads all models to CPU using accelerate, reducing memory usage with a low impact on performance. Compared
        to `enable_sequential_cpu_offload`, this method moves one whole model at a time to the GPU when its `forward`
        method is called, and the model remains in GPU until the next model runs. Memory savings are lower than with
        `enable_sequential_cpu_offload`, but performance is much better due to the iterative execution of the `unet`.

        Arguments:
            gpu_id (`int`, *optional*):
                The ID of the accelerator that shall be used in inference. If not specified, it will default to 0.
            device (`torch.Device` or `str`, *optional*, defaults to "cuda"):
                The PyTorch device type of the accelerator that shall be used in inference. If not specified, it will
                default to "cuda".
        Nr-   zIt seems like you have activated a device mapping strategy on the pipeline so calling `enable_model_cpu_offload() isn't allowed. You can call `reset_device_map()` first and then call `enable_model_cpu_offload()`.z^Model CPU offload cannot be enabled because no `model_cpu_offload_seq` class attribute is set.r  r   r   )cpu_offload_with_hookzC`enable_model_cpu_offload` requires `accelerate v0.17.0` or higher.You have passed both `gpu_id`=4 and an index as part of the passed device `device`=wCannot pass both. Please make sure to either not define `gpu_id` or not pass the index as part of the device: `device`=_offload_gpu_id:r   Tr   empty_cachec                 X    i | ]'\  }}t          |t          j        j                  $||(S rI   r   r   r   r   s      rK   r   z>DiffusionPipeline.enable_model_cpu_offload.<locals>.<dictcomp>,  s5    kkkAJWXZ_ZbZiLjLjk1kkkrJ   z->)prev_module_hook)r   r   r   model_cpu_offload_seqr$   r%   r   r~  ImportErrorr{  r   r   indexr   rh   r  _offload_devicer   rf   is_availabler  r   rU   rz  r   r   rV   r   r   appendru  )r[   r|  r   r   r~  torch_devicedevice_indexdevice_type
device_modall_model_componentshook	model_strro  r   r]   s                  rK   enable_model_cpu_offloadz*DiffusionPipeline.enable_model_cpu_offload  s.    %)$6d$B$bs4K]G^G^abGb!$ 	 g   %-p   #$$ 	e)>t])S)S 	e8888888cddd|F++#),":^ ^ ^ms ^ ^ KW  K\^ ^    &b);bwtM^`a?b?b"'EEt/CEEFF%d333UFK66
:}-- 	%*2I2I2K2K 	%""$$$kk1F1F1H1Hkkk399$?? 	) 	)I(,,Y==EeUX_55 ++E6DQQQGAtO""4((((
 05577 	- 	-KD%eUX_55 t555    //v>>4&&t,,,,	- 	-rJ   c                     t          | d          rt          | j                  dk    rdS |                     t	          | dd                     dS )a  
        Function that offloads all components, removes all model hooks that were added when using
        `enable_model_cpu_offload` and then applies them again. In case the model has not been offloaded this function
        is a no-op. Make sure to add this function to the end of the `__call__` function of your pipeline so that it
        functions correctly when applying enable_model_cpu_offload.
        rz  r   Nr  r   )r   )rf   r   rz  r  rh   rq  s    rK   maybe_free_model_hooksz(DiffusionPipeline.maybe_free_model_hooksE  s[     t\** 	c$/.B.Ba.G.GF 	%%WT;Lf-U-U%VVVVVrJ   c                    t                      rt          dd          rddlm} nt	          d          |                                  | j        duot          | j                  dk    }|rt          d          t          j
        |          }|j        }||t          d	| d
| d|j                   |p|j        pt          | dd          | _        |j        }t          j
        | d| j                   }|| _        | j
        j        dk    ro|                     dd           t          t          | j
        j        d          }t#          |d          r(|                                r|                                 | j                                        D ]j\  }	}
t-          |
t          j        j                  s%|	| j        v r|
                    |           Dt          |
j                  dk    } ||
||           kdS )u  
        Offloads all models to CPU using 🤗 Accelerate, significantly reducing memory usage. When called, the state
        dicts of all `torch.nn.Module` components (except those in `self._exclude_from_cpu_offload`) are saved to CPU
        and then moved to `torch.device('meta')` and loaded to GPU only when their specific submodule has its `forward`
        method called. Offloading happens on a submodule basis. Memory savings are higher than with
        `enable_model_cpu_offload`, but performance is lower.

        Arguments:
            gpu_id (`int`, *optional*):
                The ID of the accelerator that shall be used in inference. If not specified, it will default to 0.
            device (`torch.Device` or `str`, *optional*, defaults to "cuda"):
                The PyTorch device type of the accelerator that shall be used in inference. If not specified, it will
                default to "cuda".
        r  r   r   )cpu_offloadzG`enable_sequential_cpu_offload` requires `accelerate v0.14.0` or higherNr-   zIt seems like you have activated a device mapping strategy on the pipeline so calling `enable_sequential_cpu_offload() isn't allowed. You can call `reset_device_map()` first and then call `enable_sequential_cpu_offload()`.r  r  r  r  r  r   Tr  r  )offload_buffers)r$   r%   r   r  r  r{  r   r   r   r   r   r  r   rh   r  r  r   rf   r  r  r   rU   rV   r   r   ru  _parameters)r[   r|  r   r  r   r  r  r  r  r]   ro  r  s               rK   enable_sequential_cpu_offloadz/DiffusionPipeline.enable_sequential_cpu_offloadS  sw    #$$ 	i)>tX)N)N 	i.......ghhh$($6d$B$bs4K]G^G^abGb!$ 	 q   |F++#),":^ ^ ^ms ^ ^ KW  K\^ ^    &b);bwtM^`a?b?b"'EEt/CEEFF%;u$$GGE$G777 (8$??Jz=11 )j6M6M6O6O )&&(((?0022 
	L 
	LKD%eUX_55 t555     #&e&7"8"81"<E6?KKKKK
	L 
	LrJ   c                     | j         dS |                                  | j                                        D ]9\  }}t	          |t
          j        j                  r|                    d           :d| _         dS )z:
        Resets the device maps (if any) to None.
        Nr   )	r   r{  r   rU   rV   r   r   r   r   )r[   r]   rF  s      rK   reset_device_mapz"DiffusionPipeline.reset_device_map  s|     %F!!####'?#8#8#:#: ( (ii99 (LL'''!%DrJ   c                   789:;<=                      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}d}d}d}|s_	 t          ||	          }nK# t          t          t          j        f$ r,}t                              d| d           d}|}Y d}~nd}~ww xY w|st          | j	        ||	||||          }| 
                    |          }|                     dg           }d |                                D             7d |j        D             }t          ||          \  }}t          j        t                               d          d                   }t%          |d          }i } 7D ]h}!||!         d         }"|"t'          |"t(                    s(|! d|" d}#|#|v r|"| |!<   :|"t*          vr%t-          ||"          st/          |# d  d!          it1          |          dk    r!|d"| d#| d$| d%}$t3          d&d'|$d(           t5          |          t5          |          z
  }t5          |          t5          |          z
  }|	t6          v rYt9          j        t9          j        t<                    j                  t9          j        d)          k    rtA          |||	|           7fd*|D             8d}%|>t'          |d+         tB          tD          f          r|d+         d         }|d+         d,         }%tC          |          }|8fd-7D             z  }|d. |                                 D             z  }|| d|v r| dgng z  }|d/ 8D             z  }|tF          tH          | j	        tJ          gz  }|duo| d|v }&t1          |           dk    }'|&r|st/          d0 d1| d2 d3| d4	          |'r{|syt/          d0 d1d5&                    d6 |                                 D                        d7d8&                    fd9|                                 D                        d:          tO          | ||||&rnd|	|%||;	  	        }(| (                    |(          \  })}*fd<|)D             :|r*|s(tS          ||:=          stU          d>| d?| d@          |
rg dA}nS|rtS          ||:=          rdBdCg}||n|(j+        }|s|dDdEgz  }dF |D             }+dG |D             },t1          |+          dk    r\|,|+k    rVt                              dH| dI| dJ| dKd8&                    |+           dL| dKd8&                    |,|+z
             dM           ndNdCg}||n|(j+        }|s|dDdEgz  }dO |D             }-dP |D             }.t1          |-          dk    r\|.|-k    rVt                              dH| dI| dJ| dKd8&                    |-           dL| dKd8&                    |.|-z
             dM           :fdQ|D             }|(j,        r|-                    dR           |dS |D             z   }dT |D             <dU |D             ;<fdV|D             }/;fdW|/D             }/t]          |          j/        =ta          =fdX|/D                       }0|0r|s=S dY| j        i}1||1                    d          s||1d<   	 te          ||||||	|||1Z
  
        }2| 3                    th          j5        &                    |2d[                    6                    d+d          }3t'          |3t(                    r|37                    d\          r
|3d]d         n|3}3t          j        t                               d          d                   }t'          |3t(                    rt%          ||3d          nd}(|(||(j,        rutq          j9        th          j5        &                    |2dR                    9tu          9fd^tv          D             g           }4|4D ]}5||||||||d_}6ty          j=        |5fi |6  |2S # t|          $ r | tU          d` da          |w xY w)bu{  
        Download and cache a PyTorch diffusion pipeline from pretrained pipeline weights.

        Parameters:
            pretrained_model_name (`str` or `os.PathLike`, *optional*):
                A string, the *repository id* (for example `CompVis/ldm-text2im-large-256`) of a pretrained pipeline
                hosted on the Hub.
            custom_pipeline (`str`, *optional*):
                Can be either:

                    - A string, the *repository id* (for example `CompVis/ldm-text2im-large-256`) of a pretrained
                      pipeline hosted on the Hub. The repository must contain a file called `pipeline.py` that defines
                      the custom pipeline.

                    - A string, the *file name* of a community pipeline hosted on GitHub under
                      [Community](https://github.com/huggingface/diffusers/tree/main/examples/community). Valid file
                      names must match the file name and not the pipeline script (`clip_guided_stable_diffusion`
                      instead of `clip_guided_stable_diffusion.py`). Community pipelines are always loaded from the
                      current `main` branch of GitHub.

                    - A path to a *directory* (`./my_pipeline_directory/`) containing a custom pipeline. The directory
                      must contain a file called `pipeline.py` that defines the custom pipeline.

                <Tip warning={true}>

                🧪 This is an experimental feature and may change in the future.

                </Tip>

                For more information on how to load and create custom pipelines, take a look at [How to contribute a
                community pipeline](https://huggingface.co/docs/diffusers/main/en/using-diffusers/contribute_pipeline).

            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.
            custom_revision (`str`, *optional*, defaults to `"main"`):
                The specific model version to use. It can be a branch name, a tag name, or a commit id similar to
                `revision` when loading a custom pipeline from the Hub. It can be a 🤗 Diffusers version when loading a
                custom pipeline from GitHub, otherwise it defaults to `"main"` when loading from the Hub.
            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.
            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.
            use_onnx (`bool`, *optional*, defaults to `False`):
                If set to `True`, ONNX weights will always be downloaded if present. If set to `False`, ONNX weights
                will never be downloaded. By default `use_onnx` defaults to the `_is_onnx` class attribute which is
                `False` for non-ONNX pipelines and `True` for ONNX pipelines. ONNX weights include both files ending
                with `.onnx` and `.pb`.
            trust_remote_code (`bool`, *optional*, defaults to `False`):
                Whether or not to allow for custom pipelines and components defined on the Hub in their own files. This
                option should only be set to `True` for repositories you trust and in which you have read the code, as
                it will execute code present on the Hub on your local machine.

        Returns:
            `os.PathLike`:
                A path to the downloaded pipeline.

        <Tip>

        To use private or [gated models](https://huggingface.co/docs/hub/models-gated#gated-models), log-in with
        `huggingface-cli login`.

        </Tip>

        r   Nr   r   Fr   r   ry   r   r   r   r  ro   r	  r
  r  trust_remote_codeT)ry   r   zCouldn't connect to the Hub: z$.
Will try to load from local cache.)r   r   r   r   r   ry   r  c                 N    g | ]"\  }}t          |t                    |d k     |#S )rr   )rV   rX   r  s      rK   r   z.DiffusionPipeline.download.<locals>.<listcomp>*  s7    lll$!QAtATATlYZ^kYkYkAYkYkYkrJ   c                     h | ]	}|j         
S rI   )	rfilename)r   siblings     rK   	<setcomp>z-DiffusionPipeline.download.<locals>.<setcomp>,  s    HHHw*HHHrJ   )ro   r   r   r%  r  r  z4 as defined in `model_index.json` does not exist in z. and is not a module in 'diffusers/pipelines'.z7You are trying to load the model files of the `variant=zE`, but no such modeling files are available.The default model files: z= will be loaded instead. Make sure to not load from `variant=z`if such variant modeling files are not available. Doing so will lead to an error in v0.24.0 as defaulting to non-variantmodeling files is deprecated.zno variant defaultz0.24.0r  z0.22.0c                     h | ]N}t           j                            |          d          v )t           j                            |          d          OS )r   )r   r   r   )r   ffolder_namess     rK   r  z-DiffusionPipeline.download.<locals>.<setcomp>W  sP    !v!v!v!RTRYR_R_`aRbRbcdReiuRuRu"'--"2"21"5RuRuRurJ   rr   r-   c                 "    g | ]}|v| d S )z/*rI   )r   r   model_folder_namess     rK   r   z.DiffusionPipeline.download.<locals>.<listcomp>c  s*    ]]]AJ\A\A\!xxxA\A\A\rJ   c                 $    g | ]\  }}| d | dS )r  r  rI   )r   r   r  s      rK   r   z.DiffusionPipeline.download.<locals>.<listcomp>e  s(    SSSA!}}a}}}SSSrJ   c                 N    g | ]"}t           j                            |d           #S )zconfig.jsonr   r   r   )r   r   s     rK   r   z.DiffusionPipeline.download.<locals>.<listcomp>i  s(    ZZZ!rw||A}==ZZZrJ   zThe repository for z contains custom code in zp.py which must be executed to correctly load the model. You can inspect the repository content at https://hf.co/z/blob/main/zV.py.
Please pass the argument `trust_remote_code=True` to allow custom code to be run.z.py, c                 T    g | ]%\  }}t           j                            ||          &S rI   r  r  s      rK   r   z.DiffusionPipeline.download.<locals>.<listcomp>~  sY      ha  ha  ha  @C  @A  BChjhohthtuvxyhzhz  ha  ha  harJ   z_ which must be executed to correctly load the model. You can inspect the repository content at r   c           	      .    g | ]\  }}d  d| d| dS )zhttps://hf.co/r  r  rI   )r   r   r   pretrained_model_names      rK   r   z.DiffusionPipeline.download.<locals>.<listcomp>  s      \v  \v  \v  UX  UV  WX  ]P  nC  ]P  ]P  FG  ]P  ]P  JK  ]P  ]P  ]P  \v  \v  \vrJ   zS.
Please pass the argument `trust_remote_code=True` to allow custom code to be run.)r  r   rz   hub_revisionra   r   r   c                     g | ]}|v |	S rI   rI   r  s     rK   r   z.DiffusionPipeline.download.<locals>.<listcomp>  s     O O Oq1;;;;;rJ   )ro   passed_componentsz6Could not find the necessary `safetensors` weights in z
 (variant=))*.bin*.safetensors*.onnx*.pbr  z	*.msgpackr  r  c                 <    h | ]}|                     d           |S z.safetensorsendswithr   r  s     rK   r  z-DiffusionPipeline.download.<locals>.<setcomp>  s-    0l0l0lqQRQ[Q[\jQkQk0l0l0l0lrJ   c                 <    h | ]}|                     d           |S r  r  r  s     rK   r  z-DiffusionPipeline.download.<locals>.<setcomp>  s*    .h.h.hQQZZXfMgMg.hq.h.h.hrJ   z
A mixture of z	 and non-z" filenames will be loaded.
Loaded z filenames:
[z]
Loaded non-zF
If this behavior is not expected, please check your folder structure.r  c                 <    h | ]}|                     d           |S z.binr  r  s     rK   r  z-DiffusionPipeline.download.<locals>.<setcomp>  s*    (\(\(\qTZI[I[(\(\(\(\rJ   c                 <    h | ]}|                     d           |S r  r  r  s     rK   r  z-DiffusionPipeline.download.<locals>.<setcomp>  s*    &X&X&XQQZZPVEWEW&Xq&X&X&XrJ   c                     g | ]G}t          |                    d                     dk    r|                    d           d         v E|HS )r  r   r   )r   r   )r   r  r  s     rK   r   z.DiffusionPipeline.download.<locals>.<listcomp>  sW       #aggcll2C2Cq2H2HQWWUX\\Z[_`qMqMqMqMqMqrJ   r   c                     g | ]}| d S )z.index.*jsonrI   )r   is     rK   r   z.DiffusionPipeline.download.<locals>.<listcomp>  s!    0]0]0]A1C1C1C0]0]0]rJ   c                 Z    g | ](}t          j        t          j        |                    )S rI   recompilefnmatch	translater   r  s     rK   r   z.DiffusionPipeline.download.<locals>.<listcomp>  s-     [ [ [aG,=a,@,@!A!A [ [ [rJ   c                 Z    g | ](}t          j        t          j        |                    )S rI   r  r  s     rK   r   z.DiffusionPipeline.download.<locals>.<listcomp>  s-    YYYQ
7+<Q+?+? @ @YYYrJ   c                 L    g | ]t          fd D                        S )c              3   B   K   | ]}|                               V  d S r   matchr   r  r  s     rK   r   z8DiffusionPipeline.download.<locals>.<listcomp>.<genexpr>  s-      =d=dQaggajj=d=d=d=d=d=drJ   r   )r   r  re_ignore_patterns    @rK   r   z.DiffusionPipeline.download.<locals>.<listcomp>  s=    eeeA#=d=d=d=dRc=d=d=d:d:deaeeerJ   c                 L    g | ]t          fd D                        S )c              3   B   K   | ]}|                               V  d S r   r  r  s     rK   r   z8DiffusionPipeline.download.<locals>.<listcomp>.<genexpr>  s-      >d>daqwwqzz>d>d>d>d>d>drJ   r  )r   r  re_allow_patterns    @rK   r   z.DiffusionPipeline.download.<locals>.<listcomp>  s=    eeeA3>d>d>d>dSc>d>d>d;d;deaeeerJ   c              3   F   K   | ]}|z                                   V  d S r   )is_file)r   r  snapshot_folders     rK   r   z-DiffusionPipeline.download.<locals>.<genexpr>  s4      $]$]o&9%B%B%D%D$]$]$]$]$]$]rJ   r  )	r   r   r   r   ry   r   allow_patternsignore_patterns
user_agentrQ   r)  r*  c                 <    g | ]}t          j        |g           S rI   r/  )r   r   r2  s     rK   r   z.DiffusionPipeline.download.<locals>.<listcomp>  s'    &d&d&d!wy~q"'E'E&d&d&drJ   )r   r   r   r   r   ry   ro   r	  zCannot load model z: model is not cached locally and an error occurred while trying to fetch metadata from the Hub. Please check out the root cause in the stacktrace above.)?r   r   r   r   requestsConnectionErrorr   r   r   config_name_dict_from_json_filerU   siblingsr:   r   r   r@   r   rh   rV   r   r1   rf   r   r   r#   r[  r    r   rT  r   rU  r;   rX   rW   r   r   r0   r   r5   r   r7   EnvironmentError_is_onnxrS  r  r   parentallr  r   rP  r   r   rX  r  r   rY  sumr/   rP   rO  FileNotFoundError)>r\  r  r\   r   r   r   r   r   ry   r   r   r   r  ro   r	  r
  r  r  allow_pickler  r  model_info_call_errorr   econfig_filer]  ignore_filenames	filenamesmodel_filenamesvariant_filenamesdiffusers_moduler%  custom_componentsrF  module_candidatecandidate_filerc  rb  load_pipe_from_hubload_components_from_hubr  expected_componentsr   safetensors_variant_filenamessafetensors_model_filenamesbin_variant_filenamesbin_model_filenamesexpected_filespipeline_is_cachedr  r&  cls_namerj  connected_pipe_repo_iddownload_kwargsr  r  r2  r  r  r  r  s>    ``                                                    @@@@@@@rK   rO  zDiffusionPipeline.download  sY   x JJ{D11	 **%6==$4e<<**Y--!::&8$??

7D))::j$//JJ{E22	 **%6== **%6==**Y-- **%6==::j$//"(**-F"N"N"JJ':EBB""OL59 	**!"7uxXXX3X5MN * * *gqggghhh#' ()%%%%%%*
   z	')%#!- /	 	 	K 22;??K*CC ml+*;*;*=*=lllLHH$-HHHI1LY`g1h1h1h.O.(6x~~c7J7J17MNN 0+>>I !#)  	#.y#9!#< #+:>NPS3T3T+ %.!E!E0@!E!E!E!Y..3C%i00%-===giYiFjFj=$)  e  e_t  e  e  e   $%%**w/B4g 4 40?4 4 F4 4 4 $ .:M]bcccc "/22S9I5J5JJO #$5 6 6=M9N9N N 333k**79 9x((9) 9) ..CUGU]_nooo!v!v!v!v!v!v!v $&:k-6PSWY^R_+`+`&"-m"<Q"?$/$>q$A! "/22N ]]]]]]]]NSS9J9P9P9R9RSSSSNo;R;R;RV_;_;_/66677eggNZZGYZZZZN%)	 N "1!<!eOAXAXAX\eAe'*+<'='='A$! *;  i*? i iZi i i_ti i BQi i i   ( 0A  i*? i iZaZfZf  ha  ha  GX  G^  G^  G`  G`  ha  ha  ha  [b  [b i iQUQZQZ  \v  \v  \v  \v  \m  \s  \s  \u  \u  \v  \v  \v  Rw  Rwi i i   1(? /1CM--%,#(
 
 
N &)%<%<^%L%L" O O O O,? O O O  	$	 2#WHY  	 'r_rrhorrr     "N"N"N  %>DU& & &  $+K"8'/';88AX :#&'99O0l0l<M0l0l0l-.h.h/.h.h.h+566::37TTTNN ^'  ^  ^G  ^  ^ho  ^  ^  @D  @I  @I  Jg  @h  @h  ^  ^  x  ^  ^  OS  OX  OX  Yt  wT  YT  OU  OU  ^  ^  ^   $3K"@'/';88AX :#&'99O(\(\4E(\(\(\%&X&X/&X&X&X#,--116IMb6b6bNN F'  F  FG  F  Fho  F  F  @D  @I  @I  J_  @`  @`  F  F  pw  F  F  GK  GP  GP  Qd  g|  Q|  G}  G}  F  F  F  
   )  N 3 3%%k222 .0]0]_0]0]0]]O [ [? [ [ [YY.YYYeeeeeeeNeeeeeeeN";//6O!$$]$]$]$]n$]$]$]!]!]! '. ' '&&5
&/G/G/N/N&,;J()5	--%# /!1!- /%  M rw||MCU'V'VWW[[\ikoppH'1(C'@'@nXEXEXY_E`E`nx||fnH(6x~~c7J7J17MNNJTU]_bJcJcmW%5xFFFimN)n.R)%N27<<{+S+STT	"%&d&d&d&dOc&d&d&dfh"i"i.= Z Z*%.+:*8#*,<!&#*+:	' 	'O &./EYYYYYY    	- 	- 	-
 %, ')>     -	-	-s%   %E8 8G "F;;G .E/e "f c                    t          j        |j                  j        }d |                                D             }t          d |                                D                       }t          |                                          dhz
  }t          |          }|D ]5}|| j        v r*|	                    |           |
                    |           6||fS )Nc                 D    i | ]\  }}|j         t          j        k    ||S rI   defaultr   _emptyr  s      rK   r   z9DiffusionPipeline._get_signature_keys.<locals>.<dictcomp>  s.    bbb1aiSZSaFaFaq!FaFaFarJ   c                 B    h | ]\  }}|j         t          j        k    |S rI   r  r  s      rK   r  z8DiffusionPipeline._get_signature_keys.<locals>.<setcomp>  s,    "c"c"cAqyT[TbGbGb1GbGbGbrJ   r[   )r   r   __init__r   rU   r[  r   rX   r~   addremove)r\  objr   required_parametersoptional_parametersr   optional_namesr]   s           rK   r   z%DiffusionPipeline._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122" 	1 	1Ds/// $$T***#**4000!444rJ   c                 l   i }t          j        | j                  j                                        D ]\  }}t          j        |j                  r|j        f||<   *t          |j                  t          k    rt          |j                  ||<   _t                              d| d|  d           |S )Nz)cannot get type annotation for Parameter z of r   )r   r   r  r   rU   isclass
annotationr   r
   r   r   r   )r\  signature_typesr   r   s       rK   _get_signature_typesz&DiffusionPipeline._get_signature_types!  s    %cl33>DDFF 	Z 	ZDAqq|,, Z&'l_""AL))U22%-al%;%;""X1XXRUXXXYYYYrJ   c           
      4                                     \  } fd j                                        D             }t          |                                          |k    r2t	            d j         d| d|                                 d          |S )a  
        The `self.components` property can be useful to run different pipelines with the same weights and
        configurations without reallocating additional memory.

        Returns (`dict`):
            A dictionary containing all the modules needed to initialize the pipeline.

        Examples:

        ```py
        >>> from diffusers import (
        ...     StableDiffusionPipeline,
        ...     StableDiffusionImg2ImgPipeline,
        ...     StableDiffusionInpaintPipeline,
        ... )

        >>> text2img = StableDiffusionPipeline.from_pretrained("runwayml/stable-diffusion-v1-5")
        >>> img2img = StableDiffusionImg2ImgPipeline(**text2img.components)
        >>> inpaint = StableDiffusionInpaintPipeline(**text2img.components)
        ```
        c                 d    i | ],}|                     d           s|v|t          |          -S rE  )r  rh   )r   r   r  r[   s     rK   r   z0DiffusionPipeline.components.<locals>.<dictcomp>E  sL     
 
 
$%1<<PSCTCT
YZbuYuYuAwtQYuYuYurJ   z% has been incorrectly initialized or z& is incorrectly implemented. Expected z to be defined, but z are defined.)r   rg   r   r[  r   rl   )r[   r   r   r  s   `  @rK   r   zDiffusionPipeline.components-  s    . 150H0H0N0N--
 
 
 
 
)-)9)9););
 
 

 z  !!%555 [ [dn [ [$[ [:D//:K:K[ [ [  
 rJ   c                      t          |           S )zL
        Convert a NumPy image or a batch of images to a PIL image.
        )r)   )r?   s    rK   r)   zDiffusionPipeline.numpy_to_pilQ  s    
 F###rJ   c                     t          | d          si | _        n?t          | j        t                    s%t	          dt          | j                   d          |t          |fi | j        S |t          dd|i| j        S t	          d          )N_progress_bar_configz=`self._progress_bar_config` should be of type `dict`, but is r   totalz/Either `total` or `iterable` has to be defined.rI   )rf   r  rV   r   r   r   r   )r[   iterabler  s      rK   progress_barzDiffusionPipeline.progress_barX  s    t344 	(*D%%D5t<< 	rPTUYUnPoPorrr   >>D$=>>>AAeAt'@AAANOOOrJ   c                     || _         d S r   )r  )r[   r\   s     rK   set_progress_bar_configz)DiffusionPipeline.set_progress_bar_configg  s    $*!!!rJ   attention_opc                 2    |                      d|           dS )u  
        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 DiffusionPipeline
        >>> from xformers.ops import MemoryEfficientAttentionFlashAttentionOp

        >>> pipe = DiffusionPipeline.from_pretrained("stabilityai/stable-diffusion-2-1", torch_dtype=torch.float16)
        >>> pipe = pipe.to("cuda")
        >>> pipe.enable_xformers_memory_efficient_attention(attention_op=MemoryEfficientAttentionFlashAttentionOp)
        >>> # Workaround for not accepting attention shape using VAE for Flash Attention
        >>> pipe.vae.enable_xformers_memory_efficient_attention(attention_op=None)
        ```
        TN+set_use_memory_efficient_attention_xformers)r[   r  s     rK   *enable_xformers_memory_efficient_attentionz<DiffusionPipeline.enable_xformers_memory_efficient_attentionj  s!    B 	88|LLLLLrJ   c                 0    |                      d           dS )zs
        Disable memory efficient attention from [xFormers](https://facebookresearch.github.io/xformers/).
        FNr   rq  s    rK   +disable_xformers_memory_efficient_attentionz=DiffusionPipeline.disable_xformers_memory_efficient_attention  s     	88?????rJ   validc                      dt           j        j        ffd                                \  }} fd|D             }d |D             }|D ]} |           d S )Nr^   c                     t          | d          r|                                |                                 D ]} |           d S )Nr!  )rf   r!  children)r^   childr  fn_recursive_set_mem_effr%  s     rK   r*  z_DiffusionPipeline.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 0rJ   c                 2    g | ]}t          |d           S r   r   r   s     rK   r   zQDiffusionPipeline.set_use_memory_efficient_attention_xformers.<locals>.<listcomp>  r   rJ   c                 P    g | ]#}t          |t          j        j                  !|$S rI   r   r   s     rK   r   zQDiffusionPipeline.set_use_memory_efficient_attention_xformers.<locals>.<listcomp>  r   rJ   )r   r   r   r   )r[   r%  r  r   r   r   r^   r*  s   ```    @rK   r!  z=DiffusionPipeline.set_use_memory_efficient_attention_xformers  s    	0UX_ 	0 	0 	0 	0 	0 	0 	0 	0 22488a@@@@<@@@HHgHHH 	- 	-F$$V,,,,	- 	-rJ   auto
slice_sizec                 0    |                      |           dS )u  
        Enable sliced attention computation. When this option is enabled, the attention module splits the input tensor
        in slices to compute attention in several steps. For more than one attention head, the computation is performed
        sequentially over each head. This is useful to save some memory in exchange for a small speed decrease.

        <Tip warning={true}>

        ⚠️ Don't enable attention slicing if you're already using `scaled_dot_product_attention` (SDPA) from PyTorch
        2.0 or xFormers. These attention computations are already very memory efficient so you won't need to enable
        this function. If you enable attention slicing with SDPA or xFormers, it can lead to serious slow downs!

        </Tip>

        Args:
            slice_size (`str` or `int`, *optional*, defaults to `"auto"`):
                When `"auto"`, halves the input to the attention heads, so attention will be computed in two steps. If
                `"max"`, maximum amount of memory will be saved by running only one slice at a time. If a number is
                provided, uses as many slices as `attention_head_dim // slice_size`. In this case, `attention_head_dim`
                must be a multiple of `slice_size`.

        Examples:

        ```py
        >>> import torch
        >>> from diffusers import StableDiffusionPipeline

        >>> pipe = StableDiffusionPipeline.from_pretrained(
        ...     "runwayml/stable-diffusion-v1-5",
        ...     torch_dtype=torch.float16,
        ...     use_safetensors=True,
        ... )

        >>> prompt = "a photo of an astronaut riding a horse on mars"
        >>> pipe.enable_attention_slicing()
        >>> image = pipe(prompt).images[0]
        ```
        Nset_attention_slice)r[   r.  s     rK   enable_attention_slicingz*DiffusionPipeline.enable_attention_slicing  s    L 	  ,,,,,rJ   c                 0    |                      d           dS )z
        Disable sliced attention computation. If `enable_attention_slicing` was previously called, attention is
        computed in one step.
        N)r2  rq  s    rK   disable_attention_slicingz+DiffusionPipeline.disable_attention_slicing  s     	%%d+++++rJ   c                                                       \  }} fd|D             }d |D             }|D ]}|                    |           d S )Nc                 2    g | ]}t          |d           S r   r   r   s     rK   r   z9DiffusionPipeline.set_attention_slice.<locals>.<listcomp>  r   rJ   c                 p    g | ]3}t          |t          j        j                  !t	          |d           1|4S r0  )rV   r   r   r   rf   r   s     rK   r   z9DiffusionPipeline.set_attention_slice.<locals>.<listcomp>  s<    nnnAux)G)GnGTUWlLmLmn1nnnrJ   )r   r1  )r[   r.  r   r   r   r^   s   `     rK   r1  z%DiffusionPipeline.set_attention_slice  sv    22488a@@@@<@@@nngnnn 	3 	3F&&z2222	3 	3rJ   c                    t          |j                                      dd          }                    dd          }                    dd          }|t          ||          }n| }|                     |          \  t          j        | j                  j        }t          fd|
                                D                       }|                                }	                    dd          }
fdD             }i }|j        
                                D ]\  }}|v r||vr}t          |t                    r"t          |          |	|         v s||| j        v r|||<   Jt"                              d	| d
| dt          |           d|	|          d| d| d           fdD             fd                                D             }fd                                D             }|D ]}                    d|           ||<   i |||fd
                                D             }t                    t          |j                  z
  t                                                    z
  t          |          z
  }t)          |          dk    rgt+          d| d dt          t-          |                                          t-          |                                          z              d           |di }|
|                    |
            |j        di | ||                    |           |S )a  
        Create a new pipeline from a given pipeline. This method is useful to create a new pipeline from the existing
        pipeline components without reallocating additional memory.

        Arguments:
            pipeline (`DiffusionPipeline`):
                The pipeline from which to create a new pipeline.

        Returns:
            `DiffusionPipeline`:
                A new pipeline with the same weights and configurations as `pipeline`.

        Examples:

        ```py
        >>> from diffusers import StableDiffusionPipeline, StableDiffusionSAGPipeline

        >>> pipe = StableDiffusionPipeline.from_pretrained("runwayml/stable-diffusion-v1-5")
        >>> new_pipe = StableDiffusionSAGPipeline.from_pipe(pipe)
        ```
        r   Nr   r  )r   c                 L    h | ] \  }}|j         t          j        k    |v |!S rI   r  )r   r   r   r   s      rK   r  z.DiffusionPipeline.from_pipe.<locals>.<setcomp>  s7    ggg41agn1L1LQRVfQfQfQQfQfQfrJ   ru   c                 D    i | ]}|v |                     |          S rI   r  r  s     rK   r   z/DiffusionPipeline.from_pipe.<locals>.<dictcomp>  r  rJ   z
component zP is not switched over to new pipeline because type does not match the expected. z is z while the new pipeline expect zU. please pass the component of the correct type to the new pipeline. `from_pipe(..., r   z)`c                 D    i | ]}|v |                     |          S rI   r  r  s     rK   r   z/DiffusionPipeline.from_pipe.<locals>.<dictcomp>%  r  rJ   c                 2    i | ]}|v |v
||         S rI   rI   )r   r   r   original_configr>  s     rK   r   z/DiffusionPipeline.from_pipe.<locals>.<dictcomp>&  s@      
  
  
O##1C(C(C q!(C(C(CrJ   c                 ~    g | ]9}|                     d           r"|dd         v #|dd         v/|dd         :S )r   r-   Nr  )r   r   r   r>  s     rK   r   z/DiffusionPipeline.from_pipe.<locals>.<listcomp>/  sg     "
 "
 "
||C  "
 &'qrrUo%=%=!ABB%OaBaBa abbEBaBaBarJ   r   c                 Z    i | ]'\  }}|v	|                     d           rdnd  | |(S )r   r(  r?  )r   r   r   pipeline_kwargss      rK   r   z/DiffusionPipeline.from_pipe.<locals>.<dictcomp>@  sR     "
 "
 "
<@Aq_`hw_w_wQ\\#&&/rrC444a_w_w_wrJ   r   rG  rH  rI  z were passedrJ  )r   rI   )r   rg   r   r3   r   r   r   r  r   r[  rU   r  r   rV   r   r   r~   r   r   r   r   r   rX   rY   r   )r\  pipeliner\   r   r   r  r  r   true_optional_modulescomponent_typesr   r!  original_class_objr]   rF  original_pipe_kwargsadditional_pipe_kwargsr   unused_original_configrl  new_pipeliner   r   r=  r>  rA  s     `                  @@@@@rK   	from_pipezDiffusionPipeline.from_pipe  s   0 x//jj55 !**%6== **%6==&7RabbbNN N,/,C,CN,S,S)/ &s|44?
 #gggg:++--ggg!
 !
 )==??(7(;(;OT(R(R%VVVV6FVVV'288:: 	 	OD)'''D8H,H,H #9j99I/$*???!)dc6N.N.N/8&t,,NNT    &*9oo VefjVk os vz     XWWWWWW 
  
  
  
  
  
$))++ 
  
  
"
 "
 "
 "
 "
$))++"
 "
 "

 ( 	C 	CA&5&9&9'a''&B&B ##

 
 !
 #	

 
"
 "
 "
 "
DSDYDYD[D["
 "
 "

  !!(/001/&&(())* '(() 	 !## fN  f  f6F  f  fSVW[\l\q\q\s\sWtWtw{  }O  }T  }T  }V  }V  xW  xW  XW  TX  TX  f  f  f   &~8888(4++:W+XXX''AA*@AAA"OO+O...rJ   )TNF)Nr   rT   r   )r-  )7r@   rA   rB   rC   r  r  r   r~   ru  rS  r  rb   r   r   rj   r
   r   PathLikeboolr	   r   r   propertyr   r   r   classmethodr   rA  rr  rv  r{  intr  r  r  r  rO  r   r  r   r   staticmethodr)   r  r  r   r"  r$  r!  r2  r4  r1  rJ  __classcell__)rl   s   @rK   rP   rP      s}        " %K M "!H( ( () )C ) ) ) ) ) )$ $(!%!v vc2;./v !v #	v
 v v v vpO O Ob # # # # X# u{    X rHU3PRP[K[E\<] r r r  [rh ;c ; ; ; X;   X*  L- L-x} L-USXS_adSdMe L- L- L- L-\W W W;L ;LHSM ;LRWX]XdfiXiRj ;L ;L ;L ;Lz& & & q-%R[@P:Q q- q- q-  [q-f 5 5 [5 	 	 [	 !DcN ! ! ! X!F $ $ \$P P P P+ + +!M !MxPXGY !M !M !M !MF@ @ @ ?C- --)1();-	- - - -(&- &-8E#s(O3L &- &- &- &-P, , ,3hsm 3 3 3 3 x x [x x x x xrJ   rP   c                   l    e Zd ZdZd Zd Zd Zd Zdededed	efd
Z	d Z
ddedefdZddedefdZdS )StableDiffusionMixinzb
    Helper for DiffusionPipeline with vae and unet.(mainly for LDM such as stable diffusion)
    c                 8    | j                                          dS )z
        Enable sliced VAE decoding. When this option is enabled, the VAE will split the input tensor in slices to
        compute decoding in several steps. This is useful to save some memory and allow larger batch sizes.
        N)vaeenable_slicingrq  s    rK   enable_vae_slicingz'StableDiffusionMixin.enable_vae_slicing`      
 	!!!!!rJ   c                 8    | j                                          dS )z
        Disable sliced VAE decoding. If `enable_vae_slicing` was previously enabled, this method will go back to
        computing decoding in one step.
        N)rU  disable_slicingrq  s    rK   disable_vae_slicingz(StableDiffusionMixin.disable_vae_slicingg  s    
 	  """""rJ   c                 8    | j                                          dS )a  
        Enable tiled VAE decoding. When this option is enabled, the VAE will split the input tensor into tiles to
        compute decoding and encoding in several steps. This is useful for saving a large amount of memory and to allow
        processing larger images.
        N)rU  enable_tilingrq  s    rK   enable_vae_tilingz&StableDiffusionMixin.enable_vae_tilingn  s     	     rJ   c                 8    | j                                          dS )z
        Disable tiled VAE decoding. If `enable_vae_tiling` was previously enabled, this method will go back to
        computing decoding in one step.
        N)rU  disable_tilingrq  s    rK   disable_vae_tilingz'StableDiffusionMixin.disable_vae_tilingv  rX  rJ   s1s2b1b2c                     t          | d          st          d          | j                            ||||           dS )a5  Enables the FreeU mechanism as in https://arxiv.org/abs/2309.11497.

        The suffixes after the scaling factors represent the stages where they are being applied.

        Please refer to the [official repository](https://github.com/ChenyangSi/FreeU) for combinations of the values
        that are known to work well for different pipelines such as Stable Diffusion v1, v2, and Stable Diffusion XL.

        Args:
            s1 (`float`):
                Scaling factor for stage 1 to attenuate the contributions of the skip features. This is done to
                mitigate "oversmoothing effect" in the enhanced denoising process.
            s2 (`float`):
                Scaling factor for stage 2 to attenuate the contributions of the skip features. This is done to
                mitigate "oversmoothing effect" in the enhanced denoising process.
            b1 (`float`): Scaling factor for stage 1 to amplify the contributions of backbone features.
            b2 (`float`): Scaling factor for stage 2 to amplify the contributions of backbone features.
        unetz.The pipeline must have `unet` for using FreeU.)rb  rc  rd  re  N)rf   r   rg  enable_freeu)r[   rb  rc  rd  re  s        rK   rh  z!StableDiffusionMixin.enable_freeu}  sK    $ tV$$ 	OMNNN	"r:::::rJ   c                 8    | j                                          dS )z(Disables the FreeU mechanism if enabled.N)rg  disable_freeurq  s    rK   rj  z"StableDiffusionMixin.disable_freeu  s    	!!!!!rJ   Trg  rU  c                    d| _         d| _        |rFd| _         | j                                         | j                            t                                 |rqt          | j        t                    st          d          d| _        | j                                         | j                            t                                 dS dS )u  
        Enables fused QKV projections. For self-attention modules, all projection matrices (i.e., query, key, value)
        are fused. For cross-attention modules, key and value projection matrices are fused.

        <Tip warning={true}>

        This API is 🧪 experimental.

        </Tip>

        Args:
            unet (`bool`, defaults to `True`): To apply fusion on the UNet.
            vae (`bool`, defaults to `True`): To apply fusion on the VAE.
        FTzO`fuse_qkv_projections()` is only supported for the VAE of type `AutoencoderKL`.N)
fusing_unet
fusing_vaerg  fuse_qkv_projectionsset_attn_processorr   rV   rU  r   r   r[   rg  rU  s      rK   rn  z)StableDiffusionMixin.fuse_qkv_projections  s     ! 	B#DI**,,,I(()>)@)@AAA 	Adh66 t !rsss"DOH))+++H''(=(?(?@@@@@	A 	ArJ   c                    |rB| j         st                              d           n | j                                         d| _         |rE| j        st                              d           dS | j                                         d| _        dS dS )u.  Disable QKV projection fusion if enabled.

        <Tip warning={true}>

        This API is 🧪 experimental.

        </Tip>

        Args:
            unet (`bool`, defaults to `True`): To apply fusion on the UNet.
            vae (`bool`, defaults to `True`): To apply fusion on the VAE.

        zDThe UNet was not initially fused for QKV projections. Doing nothing.FzCThe VAE was not initially fused for QKV projections. Doing nothing.N)rl  r   r   rg  unfuse_qkv_projectionsrm  rU  rp  s      rK   rr  z+StableDiffusionMixin.unfuse_qkv_projections  s      	)# )effff	00222#(  	(? (deeeee//111"'	( 	(rJ   N)TT)r@   rA   rB   rC   rW  r[  r^  ra  floatrh  rj  rL  rn  rr  rI   rJ   rK   rS  rS  [  s         " " "# # #! ! !" " ";u ;% ;U ; ; ; ; ;," " "A A A4 A A A A>( (4 (T ( ( ( ( ( (rJ   rS  )br  r   r   r   r  r   dataclassesr   pathlibr   typingr   r   r   r   r	   r
   r   r   numpyrF   	PIL.ImagerD   r  r   huggingface_hubr   r   r   r   r   huggingface_hub.utilsr   r   	packagingr   requests.exceptionsr   	tqdm.autor   r(  r   configuration_utilsr   modelsr   models.attention_processorr   models.modeling_utilsr   r   schedulers.scheduling_utilsr   utilsr   r    r!   r"   r#   r$   r%   r&   r'   r(   r)   utils.hub_utilsr*   r+   utils.torch_utilsr,   	torch_npupipeline_loading_utilsr.   r/   r0   r1   r2   r3   r4   r5   r6   r7   r8   r9   r:   r;   r   	LIBRARIESr`   r  rL  
get_loggerr@   r   r>   rM   rP   rS  rI   rJ   rK   <module>r     s          				 				 



 ! ! ! ! ! !       S S S S S S S S S S S S S S S S S S S S                        M L L L L L L L       ) ) ) ) ) )             - - - - - - " " " " " " > > > > > > J J J J J J J J ? ? ? ? ? ?                          M L L L L L L L 2 2 2 2 2 2                                 $   	  GW"| 		H	%	% 
5 
5 
5 
5 
5* 
5 
5 
5 	 	 	 	 	* 	 	 	Y Y Y Y Y^ Y Y Yx6u( u( u( u( u( u( u( u( u( u(rJ   