
    biB                    D   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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l0m1Z1 ddl2m3Z3 ddl4m5Z5m6Z6 ddl7m8Z8 ddl9m:Z: ddl;m<Z< ddl=m>Z>m?Z?m@Z@mAZAmBZBmCZCmDZDmEZEmFZFmGZGmHZHmIZImJZJmKZK ddlLmMZMmNZNmOZO ddlPmQZQmRZRmSZS  eG       rd dlTZTddlUmVZVmWZWmXZXmYZYmZZZm[Z[m\Z\m]Z]m^Z^m_Z_m`Z`maZambZbmcZcmdZdmeZemfZfmgZgmhZhmiZimjZjmkZkmlZl  eD       rd dlmZmg ZneYD ]  Zoenj                  eo        dg eR       gz   Zq eJj                  es      Zte G d de@             Zue G d de@             Zv G d d      Zw G d  d!e/eA      Zx G d" d#      Zyy)$    N)	dataclass)Path)AnyCallableDictListOptionalUnionget_args
get_origin)	DDUFEntry	ModelCardcreate_repohf_hub_download
model_inforead_dduf_filesnapshot_download)OfflineModeIsEnabledvalidate_hf_hub_args)version)	HTTPError)tqdm)Self   )__version__)ConfigMixin)AutoencoderKL)FusedAttnProcessor2_0)_LOW_CPU_MEM_USAGE_DEFAULT
ModelMixin)PipelineQuantizationConfig)_check_bnb_status)SCHEDULER_CONFIG_NAME)CONFIG_NAMEDEPRECATED_REVISION_ARGS
BaseOutputPushToHubMixin_get_detailed_type_is_valid_typeis_accelerate_availableis_accelerate_versionis_hpu_availableis_torch_npu_availableis_torch_versionis_transformers_versionloggingnumpy_to_pil)%_check_legacy_sharding_variant_formatload_or_create_model_cardpopulate_model_card)empty_device_cache
get_deviceis_compiled_module   )ALL_IMPORTABLE_CLASSESCONNECTED_PIPES_KEYSCUSTOM_PIPELINE_FILE_NAMELOADABLE_CLASSES_download_dduf_file_fetch_class_library_tuple"_get_custom_components_and_folders_get_custom_pipeline_class_get_final_device_map_get_ignore_patterns_get_pipeline_class_identify_model_variants-_maybe_raise_error_for_incorrect_transformers#_maybe_raise_warning_for_inpainting/_maybe_warn_for_wrong_component_in_quant_config _resolve_custom_pipeline_and_cls_unwrap_model+_update_init_kwargs_with_connected_pipelinefilter_model_filesload_sub_modelmaybe_raise_or_warnvariant_compatible_siblingswarn_deprecated_model_variantbalancedc                   h    e Zd ZU dZeeej                  j                     ej                  f   e
d<   y)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__     ]/home/cdr/jupyterlab/.venv/lib/python3.12/site-packages/diffusers/pipelines/pipeline_utils.pyrR   rR   t   s*     $syy'344r^   rR   c                   0    e Zd ZU dZej
                  ed<   y)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)rT   rU   rV   rW   rZ   r[   r\   r]   r^   r_   ra   ra      s     JJr^   ra   c                   &     e Zd ZdZdZ fdZ xZS )DeprecatedPipelineMixina7  
    A mixin that can be used to mark a pipeline as deprecated.

    Pipelines inheriting from this mixin will raise a warning when instantiated, indicating that they are deprecated
    and won't receive updates past the specified version. Tests will be skipped for pipelines that inherit from this
    mixin.

    Example usage:
    ```python
    class MyDeprecatedPipeline(DeprecatedPipelineMixin, DiffusionPipeline):
        _last_supported_version = "0.20.0"

        def __init__(self, *args, **kwargs):
            super().__init__(*args, **kwargs)
    ```
    Nc                     | j                   j                  }t        | j                   dt              }t        j                  d| d| d       t        |   |i | y )N_last_supported_versionzThe z_ has been deprecated and will not receive bug fixes or feature updates after Diffusers version z. )	__class__rT   getattrr   loggerwarningsuper__init__)selfargskwargs
class_nameversion_inforg   s        r_   rl   z DeprecatedPipelineMixin.__init__   sn    ^^,,
 t~~/H+V 	:,}  K  ~L  LN  O	

 	$)&)r^   )rT   rU   rV   rW   rf   rl   __classcell__rg   s   @r_   rd   rd      s    $ #* *r^   rd   c                       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	 	 	 	 d2d	eeej"                  f   d
edee   deeeef      def
dZdefdZedej4                  fd       Zedej6                  fd       Zeedeeeej"                  f      defd              Zedefd       Zed        Z d Z!d3dee   deej4                  ef   fdZ"d Z#d3dee   deej4                  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,ejZ                  j\                  d3d#       Z/d$ Z0d4d%ee1   fd&Z2d' Z3	 d4d(ed%ee1   ddfd)Z4d5d*eeeef      fd+Z5d, Z6d*ee   fd-Z7ed.        Z8	 d6d/ed0eejr                  jt                     defd1Z; xZ<S )7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                     |j                         D ]Z  \  }}|t        |t        t        f      r
|d   |di}nt	        |      \  }}|||fi} | j
                  di | t        | ||       \ y Nr   NNr]   )items
isinstancetuplelistr>   register_to_configsetattr)rm   ro   namemoduleregister_dictlibraryrp   s          r_   register_modulesz"DiffusionPipeline.register_modules   s    "LLN 	(LD&~FUDM!BvayGX!%| 4&@&H#!%'< = $D##4m4 D$'	(r^   r   valuec                 X   || 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        | )  ||       y rx   )__dict__hasattrconfigr{   rh   r|   r}   r>   r~   rk   __setattr__)rm   r   r   class_library_tuplerg   s       r_   r   zDiffusionPipeline.__setattr__   s    4== WT[[$%?'$++t4udmD$T):1)=)I*DU*K'*6''''F41D*EF'''84-8D%(r^   save_directorysafe_serializationvariantmax_shard_sizepush_to_hubc                     " t         j                        }|j                  dd       |j                  dd       |j                  dd       |j                  dd       |r|j                  dd      }|j                  dd      }	|j                  dd	      }
|j                  d
d      }|j                  d|j                  t        j
                  j                        d         }t        |d|	|      j                  } j                         \  "}" fd}|j                         D ci c]  \  }} |||      s|| }}}|j                         D ]  }t         |      }|j                  }t        |      rt        |      }|j                  }d}t!        j                         D ]  \  }}|t"        j$                  v rt'        j(                  |      }n t*        j-                  | d| d| d|        |j                         D ](  \  }}t        |d      }|t/        ||      s#|d   } n | n |>t*        j1                  d| d| dt3        |       d         j4                  di |di #t        ||      }t7        j8                  |      }d|j:                  v }d|j:                  v }d|j:                  v }i } |r|| d<   |r|| d<   |r||| d<    |t        j
                  j=                  ||      fi |    j?                  |       |r_tA        d      }!tC        |!      }!|!jE                  t        j
                  j=                  |d              jG                  |||
       yyc c}}w ) 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`.
            max_shard_size (`int` or `str`, defaults to `None`):
                The maximum size for a checkpoint before being sharded. Checkpoints shard will then be each of size
                lower than this size. If expressed as a string, needs to be digits followed by a unit (like `"5GB"`).
                If expressed as an integer, the unit is bytes. Note that this limit will be decreased after a certain
                period of time (starting from Oct 2024) to allow users to upgrade to the latest version of `diffusers`.
                This is to establish a common default size for this argument across different libraries in the Hugging
                Face ecosystem (`transformers`, and `accelerate`, for example).
            push_to_hub (`bool`, *optional*, defaults to `False`):
                Whether or not to push your model to the Hugging Face 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private	create_prFtokenrepo_idT)exist_okr   r   c                 8    | vry| j                   v r|d   yy)NFr   T)_optional_components)r   r   expected_modulesrm   s     r_   is_saveable_modulez=DiffusionPipeline.save_pretrained.<locals>.is_saveable_module   s,    ++t000U1X5Er^   z is not installed. Cannot save  as z from r   zself.=z	 of type z cannot be saved.ry   r   r   r   )r   is_pipeline	README.md)r   r   r   r]   )$dictr   popsplitospathsepr   r   _get_signature_keysrz   keysrh   rg   r7   rI   r<   sysmodules	importlibimport_moduleri   info
issubclassrj   typer~   inspect	signature
parametersjoinsave_configr3   r4   save_upload_folder)#rm   r   r   r   r   r   ro   model_index_dictr   r   r   r   r   optional_kwargsr   kv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_method_accept_max_shard_sizesave_kwargs
model_cardr   s#   `                                 @r_   save_pretrainedz!DiffusionPipeline.save_pretrained   s   H  ,]D1148Y-_d3#ZZ(8$?NjjD1G

;6IJJw-EjjN,@,@,Mb,QRG!'D'QVW__G,0,D,DT,J)/	 .>-C-C-EbTQI[\]_`IaAqDbb'7'<'<'> 6	^#&=>I!++I "),))4	%//	#1A1G1G1I -o3;;.'55lCGKK'.(GH_G``detduu{  }I  |J  K 6E5J5J5L 1J 1&-gz4&HO&2z)_7]+<Q+?( $/"  '34Ai[	$y/IZZkl (''R+BL*QR!)-=>K %,$5$5k$B!&:>S>^>^&^#)26K6V6V)V&0@DYDdDd0d-K&4F01))0I&0^5O0>,-^5LM]Q\]m6	^r 	(27%UYZJ,Z8JOOBGGLLEF-#    y cs   ,M:>M:returnc                 4
   |j                  dd      }|j                  dd      }|j                  dd      }d}d}t        |      dk(  rCt        |d   t        j                        r|d   }n|d   t        j
                  |d         nd}ntt        |      dk(  rMt        |d   t        j                        rt        d	      |d   t        j
                  |d         nd}|d   }nt        |      dkD  rt        d
      ||t        d      |xs |}||t        d      |xs |}|t        j
                  |      j                  nd}t        d | j                  j                         D              }	d d t        fd| j                  j                         D              }
| j                  duxr t        | j                        dkD  }|rt        d      |dv r(|
r|	st        d      |	rt        dd      rt        d      t        fd| j                  j                         D              }|rD|dv r@t        j                  ddj                  | j                  j!                                d       |dk(  r|j                  dd      rt#               rdt$        j&                  d<   t        j)                  d        ddl}t-        t        d      rt        j.                  j1                         st        d!      dt$        j&                  d"<   t        j)                  d#       | j3                  |       \  }}|D cg c]  }t5        | |d       }}|D cg c])  }t        |t        j6                  j8                        s(|+ }}|xs |
}|D ]t  }t;        |      \  }}}| j=                  |$      }|s|r@|>t        j                  d%|j>                  j@                   d&|rd'nd( d)| d*|rd'nd( d+	       |r?|=t        j                  d%|j>                  j@                   d,| d-|j
                   d.       | j=                  d|/      r2|0t        j                  d%|j>                  j@                   d0| d1       |r!|tC        d2d3      r|jE                  |4       n|s|s|s|jE                  ||       |j                  t        jF                  k(  sItI        |      d5v sX|r\|r`t        j                  d6       w | S c c}w c c}w )7ug  
        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_warningsFr8   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              3   J   K   | ]  \  }}t        t        |              y wN)anyr"   ).0_r   s      r_   	<genexpr>z'DiffusionPipeline.to.<locals>.<genexpr>  s     iIAvs$5f$=?is   !#c                 v   t               rt        dd      ryt        |       \  }}}|ryt        | d      xr t	        | j
                  t        j                  j                        xsS t        | j
                  d      xr; t	        | j
                  j                  d   t        j                  j                        S )N<0.14.0F_hf_hookhooksr   )	r*   r+   r"   r   r{   r   
accelerater   AlignDevicesHook)r   r   is_loaded_in_8bit_bnbs      r_    module_is_sequentially_offloadedz>DiffusionPipeline.to.<locals>.module_is_sequentially_offloaded  s    *,0Ec80T*;F*C'Aq'$6:. 6??J,<,<,M,MN \6??G4 \v44Q79I9I9Z9Z[r^   c                     t               rt        dd      ryt        | d      xr. t        | j                  t
        j                  j                        S )Nr   0.17.0.dev0Fr   )r*   r+   r   r{   r   r   r   
CpuOffloadr   s    r_   module_is_offloadedz1DiffusionPipeline.to.<locals>.module_is_offloaded  s>    *,0Ec=0Y6:.k:foozO_O_OjOj3kkr^   c              3   4   K   | ]  \  }} |        y wr   r]   )r   r   r   r   s      r_   r   z'DiffusionPipeline.to.<locals>.<genexpr>  s       1
9BF,V41
   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()` to remove the existing device map from the pipeline.)cudaxpua7  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.r   z
1.1.0.dev0zYou are trying to call `.to('cuda')` on a pipeline that has models quantized with `bitsandbytes`. Your current `accelerate` installation does not support it. Please upgrade the installation.c              3   4   K   | ]  \  }} |        y wr   r]   )r   r   r   r   s      r_   r   z'DiffusionPipeline.to.<locals>.<genexpr>  s     #iIAv$7$?#ir   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.hpuhpu_migrationT1PT_HPU_GPU_MIGRATIONz0Environment variable set: PT_HPU_GPU_MIGRATION=1zBYou are trying to call `.to('hpu')` but HPU device is unavailable.PT_HPU_MAX_COMPOUND_OP_SIZEz7Environment variable set: PT_HPU_MAX_COMPOUND_OP_SIZE=1r   zThe module 'z$' has been loaded in `bitsandbytes` 4bit8bitz and conversion to z& is not supported. Module is still in z precision.z:' has been loaded in `bitsandbytes` 8bit and moving it to z2 via `.to()` is not supported. Module is still on .)raise_errorr   z&' is group offloaded and moving it to z via `.to()` is not supported.>z4.44.0r   )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   lenr{   torchr   r   
ValueErrorr   r   
componentsrz   hf_device_mapr+   ri   rj   r   r   r,   r   environdebughabana_frameworks.torchr   r   is_availabler   rh   nnModuler"   *_maybe_raise_error_if_group_offload_activerg   rT   r/   tofloat16str)rm   rn   ro   r   r   r   	dtype_arg
device_argdevice_typepipeline_has_bnb"pipeline_is_sequentially_offloadedis_pipeline_device_mappedpipeline_is_offloadedhabana_frameworksmodule_namesr   nr   mis_offloadedr   is_loaded_in_4bit_bnbr   is_group_offloadedr   r   s                           @@r_   r  zDiffusionPipeline.toq  s   H 

7D)Hd+!',De!L	
t9>$q'5;;/ G	6:1g6IU\\$q'2t
Y!^$q'5;;/ x  37q'2Ed1g.4JQIY]opp!6y  "*"8z  %:393Eell6*//4iQUQ`Q`QfQfQhii		l .1 1
FJooF[F[F]1
 .
* %)$6$6d$B$bs4K]K]G^abGb!$ p  /)1:J  N  "&;C&N  U 
 !$#iQUQ`Q`QfQfQh#i i [O%CNN H  IM  IR  IR  SW  Sb  Sb  Sg  Sg  Si  Ij  Hk  kk  l
 %FJJ$EJZJ\14BJJ-.LLKL* E5)eii.D.D.F !eff8;BJJ45LLRS2248a3?@a74D)@@%HAuxx)G1HH,R0R +	F>OPV>W;A$&;!%!P!PX^!P!_%)>EDU"6#3#3#<#<"==a  mBbh  HN  bO  Ob  ch  bi  iO  Zo  PV  u{  O|  |G  H %);"6#3#3#<#<"==wx~w  @r  sy  s@  s@  rA  AB  C ??EZ`?a&"6#3#3#<#<"==cdjck  lJ  K %);@WX[]e@f			(*3HQc		&%( -K7*.$bK+	X a AHs   T)TTc                 ,   | j                  |       \  }}|D cg c]  }t        | |d       }}|D cg c])  }t        |t        j                  j
                        s(|+ }}|D ]  }|j                  c S  t        j                  d      S c c}w c c}w )zi
        Returns:
            `torch.device`: The torch device on which the pipeline is located.
        Nr   )r   rh   r{   r   r  r  r   rm   r  r   r  r   r  r   s          r_   r   zDiffusionPipeline.device.  s     2248a3?@a74D)@@%HAuxx)G1HH 	!F== 	! ||E"" AHs   B)BBc                 "   | j                  |       \  }}|D cg c]  }t        | |d       }}|D cg c])  }t        |t        j                  j
                        s(|+ }}|D ]  }|j                  c S  t        j                  S c c}w c c}w )zg
        Returns:
            `torch.dtype`: The torch dtype on which the pipeline is located.
        N)r   rh   r{   r   r  r  r   float32r  s          r_   r   zDiffusionPipeline.dtype=  s     2248a3?@a74D)@@%HAuxx)G1HH 	 F<<	  }} AHs   B)BBpretrained_model_name_or_pathc                 l  B |j                         }|j                  dd      }|j                  dd      }|j                  dd      }|j                  dd      }|j                  dd      }|j                  dd      }	|j                  d	d      }
|j                  d
d      }|j                  dd      }|j                  dd      }|j                  dd      }|j                  dd      }|j                  dd      }|j                  dd      }|j                  dd      }|j                  dd      }|j                  dd      }|j                  dt              }|j                  dd      }|j                  dd      }|j                  dd      }|j                  dd      }|j                  dd      }|j                  dd      }|St        |t              sCt        |t
        j                        s)t
        j                  }t        j                  d| d       |r!t               sd}t        j                  d       |t        |t              s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%      |+|t         vr#t        | d&d'j#                  t                      ||t         v rt%        d(d)      rt        d*      |du r|t        d+| d,      |r|rt        d-      |rt        d.      t&        j(                  j+                  |      sF|j-                  d/      d0kD  rt        d1| d2       | j.                  |f||||||	|
|||||||d3|}n|}|(t1        ||4      rd5| d6}t        j                  |       d}|r-t&        j(                  j#                  ||      }t3        |      }d7}| j5                  ||8      } |rt7        |        | j                  d9d       t9        ||| :      }!t;        |!      d;k(  r|d<| d=}"t        |"      t=        || |>      \  }}#t?        | | |||#||?      }$||$j@                  rt        d@      tC        |$|| A       | jE                  |$      \  }%}&|$jG                         }'|%D (ci c]  }(|(|v s|(|j                  |(       c}(B|&D (ci c]  }(|(|v s|(|j                  |(       })}( |$jH                  | fi |\  }*}+},|&D (ci c]&  }(|(|*v r |(|$jJ                  vr|(|*j                  |(      ( }-}(i |-|)}-BfdB}.|*jM                         D (/ci c]  \  }(}/ |.|(|/      s|(|/ }*}(}/|
rdC|*v rdCBvrt        dD      t;        |+      d;kD  r&t        j                  dE|+ dF|$jN                   dG       d;dHl(m)}0 d}1|tU        ||$B|*tV        ||||||||	I      }1d}2tY        |*|       t[        j\                  |*jM                         dJK      D ]Y  \  }3\  }4}5|1Lt        |1t              r*t;        |1      d;kD  r|1j_                  |3d      }6|6d7|6i}2nd}2nt        |1t              r|1}2|5ja                  dL      r|5dMd n|5}5tc        |0|4      }7td        }8d}9|3Bv rtg        |4tV        |5|8B|3|7       B|3   }9nt        |t              r0|j_                  |3|j_                  dNt
        j                              n|}:ti        dki dO|4dP|5dQ|8dR|0dS|7dT|$d
|:d|d|d|2d|d|d|dU|!dV|3d	|
d|d|dW|d|dX|d|d|}9t        jk                  dY|3 dZ|5 d[|3 d\| d]	       |9|-|3<   \ |$j@                  rMt&        j(                  jm                  t&        j(                  j#                  |d^            rto        dk|-|)B|d_|}-tq        |%      tq        |-js                               z
  };tu        Bjs                               }<|$jJ                  }=t;        |;      d;kD  r.|;tq        |<|=z         k  r|;D ]  }>Bj_                  |>d      |-|><    nkt;        |;      d;kD  r]tq        tu        |-js                               tu        Bjs                               z         tq        |&      z
  }<t        d`|$ da|% db|< dc      |-jM                         D ]o  \  }?}@dd|?v rde|?v r@|'|?   tv        jx                  jz                  fk(  r5t}        @|'|?         rEt        j                  df|? dg|'|?    dht        @       d]       q  |$dki |-}A|Aj                  |i       |t        Adj|1       |t        Ad|       AS c c}(w c c}(w c c}(w c c}/}(w )lu%  
        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 stable-diffusion-v1-5/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`].
                    - A path to a *directory* (for example `./my_pipeline_directory/`) containing a dduf file
            torch_dtype (`torch.dtype` or `dict[str, Union[str, torch.dtype]]`, *optional*):
                Override the default `torch.dtype` and load the model with another dtype. To load submodels with
                different dtype pass a `dict` (for example `{'transformer': torch.bfloat16, 'vae': torch.float16}`).
                Set the default dtype for unspecified components with `default` (for example `{'transformer':
                torch.bfloat16, 'default': torch.float16}`). If a component is not specified and no default is set,
                `torch.float32` is used.
            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.

            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`, *optional*):
                Strategy that dictates how the different components of a pipeline should be placed on available
                devices. Currently, only "balanced" `device_map` is supported. Check out
                [this](https://huggingface.co/docs/diffusers/main/en/tutorials/inference_with_big_models#device-placement)
                to know more.
            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`.
            dduf_file(`str`, *optional*):
                Load weights from the specified dduf file.

        <Tip>

        To use private or [gated](https://huggingface.co/docs/hub/models-gated#gated-models) models, log-in with `hf
        auth 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("stable-diffusion-v1-5/stable-diffusion-v1-5")

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

        >>> scheduler = LMSDiscreteScheduler.from_config(pipeline.scheduler.config)
        >>> pipeline.scheduler = scheduler
        ```
        	cache_dirNforce_downloadFproxieslocal_files_onlyr   revision	from_flaxtorch_dtypecustom_pipelinecustom_revisionprovidersess_optionsprovider_options
device_map
max_memoryoffload_folderoffload_state_dictlow_cpu_mem_usager   	dduf_fileuse_safetensorsuse_onnxload_connected_pipelinequantization_configzPassed `torch_dtype` z7 is not a `torch.dtype`. Defaulting to `torch.float32`.a,  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
```
.zJ`quantization_config` must be an instance of `PipelineQuantizationConfig`.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`.;Custom pipelines are not supported with DDUF at the moment.>Connected pipelines are not supported with DDUF at the moment./r8   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   r"  r#  r0  r1  r%  r&  r   r/  r2  )folderr   BWarning: The repository contains sharded checkpoints for variant '  ' maybe in a deprecated format. Please check your files carefully:

- Correct format example: diffusion_pytorch_model.fp16-00003-of-00003.safetensors
- Deprecated format example: diffusion_pytorch_model-00001-of-00002.fp16.safetensors

If you find any files in the deprecated format:
1. Remove all existing checkpoint files for this variant.
2. Re-obtain the correct files by running `save_pretrained()`.

This will ensure you're using the most up-to-date and compatible checkpoint format. )dduf_entries_ignore_files)r8  r   r   r   z7You are trying to load the model files of the `variant=z,`, but no such modeling files are available.)r8  r   r%  )r   r2  r%  rp   r  r"  z:`device_map` is not yet supported for connected pipelines.)pipeline_classr  r   c                 &    |d   y| v r|    yy)Nr   FTr]   )r   r   passed_class_objs     r_   load_modulez6DiffusionPipeline.from_pretrained.<locals>.load_module  s*    Qx'',<T,B,Jr^   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@  	init_dictr   r+  r$  cached_folderr  r   r!  r   r"  zLoading pipeline components...)descFlax   defaultr   rp   importable_classesrC  is_pipeline_moduler>  model_variantsr   rE  r<  zLoaded r   z from `z` subfolder of r   r   )init_kwargspassed_pipe_kwargspassed_class_objsr8  	Pipeline 
 expected , but only z were passed.	scheduler	tokenizerzExpected types for z: z, got r   r   r]   )Bcopyr   r   r{   r   r   r   r  ri   rj   r*   r!   r   r.   NotImplementedErrorr	  SUPPORTED_DEVICE_MAPr   r+   r   r   isdircountdownloadr2   r   load_configrE   rD   r   rH   rC   _load_connected_pipesrF   r   _get_signature_typesextract_init_dictr   rz   rT   	diffusersrC  rA   r   rG   r0   r   get
startswithr   r9   rM   rL   r   isfilerJ   setr   r}   r   	Signatureemptyr)   r(   r~   r   )Cclsr  ro   kwargs_copiedr  r  r   r!  r   r"  r#  r$  r%  r&  r'  r(  r)  r*  r+  r,  r-  r.  r   r/  r0  r1  r2  r3  rE  warn_msgr<  dduf_file_pathconfig_dictrL  error_messagecustom_class_namer>  r   r   expected_typesr   rN  rD  unused_kwargsr   rM  rA  r   rC  final_device_mapcurrent_device_mapr   r   rp   component_devicerK  rJ  loaded_sub_modelsub_model_dtypemissing_modulespassed_modulesoptional_modulesr   kwargmodelr@  sC                                                                     @r_   from_pretrainedz!DiffusionPipeline.from_pretrainedL  s   n JJ{D1	$4e<**Y-!::&8$?

7D)::j$/JJ{E2	jj5 **%6= **%6=::j$/zz.$7!::&8$?ZZd3
ZZd3
$4d;#ZZ(<dC"JJ':<VW**Y-JJ{D1	 **%6=::j$/"(**-F"N$jj)>E":k4+HQ[\ginititQu--KNN'}4kl %<%> %NN. *:>QSm3nijj$-=dG-L%. 
 !*:4*I%& 
 !*A*C%z  !*Z*E=>>!j8L&L%,HSgIhHij  !j4H&H$S(3)*mnn%**@UV`Ua bR R 
 )*ghh&)*jkk ww}}:;,2237!; BC`Ba bf f  )CLL-#-!1!# /! / /#(?  !M& :M #HP]gn#oTU\T] ^f f  NN8$WW\\-CN).9LMoom,oO9+F 	. 2PW`kl~!#(;UV]U^  _K  LM]++ .N o.
** -$;+($
 !n&J&J%&bcc
 	,)*G	
 -0,C,CN,S)/'<<>6FV!v+Avzz!},V8GW11PV;aA.WW&Fn&F&F{&]V\&]#	=!
 %
I~!>+N+N"N y}}Q
 

 <;(:;	 '0oo&7Mda;q!;LQTM	M )Y6;KSc;c%.  }!NN$]O3HI`I`Haavw
 	(  !4%-!1#%'+-!1! " "7	CVW07Y__=NUu0v A	1,D,<+.5#>N:ORS:S'7';';D$'G$'3.02B-C*-1* 0#6)9& ,6+@+@+HABjJ ")L!A!7# '' $ ':7IK[]acu $4D#9 
 "+t4  OOD+//)U]]*ST$  
 $2 $!-$)$ (:$ (	$
 (:$ $2$ !0$ &$ ".$  2$  *$ $2$ (:$ $2$ $  (!$" $#$$ '8%$& #0'$( %4)$* ".+$, &6-$. )</$ 2 dV4
|74&PmOnnop !1KCA	1H //BGGNN277<<P]_jCk4lE '#5"2$	
  K ./#k6F6F6H2II.3356)>>!#3~P`?`;a(a) I&6&:&:64&HF#I!A% k&6&6&8!9DAQAVAVAX<Y!YZ]`ap]qqNN+:6F5G{SaRbbop 
 #((* 	qGBb  "&r*w/@/@/F/F.HH&sN2,>?!4RD>";M:NfUghkUlTmmnop	q  -- 	  /L M!E?,<=*E02EFa WW
 Ns*   	f!!f!<	f&f&7+f+f0f0c                 0    t        | j                  dd       S )Nr   )rh   r   rm   s    r_   name_or_pathzDiffusionPipeline.name_or_pathR  s    t{{OT::r^   c                    ddl m} | j                  j                         D ]4  \  }}t	        |t
        j                  j                        s+	  ||      c S  | j                  j                         D ]  \  }}t	        |t
        j                  j                        r|| j                  v r9t        |d      s| j                  c S |j                         D ]i  }t        |d      st        |j                  d      s'|j                  j                  >t        j                  |j                  j                        c c S   | j                  S # t        $ r Y :w xY w)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   )_get_group_onload_devicer   execution_device)hooks.group_offloadingr  r   rz   r{   r   r  r  r   _exclude_from_cpu_offloadr   r   r   r   r  )rm   r  r   rz  r   s        r_   _execution_devicez#DiffusionPipeline._execution_deviceV  s"    	F
  ??002 	KD%eUXX__5/66		  ??002 	JKD%eUXX__5A_A_9_5*-{{"--/ JFJ/1CD88D <<(H(HIIJ	J {{!  s   E	EEc                     | j                   j                         D ]X  \  }}t        |t        j                  j
                        s+t        |d      s8t        j                  j                  |d       Z g | _
        y)z}
        Removes all hooks that were added when using `enable_sequential_cpu_offload` or `enable_model_cpu_offload`.
        r   T)recurseN)r   rz   r{   r   r  r  r   r   r   remove_hook_from_module
_all_hooks)rm   r   rz  s      r_   remove_all_hooksz"DiffusionPipeline.remove_all_hooksy  sc     --/ 	NHAu%1geZ6P  888M	N r^   gpu_idr   c                 <   | j                  d       | j                  duxr t        | j                        dkD  }|rt        d      | j                  t        d      t               rt        dd      rd	d
lm} nt        d      | j                          |t               }|dk(  rt        d      t        j                  |      }|j                  }| |t        d| d| d|j                          |xs |j                  xs t#        | dd	      | _        |j                   }t        j                  | d| j$                         }|| _        | j)                  dd       t+        |j                          | j,                  j/                         D 	ci c]-  \  }}	t1        |	t        j2                  j4                        s+||	/ }
}}	g | _        d}| j                  j9                  d      D ]  }|
j;                  |d      }t1        |t        j2                  j4                        s:t=        |      \  }}}|r.t>        jA                  d|jB                  jD                   d       y ||||      \  }}| j6                  jG                  |        |
j/                         D ]q  \  }}t1        |t        j2                  j4                        s+|| jH                  v r|j)                  |       K |||      \  }}| j6                  jG                  |       s yc c}	}w )a  
        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 accelerator when its
        `forward` method is called, and the model remains in accelerator 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 None):
                The PyTorch device type of the accelerator that shall be used in inference. If not specified, it will
                automatically detect the available accelerator and use.
        Tr   Nr8   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.r4  r   r   )cpu_offload_with_hookzC`enable_model_cpu_offload` requires `accelerate v0.17.0` or higher.r   z>`enable_model_cpu_offload` requires accelerator, but not found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   z->z$Skipping the hook placement for the z( as it is loaded in `bitsandbytes` 8bit.)prev_module_hook)%r  r   r   r   model_cpu_offload_seqr*   r+   r   r  ImportErrorr  r6   RuntimeErrorr   r   indexr   rh   r  _offload_devicer  r5   r   rz   r{   r  r  r  r   r   r"   ri   r   rg   rT   appendr  )rm   r  r   r  r  torch_devicedevice_indexr  r   r   all_model_componentshook	model_strrz  r   r   r   s                    r_   enable_model_cpu_offloadz*DiffusionPipeline.enable_model_cpu_offload  s    	77D7I$($6$6d$B$bs4K]K]G^abGb!$ g  %%-p  #$)>t])S8cdd>\F"#cdd||F+#)),":08lmslt J  KW  K\  K\  J]^   &b););bwtM^`a?b"''Qt/C/C.DEF%d36;;'151F1F1HkAJWXZ_ZbZbZiZiLj1kk3399$? 	)I(,,Y=EeUXX__5 +<E*B'Aq'$:5??;S;S:TT|} +E6DQGAtOO""4(	)( 0557 	-KD%eUXX__5t555 /v>4&&t,	-1  ls   ,LLc                     | j                   j                         D ]  }t        |d      s|j                          ! t        | d      rt	        | j
                        dk(  ry| j                  t        | dd             y)aV  
        Method that performs the following:
        - 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.
        - Resets stateful diffusers hooks of denoiser components if they were added with
          [`~hooks.HookRegistry.register_hook`].

        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`.
        _reset_stateful_cacher  r   Nr  r   r   )r   valuesr   r  r   r  r  rh   )rm   	components     r_   maybe_free_model_hooksz(DiffusionPipeline.maybe_free_model_hooks  ss     //1 	2Iy"9://1	2 t\*c$//.Ba.G 	%%WT;Lf-U%Vr^   c                 $   | j                  d       t               rt        dd      rddlm} nt        d      | j                          | j                  duxr t        | j                        d	kD  }|rt        d
      |t               }|dk(  rt        d      t        j                  |      }|j                  }| |t        d| d| d|j                         |xs |j                  xs t!        | dd      | _        |j                  }t        j                  | d| j"                         }|| _        | j                  j                  dk7  r4| j                  j                  }| j'                  dd       t)        |       | j*                  j-                         D ]m  \  }	}
t/        |
t        j0                  j2                        s+|	| j4                  v r|
j'                  |       Kt        |
j6                        dkD  } ||
||       o y)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 accelerator 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 None):
                The PyTorch device type of the accelerator that shall be used in inference. If not specified, it will
                automatically detect the available accelerator and use.
        Tr  r4  r   r   )cpu_offloadzG`enable_sequential_cpu_offload` requires `accelerate v0.14.0` or higherNr8   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   zC`enable_sequential_cpu_offload` requires accelerator, but not foundr  r  r  r  r  r  )offload_buffers)r  r*   r+   r   r  r  r  r   r   r   r6   r  r   r   r  r   rh   r  r  r  r5   r   rz   r{   r  r  r  _parameters)rm   r  r   r  r  r  r  r  orig_device_typer   rz  r  s               r_   enable_sequential_cpu_offloadz/DiffusionPipeline.enable_sequential_cpu_offload  s    	77D7I"$)>tX)N.ghh$($6$6d$B$bs4K]K]G^abGb!$ q  >\F"#hii||F+#)),":08lmslt J  KW  K\  K\  J]^   &b););bwtM^`a?b"''Qt/C/C.DEF%;;u$#{{//GGE$G7/0??002 
	LKD%eUXX__5t555  #&e&7&7"81"<E6?K
	Lr^   c                     | j                   y| j                          | j                  j                         D ];  \  }}t	        |t
        j                  j                        s+|j                  d       = d| _         y)z:
        Resets the device maps (if any) to None.
        Nr   )	r   r  r   rz   r{   r   r  r  r  )rm   r   r  s      r_   reset_device_mapz"DiffusionPipeline.reset_device_map9  sg     %!!##'??#8#8#: (ii9LL'( "&Dr^   c                 P  ); |j                  dd      }|j                  dd      }|j                  dd      }|j                  dd      }|j                  dd      }|j                  dd      }|j                  d	d      }	|j                  d
d      }
|j                  dd      }|j                  dd      }|j                  dd      }|j                  dd      }|j                  dd      }|j                  dd      }|j                  dd      }|r7|
rt        d      |rt        d      t        ||| j                  |||||      S ||du rdnd}||nd}d}d}d}|s	 t	        |||      }|st        || j                  |||||      }| j                  |      }|j                  dg       }j                  D ch c]  }|j                   }}|(t!        ||      rd| d}t        j                  |       t#        |      t#        |      z
  }|t$        v r[t'        j(                  t'        j(                  t*              j,                        t'        j(                  d      k\  rt/        |||||       t1        ||||      \  }}d} |
)t3        |d   t4        t6        f      r|d   d    }
|d   d!   } |
duxr |
 d"|v }!t9        |      d kD  }"|!r|st;        d#| d$|
 d%| d&|
 d'	      |"r|st;        d#| d$d(j=                  |j?                         D #$cg c]%  \  }#}$t@        jB                  j=                  |#|$      ' c}$}#       d)d*j=                  |j?                         D #$cg c]  \  }#}$d+| d,|# d,|$ d" c}$}#       d-      tE        | |||
|!r|nd|| ||.	      }%| jG                  |%      \  }&}'|&D #cg c]	  }#|#|v s|# }(}#tI        |      D )ch c]I  })t@        jB                  jK                  |)      d    |v s(t@        jB                  jK                  |)      d    K }*})tM        |(|*|||	|||%jN                  |	      }tQ        |||/      \  }+},t5        |+      }||D #cg c]  }#|#|*vs|# d0 c}#z  }||j?                         D #)cg c]  \  }#})|# d,|) d" c})}#z  }||
 d"|v r|
 d"gng z  }||*D #cg c]"  }#t@        jB                  j=                  |#d1      $ c}#z  }|tR        tT        | j                  tV        gz  }|D -cg c]8  }-t9        |-jK                  d,            d2k(  r|-jK                  d,      d    |(v r7|-: }}-|%jX                  r|j[                  d3       ||D .cg c]  }.|. d4	 c}.z   }|D -cg c]*  }-t]        j^                  ta        jb                  |-            , }/}-|D -cg c]*  }-t]        j^                  ta        jb                  |-            , }0}-|D ))cg c]  )te        )fd5|/D              r) }1})|1D ))cg c]  )te        )fd6|0D              s) }1})tg        |      jh                  ;tk        ;fd7|1D              }2|2r|s;S d8| j                  i}3|
|
jm                  d"      s|
|3d
<   	 to        |||||||||39	      }4| jq                  t@        jB                  j=                  |4d:            js                  dd      }5t3        |5tt              r|5jw                  d;      r|5d<d n|5}5ty        jz                  t        jK                  d=      d          }6t3        |5tt              rt}        |6|5d      nd}%|%|%jX                  rt        j                  t@        jB                  j=                  |4d3            }7t        t        D #cg c]  }#t}        |7j                  |#g        c}#g       }8|8D ]"  }9|||||||d>}:t        j                  |9fi |: $ |4S # t
        t        t        j                  f$ r(}t        j                  d| d       d}|}Y d}~d}~ww xY wc c}w c c}$}#w c c}$}#w c c}#w c c})w c c}#w c c})}#w c c}#w c c}-w c c}.w c c}-w c c}-w c c})w c c})w c c}#w # t        $ r | t        d?| d@      |w xY w)Au&  
        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.

            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`.
            dduf_file(`str`, *optional*):
                Load weights from the specified DDUF file.
            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 `hf
        auth login

        </Tip>

        r  Nr  Fr   r!  r   r"  r#  r%  r&  r   r0  r1  r2  trust_remote_coder/  r5  r6  )pretrained_model_namer/  pipeline_class_namer  r   r!  r   r"  T)r   r"  zCouldn't connect to the Hub: z$.
Will try to load from local cache.)r  r"  r   r  r   r=  )	filenamesr   r9  r:  z0.22.0r   r   r8   z.pyz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, z_ which must be executed to correctly load the model. You can inspect the repository content at r   zhttps://hf.co/r7  zS.
Please pass the argument `trust_remote_code=True` to allow custom code to be run.)r2  r%  r   hub_revisionrp   r  r"  )r   ignore_patternsz/*zconfig.jsonr   r   z.index.*jsonc              3   @   K   | ]  }|j                          y wr   matchr   pfs     r_   r   z-DiffusionPipeline.download.<locals>.<genexpr>O  s     =dQaggaj=d   c              3   @   K   | ]  }|j                          y wr   r  r  s     r_   r   z-DiffusionPipeline.download.<locals>.<genexpr>P  s     >daqwwqz>dr  c              3   D   K   | ]  }|z  j                           y wr   )is_file)r   r  snapshot_folders     r_   r   z-DiffusionPipeline.download.<locals>.<genexpr>S  s     $]o&9%B%B%D$]s    r>  )r  r   r!  r   r"  allow_patternsr  
user_agentrv   rG  rH  r   )r  r  r   r!  r   r   r0  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.)Hr   rW  r=   rT   r   r   r   requestsConnectionErrorri   rj   r   config_name_dict_from_json_filesiblings	rfilenamer2   rd  r%   r   parser   base_versionrO   r?   r{   r}   r|   r   r   r   rz   r   r   rC   r   rK   r   rB   _is_onnxrN   r#   r$   r;   r]  r  recompilefnmatch	translater   r   parentallendswithr   r\  ra  r	  rb  r   r   rh   r   loadsumr:   dataru   r[  FileNotFoundErrorEnvironmentError)<rg  r  ro   r  r  r   r!  r   r"  r#  r%  r&  r   r0  r1  r2  r  r/  allow_pickler  r  model_info_call_errorr   econfig_filerk  ignore_filenamessiblingr  ri  custom_componentsfolder_namesrm  load_pipe_from_hubload_components_from_hubr   r   r>  expected_componentsr   passed_componentsr  model_folder_namesmodel_filenamesvariant_filenamesr  ire_ignore_patternre_allow_patternexpected_filespipeline_is_cachedr  rE  cls_namediffusers_module	modelcardconnected_pipesconnected_pipe_repo_iddownload_kwargsr  s<                                            `                 @r_   r[  zDiffusionPipeline.downloadF  s
   x JJ{D1	$4e<**Y-!::&8$?

7D)::j$/JJ{E2	 **%6= **%6=**Y- **%6=::j$/"(**-F"N"JJ':EB4:JJ{D4Q	)*ghh&)*jkk&&;#$'LL#!1!	 	 !0 7?e;StZ_-<-H/d59*!"7uxX  )%#!-K 22;?K*C:>--Hw**HIH"'LW`jq'rXY`Xa bj j  x(I-=)>>I33k*779x(9) ..CUGU]_hi.P%{Iw/+| !%&:k-6PSWY^R_+`"-m"<Q"?$/$>q$A!!0!<!eOCTTWAX\eAe'*+<'='A$!*; )*?)@@YZiYj k__t^u  vA  BQ  AR Rhi  (0A )*?)@@YZaZfZf  HY  H_  H_  Ha  hb  @D  @A  CDhjhohohthtuvxyhz  hb  [c  Zd dQQUQZQZ  ]n  ]t  ]t  ]v  \w  UY  UV  XY^l  nC  mD  DE  FG  EH  HI  JK  IL  LO  ]P  \w  Rx  Qy yhi  1(? /1C-%,#(
N &)%<%<^%L",? Oq1; O O .@	-J"()bggmm\]N^_`NaeqNqa #" " 3!"''
O 2M7O2.O.
 "/2N ]AJ\A\!Bx]]N9J9P9P9RSA!AaS}SSNo=Nc;RV_;_/!2#67eggNGYZ!rww||A}=ZZN%)	 N *#aggcl2Cq2HQWWUX\Z[_`qMqN  33%%k2 ._0]A3l1C0]]OKZ [aG,=,=a,@!A [ [JXYQ

7+<+<Q+? @YY)2eA#=dRc=d:daeNe)7eA3>dSc>d;daeNe";/66O!$$]n$]!]!. '&&5
&/G/G/N,;J()2	--%#!1!- /%
M rww||MCU'VW[[\ikopH'1(C'@XEXEXY_E`x|fnH(66x~~c7J17MNJTU]_bJcW%5xFimN)n.R.R%NN277<<{+ST	"%Oc&d!wy~~q"'E&dfh"i.= 
Z*%.*8#*,<!&#*+:'O &../EYY
Z ! k 3X5M5MN *!>qcAfgh#' ()%*$ IP hb \w" !P"2 ^S [ 1^ [YeeH 'e ! 	-
 %, '()>(? @  -	-	-s   #_1 `:*`?+a 	a
a)a$a+	a5aa'a 8a%a%4a*	/a/>/a44a9a9a>3a>Db "b 0b 1`7`22`7b b%c                 n   t        j                  |j                        j                  }|j	                         D ci c]&  \  }}|j
                  t         j                  k(  s$||( }}}t        |j	                         D ch c]%  \  }}|j
                  t         j                  k7  s$|' c}}      }t        |j                               dhz
  }t        |      }|D ]3  }	|	| j                  v s|j                  |	       |j                  |	       5 t        |      t        |      fS c c}}w c c}}w )Nrm   )r   r   rl   r   rz   rI  _emptyrd  r   r}   r   addremovesorted)
rg  objr   r   r   required_parametersoptional_parametersr   optional_namesr   s
             r_   r   z%DiffusionPipeline._get_signature_keys  s
   &&s||4??
0:0@0@0Bb1aiiSZSaSaFaq!tbb!1A1A1C"cAqyyT[TbTbGb1"cd2779:fXE12" 	1Ds/// $$T*#**40	1
 &'0C)DDD c"cs   %D+#D+%D1
)D1
c                    i }t        j                  | j                        j                  j	                         D ]  \  }}t        j
                  |j                        r|j                  f||<   6t        |j                        t        k(  rt        |j                        ||<   kt        |j                        t        t        t        t        fv r|j                  f||<   t        j                  d| d|  d        |S )Nz)cannot get type annotation for Parameter z of r   )r   r   rl   r   rz   isclass
annotationr   r
   r   r   r   r}   r   ri   rj   )rg  signature_typesr   r   s       r_   r^  z&DiffusionPipeline._get_signature_types  s    %%cll3>>DDF 	ZDAqq||,&'ll_"ALL)U2%-all%;"ALL)dD$-EE&'ll_"!J1#TRUQVVWXY	Z r^   c           
      p   | j                  |       \  }}| j                  j                         D ci c]&  }|j                  d      r||vs|t	        | |      ( }}t        t        |j                                     }t        |      }||k7  r!t        |  d| j                   d| d| d      |S c c}w )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("stable-diffusion-v1-5/stable-diffusion-v1-5")
        >>> img2img = StableDiffusionImg2ImgPipeline(**text2img.components)
        >>> inpaint = StableDiffusionInpaintPipeline(**text2img.components)
        ```
        r   z% has been incorrectly initialized or z& is incorrectly implemented. Expected z to be defined, but z are defined.)	r   r   r   rb  rh   r  rd  r   rg   )rm   r   r  r   r   actualexpecteds          r_   r   zDiffusionPipeline.components  s    . 150H0H0N--)-)9)9);
$%1<<PSCTYZbuYuAwtQ

 
 JOO-./*+X&=dnn=M N:1&H 
 
s   B3B3B3c                     t        |       S )zL
        Convert a NumPy image or a batch of images to a PIL image.
        )r1   )rS   s    r_   r1   zDiffusionPipeline.numpy_to_pil  s    
 F##r^   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.r]   )r   r  r{   r   r   r   r   )rm   iterabler  s      r_   progress_barzDiffusionPipeline.progress_bar  s    t34(*D%D55t<OPTUYUnUnPoOppqr  >D$=$=>>AeAt'@'@AANOOr^   c                     || _         y r   )r  )rm   ro   s     r_   set_progress_bar_configz)DiffusionPipeline.set_progress_bar_config  s
    $*!r^   attention_opc                 (    | j                  d|       y)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)rm   r	  s     r_   *enable_xformers_memory_efficient_attentionz<DiffusionPipeline.enable_xformers_memory_efficient_attention  s    B 	88|Lr^   c                 &    | j                  d       y)zs
        Disable memory efficient attention from [xFormers](https://facebookresearch.github.io/xformers/).
        FNr  r}  s    r_   +disable_xformers_memory_efficient_attentionz=DiffusionPipeline.disable_xformers_memory_efficient_attention  s     	88?r^   validc                 D  	 dt         j                  j                  f	fd	| j                  |       \  }}|D cg c]  }t	        | |d        }}|D cg c])  }t        |t         j                  j                        s(|+ }}|D ]
  } 	|        y c c}w c c}w )Nr   c                 |    t        | d      r| j                         | j                         D ]
  } |        y )Nr  )r   r  children)r   childr	  fn_recursive_set_mem_effr  s     r_   r  z_DiffusionPipeline.set_use_memory_efficient_attention_xformers.<locals>.fn_recursive_set_mem_eff  s<    vLMBB5,W* 0(/0r^   )r   r  r  r   rh   r{   )
rm   r  r	  r  r   r  r   r  r   r  s
    ``      @r_   r  z=DiffusionPipeline.set_use_memory_efficient_attention_xformers  s    	0UXX__ 	0 2248a3?@a74D)@@%HAuxx)G1HH 	-F$V,	- AHs   B)BB
slice_sizec                 &    | j                  |       y)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(
        ...     "stable-diffusion-v1-5/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)rm   r  s     r_   enable_attention_slicingz*DiffusionPipeline.enable_attention_slicing-  s    L 	  ,r^   c                 &    | j                  d       y)z
        Disable sliced attention computation. If `enable_attention_slicing` was previously called, attention is
        computed in one step.
        N)r  r}  s    r_   disable_attention_slicingz+DiffusionPipeline.disable_attention_slicingU  s     	%%d+r^   c                 &   | j                  |       \  }}|D cg c]  }t        | |d        }}|D cg c]6  }t        |t        j                  j
                        s(t        |d      s5|8 }}|D ]  }|j                  |        y c c}w c c}w )Nr  )r   rh   r{   r   r  r  r   r  )rm   r  r  r   r  r   r  r   s           r_   r  z%DiffusionPipeline.set_attention_slice]  s    2248a3?@a74D)@@%nAuxx)GGTUWlLm1nn 	3F&&z2	3 Ans   B	)BB*Bc                    t        |j                        }|j                  dt        j                        }|j                  dd      }|j                  dd      }|t        ||      }n| }| j                  |      \  }}	t        j                  | j                        j                  }
t        |
j                         D ch c]*  \  }}|j                  t        j                  k7  s$||v s)|, c}}      }|j                         }|j                  dd      }|D ci c]  }||v s||j                  |       }}i }|j                   j                         D ]y  \  }}||v s||vst#        |t$              r t'        |      ||   v s||| j(                  v r|||<   Ft*        j-                  d| d| d	t'        |       d
||    d| d| d       { |	D ci c]  }||v s||j                  |       }}|j/                         D ci c]  }||	v r
||vr|||    }}|j/                         D cg c]&  }|j1                  d      r|dd |	v r|dd |vr|dd ( }}|D ]  }|j                  d|       ||<    i |||||}|j                         D ci c]$  \  }}||vs|j1                  d      rdnd | |& }}}t3        |d      r|j(                  r|j(                  ng }t        |      t        |      z
  t        |j/                               z
  t        |      z
  }t5        |      dkD  rOt7        d| d| dt        t9        |j/                               t9        |j/                               z          d       |di |}||j;                  |        |j:                  di | ||j=                  |       |S c c}}w c c}w c c}w c c}w c c}w c c}}w )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("stable-diffusion-v1-5/stable-diffusion-v1-5")
        >>> new_pipe = StableDiffusionSAGPipeline.from_pipe(pipe)
        ```
        r$  r%  Nr&  )r"  r   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)`r   r8   r;  r   r   rP  rQ  rR  z were passedrU  )r   r]   )r   r   r   r   r  r@   r   r   r   rl   r   rd  rz   rI  r  r^  r   r{   r    r   r   ri   rj   r   rb  r   r   r   r}   r~   r  )rg  pipelinero   original_configr$  r%  r&  r>  r   r   r   r   r   true_optional_modulescomponent_typesr  r@  original_class_objr   r  rN  original_pipe_kwargsadditional_pipe_kwargspipeline_kwargsunused_original_configoptional_componentsru  new_pipelines                               r_   	from_pipezDiffusionPipeline.from_pipee  s   0 x/jj> !**%6= **%6=&7RabN N,/,C,CN,S)/ &&s||4??
 #%++-g41agnn1LQRVfQfQg!
 )==?(7(;(;OT(R%6FV!v+Avzz!},VV'2288: 	OD)''D8H,H #9j9I/$*??!)dc6N6N.N/8&t,NN$TF + 6d9o%66UVefjVkUl moosnttuvzu{{}	" 9HW11PV;aA.WW %))+ 
O#1C(C q!! 
  
 %))+"
||C QqrUo%=!AB%OaBa abE"
 "

 ( 	CA&5&9&9AaS'&B #	C

 
 !
 #	

 
 ETDYDYD["
<@Aq_`hw_wQ\\#&rC04a7"
 "
 x!78X=Z=Z )) 	  !C(;$<<s?CWCWCY?ZZ]`av]ww 	 !#N+:6F5G{SVW[\l\q\q\sWtw{  }O  }T  }T  }V  xW  XW  TX  SY  Ye  f  &88(4++:W+X'''A*@A"OO+O.e h W( X 
"
""
sB   %O
'O
,O
	O(O	O$OO5+O$O),O)r   r   c                     ddl m} || j                  j                         n|g}|D cg c])  }t	        |t
        j                  j                        s(|+ }}|D ]  } ||      s|rt        d       y yc c}w )Nr   )_is_group_offload_enabledzYou are trying to apply model/sequential CPU offloading to a pipeline that contains components with group offloading enabled. This is not supported. Please disable group offloading for components of the pipeline to use other offloading methods.TF)	r  r+  r   r  r{   r   r  r  r   )rm   r   r   r+  r   r  s         r_   r  z<DiffusionPipeline._maybe_raise_error_if_group_offload_active  s     	G17T__++-fX
1;fIz)UZU]U]UdUd?eif
f# 	I(3$V 
 	  gs   )A9A9)TNNFry   r   )auto)FN)=rT   rU   rV   rW   r  r  r   r   r  r]  r  r   r	  r   r   r
   r   PathLikeboolr	   intr   r   r  propertyr   r   r   classmethodr   r{  r~  r  r  r  r  r  r  r[  r   r^  r   r   staticmethodr1   compilerdisabler  r  r   r  r  r  r  r  r  r)  r  r  r  rr   rs   s   @r_   ru   ru      sY   " %K M "!H() )C )$ $(!%48!Cc2;;./C !C #	C
 !sCx1C CJ{T {z # # # u{{   BHU3PRP[P[K[E\<] Blp B  BH ;c ; ;    D[-x} [-USXS_S_adSdMe [-zW.ALHSM ALRWX]XdXdfiXiRj ALF& I-%R[[@P:Q I-  I-V
 E E   #DcN # #J $ $ ^^P P+!MxPXGY !MF@ ?C--)1();-	-(&-8E#s(O3L &-P,3hsm 3 z zz NR19%((//1J	r^   ru   c                   j    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y)StableDiffusionMixinzb
    Helper for DiffusionPipeline with vae and unet.(mainly for LDM such as stable diffusion)
    c                 8    | j                   j                          y)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_slicingr}  s    r_   enable_vae_slicingz'StableDiffusionMixin.enable_vae_slicing      
 	!r^   c                 8    | j                   j                          y)z
        Disable sliced VAE decoding. If `enable_vae_slicing` was previously enabled, this method will go back to
        computing decoding in one step.
        N)r8  disable_slicingr}  s    r_   disable_vae_slicingz(StableDiffusionMixin.disable_vae_slicing  s    
 	  "r^   c                 8    | j                   j                          y)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)r8  enable_tilingr}  s    r_   enable_vae_tilingz&StableDiffusionMixin.enable_vae_tiling  s     	 r^   c                 8    | j                   j                          y)z
        Disable tiled VAE decoding. If `enable_vae_tiling` was previously enabled, this method will go back to
        computing decoding in one step.
        N)r8  disable_tilingr}  s    r_   disable_vae_tilingz'StableDiffusionMixin.disable_vae_tiling  r;  r^   s1s2b1b2c                 p    t        | d      st        d      | j                  j                  ||||       y)a=  Enables the FreeU mechanism as in https://huggingface.co/papers/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.)rE  rF  rG  rH  N)r   r   rJ  enable_freeu)rm   rE  rF  rG  rH  s        r_   rK  z!StableDiffusionMixin.enable_freeu  s5    $ tV$MNN		"r:r^   c                 8    | j                   j                          y)z(Disables the FreeU mechanism if enabled.N)rJ  disable_freeur}  s    r_   rM  z"StableDiffusionMixin.disable_freeu-  s    		!r^   rJ  r8  c                    d| _         d| _        |rDd| _         | j                  j                          | j                  j	                  t                      |rjt        | j                  t              st        d      d| _        | j                  j                          | j                  j	                  t                      yy)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_vaerJ  fuse_qkv_projectionsset_attn_processorr   r{   r8  r   r   rm   rJ  r8  s      r_   rQ  z)StableDiffusionMixin.fuse_qkv_projections1  s     !#DII**,II(()>)@Adhh6 !rss"DOHH))+HH''(=(?@ r^   c                    |rC| j                   st        j                  d       n!| j                  j	                          d| _         |rD| j
                  st        j                  d       y| j                  j	                          d| _        yy)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)rO  ri   rj   rJ  unfuse_qkv_projectionsrP  r8  rS  s      r_   rU  z+StableDiffusionMixin.unfuse_qkv_projectionsP  sh     ##ef		002#( ??de//1"' r^   N)TT)rT   rU   rV   rW   r:  r>  rA  rD  floatrK  rM  r.  rQ  rU  r]   r^   r_   r6  r6    sj    "#!";u ;% ;U ; ;,"A A4 A>(4 (T (r^   r6  )zr  r   r   r   r  r   dataclassesr   pathlibr   typingr   r   r   r   r	   r
   r   r   numpyrZ   	PIL.ImagerX   r  r   huggingface_hubr   r   r   r   r   r   r   huggingface_hub.utilsr   r   	packagingr   requests.exceptionsr   	tqdm.autor   typing_extensionsr   r;  r   configuration_utilsr   modelsr   models.attention_processorr   models.modeling_utilsr   r    
quantizersr!   quantizers.bitsandbytes.utilsr"   schedulers.scheduling_utilsr#   utilsr$   r%   r&   r'   r(   r)   r*   r+   r,   r-   r.   r/   r0   r1   utils.hub_utilsr2   r3   r4   utils.torch_utilsr5   r6   r7   	torch_npupipeline_loading_utilsr9   r:   r;   r<   r=   r>   r?   r@   rA   rB   rC   rD   rE   rF   rG   rH   rI   rJ   rK   rL   rM   rN   rO   r   	LIBRARIESr   r  rX  
get_loggerrT   ri   rR   ra   rd   ru   r6  r]   r^   r_   <module>rp     sp       	 	 
 !  S S S       M  )  "  - " > J 3 = ?     t s R R       6  	 GW #|z|n4 			H	% 
5* 
5 
5 	* 	 	"* "*J~^ ~B:u( u(r^   