



from typing import Callable, List, Optional, Union

import torch

from ...models import UNetaDModel
from ...schedulers import CMStochasticIterativeScheduler
from ...utils import (
    is_accelerate_available,
    is_accelerate_version,
    logging,
    randn_tensor,
    replace_example_docstring,
)
from ..pipeline_utils import DiffusionPipeline, ImagePipelineOutput


a__      =		logging.get_logger(__name__)  # pylint: disable=invalid-name


a__      =		"""
    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\")
        ```
"""







class 						snake_case  (		SCREAMING_SNAKE_CASE_					):



   '''simple docstring'''






   def __init__(   self							:     Optional[int]			,						lowerCAmelCase							:     UNetaDModel			,						lowerCAmelCase							:     CMStochasticIterativeScheduler)			->			None:

    """simple docstring"""







    super().__init__()

    self.register_modules(
        unet=lowerCAmelCase			,						scheduler=lowerCAmelCase			,						)

    _snake_case      :					Any					=   None

   def        UpperCamelCase_					(   self							:     str			,						lowerCAmelCase							:     Optional[int]=0)			->			Union[str, Any]:

    """simple docstring"""







    if is_accelerate_available() and is_accelerate_version(""">="""			,						"""0.14.0"""):
     from accelerate import cpu_offload
    else:
     raise ImportError("""`enable_sequential_cpu_offload` requires `accelerate v0.14.0` or higher""")

    _snake_case      :					Tuple					=   torch.device(F'''cuda:{gpu_id}''')

    if self.device.type != "cpu":
     self.to("""cpu"""			,						silence_dtype_warnings=lowerCAmelCase)
     torch.cuda.empty_cache()  # otherwise we don't see the memory savings (but they probably exist)

    for cpu_offloaded_model in [self.unet]:
     cpu_offload(lowerCAmelCase			,						lowerCAmelCase)

    if self.safety_checker is not None:
     cpu_offload(self.safety_checker			,						execution_device=lowerCAmelCase			,						offload_buffers=lowerCAmelCase)

   def        UpperCamelCase_					(   self							:     str			,						lowerCAmelCase							:     Any=0)			->			int:

    """simple docstring"""







    if is_accelerate_available() and is_accelerate_version(""">="""			,						"""0.17.0.dev0"""):
     from accelerate import cpu_offload_with_hook
    else:
     raise ImportError("""`enable_model_cpu_offload` requires `accelerate v0.17.0` or higher.""")

    _snake_case      :					List[Any]					=   torch.device(F'''cuda:{gpu_id}''')

    if self.device.type != "cpu":
     self.to("""cpu"""			,						silence_dtype_warnings=lowerCAmelCase)
     torch.cuda.empty_cache()  # otherwise we don't see the memory savings (but they probably exist)

    _snake_case      :					Union[str, Any]					=   None
    for cpu_offloaded_model in [self.unet]:
     _snake_case		,      _snake_case      :					Dict					=   cpu_offload_with_hook(lowerCAmelCase			,						lowerCAmelCase			,						prev_module_hook=lowerCAmelCase)

    if self.safety_checker is not None:
     _snake_case		,      _snake_case      :					Optional[Any]					=   cpu_offload_with_hook(self.safety_checker			,						lowerCAmelCase			,						prev_module_hook=lowerCAmelCase)

    # We'll offload the last model manually.
    _snake_case      :					List[str]					=   hook

   @property
   # Copied from diffusers.pipelines.stable_diffusion.pipeline_stable_diffusion.StableDiffusionPipeline._execution_device
   def        UpperCamelCase_					(   self							:     Optional[int])			->			Optional[Any]:

    """simple docstring"""







    if not hasattr(self.unet			,						"""_hf_hook"""):
     return self.device
    for module in self.unet.modules():
     if (
         hasattr(lowerCAmelCase			,						"""_hf_hook""")
         and hasattr(module._hf_hook			,						"""execution_device""")
         and module._hf_hook.execution_device is not None
     ):
      return torch.device(module._hf_hook.execution_device)
    return self.device

   def        UpperCamelCase_					(   self							:     List[str]			,						lowerCAmelCase							:     Dict			,						lowerCAmelCase							:     Dict			,						lowerCAmelCase							:     Optional[int]			,						lowerCAmelCase							:     Union[str, Any]			,						lowerCAmelCase							:     int			,						lowerCAmelCase							:     Optional[int]			,						lowerCAmelCase							:     List[Any]			,						lowerCAmelCase							:     Any=None)			->			Optional[Any]:

    """simple docstring"""







    _snake_case      :					str					=   (batch_size, num_channels, height, width)
    if isinstance(lowerCAmelCase			,						lowerCAmelCase) and len(lowerCAmelCase) != batch_size:
     raise ValueError(
         F'''You have passed a list of generators of length {len(lowerCAmelCase)}, but requested an effective batch'''
         F''' size of {batch_size}. Make sure the batch size matches the length of the generators.''')

    if latents is None:
     _snake_case      :					Tuple					=   randn_tensor(lowerCAmelCase			,						generator=lowerCAmelCase			,						device=lowerCAmelCase			,						dtype=lowerCAmelCase)
    else:
     _snake_case      :					Tuple					=   latents.to(device=lowerCAmelCase			,						dtype=lowerCAmelCase)

    # scale the initial noise by the standard deviation required by the scheduler
    _snake_case      :					Any					=   latents * self.scheduler.init_noise_sigma
    return latents

   def        UpperCamelCase_					(   self							:     Any			,						lowerCAmelCase							:     torch.FloatTensor			,						lowerCAmelCase							:     str = "pil")			->			Union[str, Any]:

    """simple docstring"""







    if output_type not in ["pt", "np", "pil"]:
     raise ValueError(
         F'''output_type={output_type} is not supported. Make sure to choose one of [\'pt\', \'np\', or \'pil\']''')

    # Equivalent to diffusers.VaeImageProcessor.denormalize
    _snake_case      :					str					=   (sample / 2 + 0.5).clamp(0			,						1)
    if output_type == "pt":
     return sample

    # Equivalent to diffusers.VaeImageProcessor.pt_to_numpy
    _snake_case      :					str					=   sample.cpu().permute(0			,						2			,						3			,						1).numpy()
    if output_type == "np":
     return sample

    # Output_type must be 'pil'
    _snake_case      :					int					=   self.numpy_to_pil(lowerCAmelCase)
    return sample

   def        UpperCamelCase_					(   self							:     Optional[int]			,						lowerCAmelCase							:     Union[str, Any]			,						lowerCAmelCase							:     Union[str, Any]			,						lowerCAmelCase							:     Tuple=None)			->			List[Any]:

    """simple docstring"""







    if self.unet.config.num_class_embeds is not None:
     if isinstance(lowerCAmelCase			,						lowerCAmelCase):
      _snake_case      :					List[Any]					=   torch.tensor(lowerCAmelCase			,						dtype=torch.int)
     elif isinstance(lowerCAmelCase			,						lowerCAmelCase):
      assert batch_size == 1, "Batch size must be 1 if classes is an int"
      _snake_case      :					Tuple					=   torch.tensor([class_labels]			,						dtype=torch.int)
     elif class_labels is None:
      # Randomly generate batch_size class labels
      # TODO: should use generator here? int analogue of randn_tensor is not exposed in ...utils
      _snake_case      :					Dict					=   torch.randint(0			,						self.unet.config.num_class_embeds			,						size=(batch_size,))
     _snake_case      :					Union[str, Any]					=   class_labels.to(lowerCAmelCase)
    else:
     _snake_case      :					str					=   None
    return class_labels

   def        UpperCamelCase_					(   self							:     Any			,						lowerCAmelCase							:     Tuple			,						lowerCAmelCase							:     Tuple			,						lowerCAmelCase							:     Tuple			,						lowerCAmelCase							:     Any			,						lowerCAmelCase							:     Union[str, Any]			,						lowerCAmelCase							:     int)			->			List[str]:

    """simple docstring"""







    if num_inference_steps is None and timesteps is None:
     raise ValueError("""Exactly one of `num_inference_steps` or `timesteps` must be supplied.""")

    if num_inference_steps is not None and timesteps is not None:
     logger.warning(
         F'''Both `num_inference_steps`: {num_inference_steps} and `timesteps`: {timesteps} are supplied;'''
         """ `timesteps` will be used over `num_inference_steps`.""")

    if latents is not None:
     _snake_case      :					List[str]					=   (batch_size, 3, img_size, img_size)
     if latents.shape != expected_shape:
      raise ValueError(F'''The shape of latents is {latents.shape} but is expected to be {expected_shape}.''')

    if (callback_steps is None) or (
        callback_steps is not None and (not isinstance(lowerCAmelCase			,						lowerCAmelCase) or callback_steps <= 0)
    ):
     raise ValueError(
         F'''`callback_steps` has to be a positive integer but is {callback_steps} of type'''
         F''' {type(lowerCAmelCase)}.''')


   @torch.no_grad()
   @replace_example_docstring(lowerCAmelCase)
   def __call__(   self							:     List[str]			,						lowerCAmelCase							:     int = 1			,						lowerCAmelCase							:     Optional[Union[torch.Tensor, List[int], int]] = None			,						lowerCAmelCase							:     int = 1			,						lowerCAmelCase							:     List[int] = None			,						lowerCAmelCase							:     Optional[Union[torch.Generator, List[torch.Generator]]] = None			,						lowerCAmelCase							:     Optional[torch.FloatTensor] = None			,						lowerCAmelCase							:     Optional[str] = "pil"			,						lowerCAmelCase							:     bool = True			,						lowerCAmelCase							:     Optional[Callable[[int, int, torch.FloatTensor], None]] = None			,						lowerCAmelCase							:     int = 1			,						)			->			Tuple:

    """simple docstring"""







    _snake_case      :					Dict					=   self.unet.config.sample_size
    _snake_case      :					Tuple					=   self._execution_device

    # 1. Check inputs
    self.check_inputs(lowerCAmelCase			,						lowerCAmelCase			,						lowerCAmelCase			,						lowerCAmelCase			,						lowerCAmelCase			,						lowerCAmelCase)

    # 2. Prepare image latents
    # Sample image latents x_0 ~ N(0, sigma_0^2 * I)
    _snake_case      :					List[str]					=   self.prepare_latents(
        batch_size=lowerCAmelCase			,						num_channels=self.unet.config.in_channels			,						height=lowerCAmelCase			,						width=lowerCAmelCase			,						dtype=self.unet.dtype			,						device=lowerCAmelCase			,						generator=lowerCAmelCase			,						latents=lowerCAmelCase			,						)

    # 3. Handle class_labels for class-conditional models
    _snake_case      :					Dict					=   self.prepare_class_labels(lowerCAmelCase			,						lowerCAmelCase			,						class_labels=lowerCAmelCase)

    # 4. Prepare timesteps
    if timesteps is not None:
     self.scheduler.set_timesteps(timesteps=lowerCAmelCase			,						device=lowerCAmelCase)
     _snake_case      :					Any					=   self.scheduler.timesteps
     _snake_case      :					Dict					=   len(lowerCAmelCase)
    else:
     self.scheduler.set_timesteps(lowerCAmelCase)
     _snake_case      :					Tuple					=   self.scheduler.timesteps

    # 5. Denoising loop
    # Multistep sampling: implements Algorithm 1 in the paper
    with self.progress_bar(total=lowerCAmelCase) as progress_bar:
     for i, t in enumerate(lowerCAmelCase):
      _snake_case      :					Optional[Any]					=   self.scheduler.scale_model_input(lowerCAmelCase			,						lowerCAmelCase)
      _snake_case      :					Optional[Any]					=   self.unet(lowerCAmelCase			,						lowerCAmelCase			,						class_labels=lowerCAmelCase			,						return_dict=lowerCAmelCase)[0]

      _snake_case      :					Optional[Any]					=   self.scheduler.step(lowerCAmelCase			,						lowerCAmelCase			,						lowerCAmelCase			,						generator=lowerCAmelCase)[0]

      # call the callback, if provided
      progress_bar.update()
      if callback is not None and i % callback_steps == 0:
       callback(lowerCAmelCase			,						lowerCAmelCase			,						lowerCAmelCase)

        # 6. Post-process image sample
    _snake_case      :					Tuple					=   self.postprocess_image(lowerCAmelCase			,						output_type=lowerCAmelCase)

    # Offload last model to CPU
    if hasattr(self			,						"""final_offload_hook""") and self.final_offload_hook is not None:
     self.final_offload_hook.offload()

    if not return_dict:
     return (image,)

    return ImagePipelineOutput(images=lowerCAmelCase)





import os
import warnings
from pathlib import Path
from typing import Optional, Union

from .dynamic_module_utils import custom_object_save
from .tokenization_utils_base import PreTrainedTokenizerBase
from .utils import PushToHubMixin, copy_func, direct_transformers_import, logging


a__      =		logging.get_logger(__name__)

# Dynamically import the Transformers module to grab the attribute classes of the processor form their names.
a__      =		direct_transformers_import(Path(__file__).parent)


a__      =		{
    """AutoTokenizer""": """PreTrainedTokenizerBase""",
    """AutoFeatureExtractor""": """FeatureExtractionMixin""",
    """AutoImageProcessor""": """ImageProcessingMixin""",
}







class 						snake_case  (		SCREAMING_SNAKE_CASE_					):



   '''simple docstring'''






   snake_case_   :	List[str]       =						["""feature_extractor""", """tokenizer"""]
   # Names need to be attr_class for attr in attributes
   snake_case_   :	Optional[Any]       =						None
   snake_case_   :	List[str]       =						None
   snake_case_   :	List[str]       =						None

   def __init__(   self							:     int			,						*lowerCAmelCase							:     Any			,						**lowerCAmelCase							:     int)			->			Optional[Any]:

    """simple docstring"""







    for key in kwargs:
     if key not in self.attributes:
      raise TypeError(F'''Unexpected keyword argument {key}.''')
    for arg, attribute_name in zip(lowerCAmelCase			,						self.attributes):
     if attribute_name in kwargs:
      raise TypeError(F'''Got multiple values for argument {attribute_name}.''')
     else:
      _snake_case      :					List[str]					=   arg

    if len(lowerCAmelCase) != len(self.attributes):
     raise ValueError(
         F'''This processor requires {len(self.attributes)} arguments: {', '.join(self.attributes)}. Got '''
         F'''{len(lowerCAmelCase)} arguments instead.''')

    # Check each arg is of the proper class (this will also catch a user initializing in the wrong order)
    for attribute_name, arg in kwargs.items():
     _snake_case      :					Optional[Any]					=   getattr(self			,						F'''{attribute_name}_class''')
     # Nothing is ever going to be an instance of "AutoXxx", in that case we check the base class.
     _snake_case      :					List[str]					=   AUTO_TO_BASE_CLASS_MAPPING.get(lowerCAmelCase			,						lowerCAmelCase)
     if isinstance(lowerCAmelCase			,						lowerCAmelCase):
      _snake_case      :					Optional[Any]					=   tuple(getattr(lowerCAmelCase			,						lowerCAmelCase) for n in class_name if n is not None)
     else:
      _snake_case      :					List[Any]					=   getattr(lowerCAmelCase			,						lowerCAmelCase)

     if not isinstance(lowerCAmelCase			,						lowerCAmelCase):
      raise ValueError(
          F'''Received a {type(lowerCAmelCase).__name__} for argument {attribute_name}, but a {class_name} was expected.''')

     setattr(self			,						lowerCAmelCase			,						lowerCAmelCase)

   def __repr__(   self							:     int)			->			Dict:

    """simple docstring"""







    _snake_case      :					Union[str, Any]					=   [F'''- {name}: {repr(getattr(self			,						lowerCAmelCase))}''' for name in self.attributes]
    _snake_case      :					str					=   """\n""".join(lowerCAmelCase)
    return F'''{self.__class__.__name__}:\n{attributes_repr}'''

   def        UpperCamelCase_					(   self							:     Optional[int]			,						lowerCAmelCase							:     Optional[int]			,						lowerCAmelCase							:     bool = False			,						**lowerCAmelCase							:     Union[str, Any])			->			Dict:

    """simple docstring"""







    os.makedirs(lowerCAmelCase			,						exist_ok=lowerCAmelCase)

    if push_to_hub:
     _snake_case      :					str					=   kwargs.pop("""commit_message"""			,						lowerCAmelCase)
     _snake_case      :					Union[str, Any]					=   kwargs.pop("""repo_id"""			,						save_directory.split(os.path.sep)[-1])
     _snake_case      :					Tuple					=   self._create_repo(lowerCAmelCase			,						**lowerCAmelCase)
     _snake_case      :					Any					=   self._get_files_timestamps(lowerCAmelCase)
    # If we have a custom config, we copy the file defining it in the folder and set the attributes so it can be
    # loaded from the Hub.
    if self._auto_class is not None:
     _snake_case      :					Any					=   [getattr(self			,						lowerCAmelCase) for attribute_name in self.attributes]
     _snake_case      :					Any					=   [(a.init_kwargs if isinstance(lowerCAmelCase			,						lowerCAmelCase) else a) for a in attrs]
     custom_object_save(self			,						lowerCAmelCase			,						config=lowerCAmelCase)

    for attribute_name in self.attributes:
     _snake_case      :					Optional[int]					=   getattr(self			,						lowerCAmelCase)
     # Include the processor class in the attribute config so this processor can then be reloaded with the
     # `AutoProcessor` API.
     if hasattr(lowerCAmelCase			,						"""_set_processor_class"""):
      attribute._set_processor_class(self.__class__.__name__)
     attribute.save_pretrained(lowerCAmelCase)

    if self._auto_class is not None:
     # We added an attribute to the init_kwargs of the tokenizers, which needs to be cleaned up.
     for attribute_name in self.attributes:
      _snake_case      :					List[str]					=   getattr(self			,						lowerCAmelCase)
      if isinstance(lowerCAmelCase			,						lowerCAmelCase):
       del attribute.init_kwargs["auto_map"]

    if push_to_hub:
     self._upload_modified_files(
         lowerCAmelCase			,						lowerCAmelCase			,						lowerCAmelCase			,						commit_message=lowerCAmelCase			,						token=kwargs.get("""use_auth_token""")			,						)

   @classmethod
   def        UpperCamelCase_					(   cls							:     List[Any]			,						lowerCAmelCase							:     Union[str, os.PathLike]			,						lowerCAmelCase							:     Optional[Union[str, os.PathLike]] = None			,						lowerCAmelCase							:     bool = False			,						lowerCAmelCase							:     bool = False			,						lowerCAmelCase							:     Optional[Union[str, bool]] = None			,						lowerCAmelCase							:     str = "main"			,						**lowerCAmelCase							:     Dict			,						)			->			Tuple:

    """simple docstring"""







    _snake_case      :					Dict					=   cache_dir
    _snake_case      :					Optional[Any]					=   force_download
    _snake_case      :					Dict					=   local_files_only
    _snake_case      :					Any					=   revision

    _snake_case      :					Dict					=   kwargs.pop("""use_auth_token"""			,						lowerCAmelCase)
    if use_auth_token is not None:
     warnings.warn(
         """The `use_auth_token` argument is deprecated and will be removed in v5 of Transformers."""			,						lowerCAmelCase)
     if token is not None:
      raise ValueError(
          """`token` and `use_auth_token` are both specified. Please set only the argument `token`.""")
     _snake_case      :					str					=   use_auth_token

    if token is not None:
     # change to `token` in a follow-up PR
     _snake_case      :					Tuple					=   token

    _snake_case      :					Tuple					=   cls._get_arguments_from_pretrained(lowerCAmelCase			,						**lowerCAmelCase)
    return cls(*lowerCAmelCase)

   @classmethod
   def        UpperCamelCase_					(   cls							:     Optional[Any]			,						lowerCAmelCase							:     str="AutoProcessor")			->			int:

    """simple docstring"""







    if not isinstance(lowerCAmelCase			,						lowerCAmelCase):
     _snake_case      :					List[Any]					=   auto_class.__name__

    import transformers.models.auto as auto_module

    if not hasattr(lowerCAmelCase			,						lowerCAmelCase):
     raise ValueError(F'''{auto_class} is not a valid auto class.''')

    _snake_case      :					List[str]					=   auto_class

   @classmethod
   def        UpperCamelCase_					(   cls							:     List[Any]			,						lowerCAmelCase							:     Any			,						**lowerCAmelCase							:     Union[str, Any])			->			Optional[Any]:

    """simple docstring"""







    _snake_case      :					Optional[Any]					=   []
    for attribute_name in cls.attributes:
     _snake_case      :					Optional[Any]					=   getattr(cls			,						F'''{attribute_name}_class''')
     if isinstance(lowerCAmelCase			,						lowerCAmelCase):
      _snake_case      :					Tuple					=   tuple(getattr(lowerCAmelCase			,						lowerCAmelCase) if n is not None else None for n in class_name)
      _snake_case      :					str					=   kwargs.get("""use_fast"""			,						lowerCAmelCase)
      if use_fast and classes[1] is not None:
       _snake_case      :					Any					=   classes[1]
      else:
       _snake_case      :					Union[str, Any]					=   classes[0]
     else:
      _snake_case      :					Optional[Any]					=   getattr(lowerCAmelCase			,						lowerCAmelCase)

     args.append(attribute_class.from_pretrained(lowerCAmelCase			,						**lowerCAmelCase))
    return args


   @property
   def        UpperCamelCase_					(   self							:     Optional[int])			->			str:

    """simple docstring"""







    _snake_case      :					Tuple					=   getattr(self			,						self.attributes[0])
    return getattr(lowerCAmelCase			,						"""model_input_names"""			,						lowerCAmelCase)
a__      =		copy_func(ProcessorMixin.push_to_hub)
if ProcessorMixin.push_to_hub.__doc__ is not None:
  a__      =		ProcessorMixin.push_to_hub.__doc__.format(
      object="""processor""", object_class="""AutoProcessor""", object_files="""processor files"""
  )
