
    
3j0                         S SK Jr  S SKrSSKJr  SSKJr  SSKJrJ	r	J
r
  SSKJr  SS	KJrJr  \" 5       (       a  S SKJs  Jr  S
rOSr\	R*                  " \5      rSr " S S\5      rg)    )CallableN   )UNet2DModel)CMStochasticIterativeScheduler)is_torch_xla_availableloggingreplace_example_docstring)randn_tensor   )DiffusionPipelineImagePipelineOutputTFa  
    Examples:
        ```py
        >>> import torch

        >>> from diffusers import ConsistencyModelPipeline

        >>> device = "cuda"
        >>> # Load the cd_imagenet64_l2 checkpoint.
        >>> model_id_or_path = "openai/diffusers-cd_imagenet64_l2"
        >>> pipe = ConsistencyModelPipeline.from_pretrained(model_id_or_path, torch_dtype=torch.float16)
        >>> pipe.to(device)

        >>> # Onestep Sampling
        >>> image = pipe(num_inference_steps=1).images[0]
        >>> image.save("cd_imagenet64_l2_onestep_sample.png")

        >>> # Onestep sampling, class-conditional image generation
        >>> # ImageNet-64 class label 145 corresponds to king penguins
        >>> image = pipe(num_inference_steps=1, class_labels=145).images[0]
        >>> image.save("cd_imagenet64_l2_onestep_sample_penguin.png")

        >>> # Multistep sampling, class-conditional image generation
        >>> # Timesteps can be explicitly specified; the particular timesteps below are from the original GitHub repo:
        >>> # https://github.com/openai/consistency_models/blob/main/scripts/launch.sh#L77
        >>> image = pipe(num_inference_steps=None, timesteps=[22, 0], class_labels=145).images[0]
        >>> image.save("cd_imagenet64_l2_multistep_sample_penguin.png")
        ```
c                     ^  \ rS rSrSrSrS\S\SS4U 4S jjrSS jr	SS	\
R                  S
\4S jjrSS jrS r\
R                   " 5       \" \5                SS\S\
R                  \\   -  \-  S-  S\S\\   S\
R*                  \\
R*                     -  S-  S\
R                  S-  S
\S-  S\S\\\\
R                  /S4   S-  S\4S jj5       5       rSrU =r$ )ConsistencyModelPipelineC   a:  
Pipeline for unconditional or class-conditional image generation.

This model inherits from [`DiffusionPipeline`]. Check the superclass documentation for the generic methods
implemented for all pipelines (downloading, saving, running on a particular device, etc.).

Args:
    unet ([`UNet2DModel`]):
        A `UNet2DModel` to denoise the encoded image latents.
    scheduler ([`SchedulerMixin`]):
        A scheduler to be used in combination with `unet` to denoise the encoded image latents. Currently only
        compatible with [`CMStochasticIterativeScheduler`].
unet	schedulerreturnNc                 P   > [         TU ]  5         U R                  UUS9  S U l        g )N)r   r   )super__init__register_modulessafety_checker)selfr   r   	__class__s      |/home/wildlama/miniconda3/lib/python3.13/site-packages/diffusers/pipelines/consistency_models/pipeline_consistency_models.pyr   !ConsistencyModelPipeline.__init__T   s1     	 	

 #    c	                     XX44n	[        U[        5      (       a*  [        U5      U:w  a  [        S[        U5       SU S35      eUc  [	        XXeS9nOUR                  XeS9nXR                  R                  -  nU$ )Nz/You have passed a list of generators of length z+, but requested an effective batch size of z@. Make sure the batch size matches the length of the generators.)	generatordevicedtype)r    r!   )
isinstancelistlen
ValueErrorr
   tor   init_noise_sigma)
r   
batch_sizenum_channelsheightwidthr!   r    r   latentsshapes
             r   prepare_latents(ConsistencyModelPipeline.prepare_latents^   s    69i&&3y>Z+GA#i.AQ R&<'gi 
 ?"5fZGjjj<G NN;;;r   sampleoutput_typec                    US;  a  [        SU S35      eUS-  S-   R                  SS5      nUS:X  a  U$ UR                  5       R                  SSS	S5      R	                  5       nUS
:X  a  U$ U R                  U5      nU$ )N)ptnppilzoutput_type=zD is not supported. Make sure to choose one of ['pt', 'np', or 'pil']r   g      ?r      r3   r   r4   )r%   clampcpupermutenumpynumpy_to_pil)r   r0   r1   s      r   postprocess_image*ConsistencyModelPipeline.postprocess_imagep   s    11{m+op 
 1*s"))!Q/$M %%aAq1779$M ""6*r   c                    U R                   R                  R                  b  [        U[        5      (       a$  [
        R                  " U[
        R                  S9nO[        U[        5      (       a2  US:X  d   S5       e[
        R                  " U/[
        R                  S9nO8Uc5  [
        R                  " SU R                   R                  R                  U4S9nUR                  U5      nU$ S nU$ )N)r!   r6   z)Batch size must be 1 if classes is an intr   )size)
r   confignum_class_embedsr"   r#   torchtensorintrandintr&   )r   r(   r    class_labelss       r   prepare_class_labels-ConsistencyModelPipeline.prepare_class_labels   s    99,,8,--$||L		JL#..!QS(SS$||\N%))L%  %}}Q		0@0@0Q0QYcXef'??62L   Lr   c                 L   Uc  Uc  [        S5      eUb  Ub  [        R                  SU SU S35        Ub1  USXU4nUR                  U:w  a  [        SUR                   SU S35      eUb  Ub7  [	        U[
        5      (       a  US	::  a  [        S
U S[        U5       S35      eg g )NzEExactly one of `num_inference_steps` or `timesteps` must be supplied.zBoth `num_inference_steps`: z and `timesteps`: zC are supplied; `timesteps` will be used over `num_inference_steps`.r   zThe shape of latents is z but is expected to be .r   z5`callback_steps` has to be a positive integer but is z	 of type )r%   loggerwarningr-   r"   rD   type)r   num_inference_steps	timestepsr,   r(   img_sizecallback_stepsexpected_shapes           r   check_inputs%ConsistencyModelPipeline.check_inputs   s    &9+<dee*y/DNN./B.CCUV_U` aH H
 (!X@N}}. #;GMM?Jabpaqqr!stt"&
>30O0OSaefSfGGW X(),  Tg&r   r(   rF   rN   rO   r   r,   return_dictcallbackrQ   c                    U R                   R                  R                  nU R                  nU R	                  X4XaX5        U R                  UU R                   R                  R                  UUU R                   R                  UUUS9nU R                  XUS9nUb;  U R                  R                  XLS9  U R                  R                  n[        U5      nO1U R                  R                  U5        U R                  R                  nU R                  US9 n[        U5       H  u  nnU R                  R                  UU5      nU R                  UUUSS9S   nU R                  R!                  UUXS	9S   nUR#                  5         U	b  X-  S:X  a
  U	" UUU5        [$        (       d  M  [&        R(                  " 5         M     SSS5        U R+                  XS
9nU R-                  5         U(       d  U4$ [/        US9$ ! , (       d  f       N@= f)a  
Args:
    batch_size (`int`, *optional*, defaults to 1):
        The number of images to generate.
    class_labels (`torch.Tensor` or `list[int]` or `int`, *optional*):
        Optional class labels for conditioning class-conditional consistency models. Not used if the model is
        not class-conditional.
    num_inference_steps (`int`, *optional*, defaults to 1):
        The number of denoising steps. More denoising steps usually lead to a higher quality image at the
        expense of slower inference.
    timesteps (`list[int]`, *optional*):
        Custom timesteps to use for the denoising process. If not defined, equal spaced `num_inference_steps`
        timesteps are used. Must be in descending order.
    generator (`torch.Generator`, *optional*):
        A [`torch.Generator`](https://pytorch.org/docs/stable/generated/torch.Generator.html) to make
        generation deterministic.
    latents (`torch.Tensor`, *optional*):
        Pre-generated noisy latents sampled from a Gaussian distribution, to be used as inputs for image
        generation. Can be used to tweak the same generation with different prompts. If not provided, a latents
        tensor is generated by sampling using the supplied random `generator`.
    output_type (`str`, *optional*, defaults to `"pil"`):
        The output format of the generated image. Choose between `PIL.Image` or `np.array`.
    return_dict (`bool`, *optional*, defaults to `True`):
        Whether or not to return a [`~pipelines.ImagePipelineOutput`] instead of a plain tuple.
    callback (`Callable`, *optional*):
        A function that calls every `callback_steps` steps during inference. The function is called with the
        following arguments: `callback(step: int, timestep: int, latents: torch.Tensor)`.
    callback_steps (`int`, *optional*, defaults to 1):
        The frequency at which the `callback` function is called. If not specified, the callback is called at
        every step.

Examples:

Returns:
    [`~pipelines.ImagePipelineOutput`] or `tuple`:
        If `return_dict` is `True`, [`~pipelines.ImagePipelineOutput`] is returned, otherwise a `tuple` is
        returned where the first element is a list with the generated images.
)r(   r)   r*   r+   r!   r    r   r,   )rF   N)rO   r    )totalF)rF   rU   r   )r   )r1   )images)r   r@   sample_size_execution_devicerS   r.   in_channelsr!   rG   r   set_timestepsrO   r$   progress_bar	enumeratescale_model_inputstepupdateXLA_AVAILABLExm	mark_stepr<   maybe_free_model_hooksr   )r   r(   rF   rN   rO   r   r,   r1   rU   rV   rQ   rP   r    r0   r^   itscaled_samplemodel_outputimages                       r   __call__!ConsistencyModelPipeline.__call__   s   l 99##//'' 	-'xh %%!))55))// & 	
 00R^0_  NN((9(L00I"%i.NN(()<=00I %89\!),1 $ @ @ K#yybgyhijk,,\1f,Z[\] ##%'A,>!,CQ6* =LLN - :  &&v&G 	##%8O"%001 :9s   BG<)G<<
H
)r   )N)r5   )
r6   Nr6   NNNr5   TNr6   )__name__
__module____qualname____firstlineno____doc__model_cpu_offload_seqr   r   r   r.   rB   Tensorstrr<   rG   rS   no_gradr	   EXAMPLE_DOC_STRINGrD   r#   	Generatorboolr   rl   __static_attributes____classcell__)r   s   @r   r   r   C   sa    ##[ #5S #X\ #$ 3 ( . ]]_12 >B#$#DH'+"' DHm1m1 llT#Y.4t;m1 !	m1
 9m1 ??T%//%::TAm1 $m1 4Zm1 m1 Cell3T9:TAm1 m1 3 m1r   r   )typingr   rB   modelsr   
schedulersr   utilsr   r   r	   utils.torch_utilsr
   pipeline_utilsr   r   torch_xla.core.xla_modelcore	xla_modelrd   rc   
get_loggerrn   rK   rw   r    r   r   <module>r      sa      ! 8 O O - C ))MM			H	% >W10 W1r   