



import csv
import json
import os

import datasets


# TODO: Add BibTeX citation
# Find for instance the citation on arxiv or on the dataset repo/website
__lowerCamelCase								=   """\
@InProceedings{huggingface:dataset,
title = {A great new dataset},
author={huggingface, Inc.
},
year={2020}
}
"""

# TODO: Add description of the dataset here
# You can copy an official description
__lowerCamelCase								=   """\
This new dataset is designed to solve this great NLP task and is crafted with a lot of care.
"""

# TODO: Add a link to an official homepage for the dataset here
__lowerCamelCase								=   """"""

# TODO: Add the licence for the dataset here if you can find it
__lowerCamelCase								=   """"""

# TODO: Add link to the official dataset URLs here
# The HuggingFace Datasets library doesn't host the datasets but only points to the original files.
# This can be an arbitrary nested dict/list of URLs (see below in `_split_generators` method)
__lowerCamelCase								=   {
    """first_domain""": """https://huggingface.co/great-new-dataset-first_domain.zip""",
    """second_domain""": """https://huggingface.co/great-new-dataset-second_domain.zip""",
}



class 						_snake_case (     datasets.GeneratorBasedBuilder			):





 """simple docstring"""



 lowerCamelCase_       =     datasets.Version('''1.1.0'''			)

 # This is an example of a dataset with multiple configurations.
 # If you don't want/need to define several sub-sets in your dataset,
 # just remove the BUILDER_CONFIG_CLASS and the BUILDER_CONFIGS attributes.

 # If you need to make complex sub-parts in the datasets with configurable options
 # You can create your own builder configuration class to store attribute, inheriting from datasets.BuilderConfig
 # BUILDER_CONFIG_CLASS = MyBuilderConfig

 # You will be able to load one or the other configurations in the following list with
 # data = datasets.load_dataset('my_dataset', 'first_domain')
 # data = datasets.load_dataset('my_dataset', 'second_domain')
 lowerCamelCase_       =     [
     datasets.BuilderConfig(name='''first_domain'''   ,version=lowerCamelCase   ,description='''This part of my dataset covers a first domain'''			),
     datasets.BuilderConfig(name='''second_domain'''   ,version=lowerCamelCase   ,description='''This part of my dataset covers a second domain'''			),
 ]

 lowerCamelCase_       =     '''first_domain'''  # It's not mandatory to have a default configuration. Just use one if it make sense.
 def lowercase_						(  self   )		->							Optional[Any]:




   """simple docstring"""







   if self.config.name == "first_domain":  # This is the name of the configuration selected in BUILDER_CONFIGS above
     _A          =      datasets.Features(
         {
             '''sentence''': datasets.Value('''string'''   ),
             '''option1''': datasets.Value('''string'''   ),
             '''answer''': datasets.Value('''string'''   )
             # These are the features of your dataset like images, labels ...
         }   )
   else:  # This is an example to show how to have different features for "first_domain" and "second_domain"
     _A          =      datasets.Features(
         {
             '''sentence''': datasets.Value('''string'''   ),
             '''option2''': datasets.Value('''string'''   ),
             '''second_domain_answer''': datasets.Value('''string'''   )
             # These are the features of your dataset like images, labels ...
         }   )
   return datasets.DatasetInfo(
       # This is the description that will appear on the datasets page.
       description=_DESCRIPTION		,      features=a		,      homepage=_HOMEPAGE		,      license=_LICENSE		,      citation=_CITATION		,      )
 def lowercase_						(  self		,      a   )		->							List[str]:




   """simple docstring"""







   _A          =      _URLS[self.config.name]
   _A          =      dl_manager.download_and_extract(a   )
   return [
       datasets.SplitGenerator(
           name=datasets.Split.TRAIN		,      gen_kwargs={
               '''filepath''': os.path.join(a		,      '''train.jsonl'''   ),
               '''split''': '''train''',
           }		,      ),
       datasets.SplitGenerator(
           name=datasets.Split.VALIDATION		,      gen_kwargs={
               '''filepath''': os.path.join(a		,      '''dev.jsonl'''   ),
               '''split''': '''dev''',
           }		,      ),
       datasets.SplitGenerator(
           name=datasets.Split.TEST		,      gen_kwargs={
               '''filepath''': os.path.join(a		,      '''test.jsonl'''   ),
               '''split''': '''test'''
           }		,      ),
   ]



 def lowercase_						(  self		,      a		,      a   )		->							Dict:




   """simple docstring"""







   with open(a		,      encoding='''utf-8'''   ) as f:
     for key, row in enumerate(a   ):
       _A          =      json.loads(a   )
       if self.config.name == "first_domain":
         # Yields examples as (key, example) tuples
         yield key, {
             "sentence": data["sentence"],
             "option1": data["option1"],
             "answer": "" if split == "test" else data["answer"],
         }
       else:
         yield key, {
             "sentence": data["sentence"],
             "option2": data["option2"],
             "second_domain_answer": "" if split == "test" else data["second_domain_answer"],
         }




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


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


__lowerCamelCase								=   """
    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 (     lowerCamelCase			):





 """simple docstring"""



 def __init__(  self		,      a		,      a   )		->							None:




   """simple docstring"""







   super().__init__()

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

   _A          =      None
 def lowercase_						(  self		,      a=0   )		->							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'''   )

   _A          =      torch.device(f'''cuda:{gpu_id}'''   )

   if self.device.type != "cpu":
     self.to('''cpu'''		,      silence_dtype_warnings=a   )
     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(a		,      a   )

   if self.safety_checker is not None:
     cpu_offload(self.safety_checker		,      execution_device=a		,      offload_buffers=a   )
 def lowercase_						(  self		,      a=0   )		->							Union[str, Any]:




   """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.'''   )

   _A          =      torch.device(f'''cuda:{gpu_id}'''   )

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

   _A          =      None
   for cpu_offloaded_model in [self.unet]:
     _A      ,				_A          =      cpu_offload_with_hook(a		,      a		,      prev_module_hook=a   )

   if self.safety_checker is not None:
     _A      ,				_A          =      cpu_offload_with_hook(self.safety_checker		,      a		,      prev_module_hook=a   )

   # We'll offload the last model manually.
   _A          =      hook
 @property
 # Copied from diffusers.pipelines.stable_diffusion.pipeline_stable_diffusion.StableDiffusionPipeline._execution_device
 def lowercase_						(  self   )		->							List[Any]:




   """simple docstring"""







   if not hasattr(self.unet		,      '''_hf_hook'''   ):
     return self.device
   for module in self.unet.modules():
     if (
         hasattr(a		,      '''_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 lowercase_						(  self		,      a		,      a		,      a		,      a		,      a		,      a		,      a		,      a=None   )		->							Dict:




   """simple docstring"""







   _A          =      (batch_size, num_channels, height, width)
   if isinstance(a		,      a   ) and len(a   ) != batch_size:
     raise ValueError(
         f'''You have passed a list of generators of length {len(a   )}, 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:
     _A          =      randn_tensor(a		,      generator=a		,      device=a		,      dtype=a   )
   else:
     _A          =      latents.to(device=a		,      dtype=a   )

   # scale the initial noise by the standard deviation required by the scheduler
   _A          =      latents * self.scheduler.init_noise_sigma
   return latents
 def lowercase_						(  self		,      a		,      a = "pil"   )		->							Tuple:




   """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
   _A          =      (sample / 2 + 0.5).clamp(0		,      1   )
   if output_type == "pt":
     return sample

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

   # Output_type must be 'pil'
   _A          =      self.numpy_to_pil(a   )
   return sample
 def lowercase_						(  self		,      a		,      a		,      a=None   )		->							Optional[int]:




   """simple docstring"""







   if self.unet.config.num_class_embeds is not None:
     if isinstance(a		,      a   ):
       _A          =      torch.tensor(a		,      dtype=torch.int   )
     elif isinstance(a		,      a   ):
       assert batch_size == 1, "Batch size must be 1 if classes is an int"
       _A          =      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
       _A          =      torch.randint(0		,      self.unet.config.num_class_embeds		,      size=(batch_size,)   )
     _A          =      class_labels.to(a   )
   else:
     _A          =      None
   return class_labels
 def lowercase_						(  self		,      a		,      a		,      a		,      a		,      a		,      a   )		->							Optional[Any]:




   """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:
     _A          =      (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(a		,      a   ) or callback_steps <= 0)
   ):
     raise ValueError(
         f'''`callback_steps` has to be a positive integer but is {callback_steps} of type'''
         f''' {type(a   )}.'''   )



 @torch.no_grad()
 @replace_example_docstring(a   )
 def __call__(  self		,      a = 1		,      a = None		,      a = 1		,      a = None		,      a = None		,      a = None		,      a = "pil"		,      a = True		,      a = None		,      a = 1		,      )		->							Any:




   """simple docstring"""







   _A          =      self.unet.config.sample_size
   _A          =      self._execution_device

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

   # 2. Prepare image latents
   # Sample image latents x_0 ~ N(0, sigma_0^2 * I)
   _A          =      self.prepare_latents(
       batch_size=a		,      num_channels=self.unet.config.in_channels		,      height=a		,      width=a		,      dtype=self.unet.dtype		,      device=a		,      generator=a		,      latents=a		,      )

   # 3. Handle class_labels for class-conditional models
   _A          =      self.prepare_class_labels(a		,      a		,      class_labels=a   )

   # 4. Prepare timesteps
   if timesteps is not None:
     self.scheduler.set_timesteps(timesteps=a		,      device=a   )
     _A          =      self.scheduler.timesteps
     _A          =      len(a   )
   else:
     self.scheduler.set_timesteps(a   )
     _A          =      self.scheduler.timesteps

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

       _A          =      self.scheduler.step(a		,      a		,      a		,      generator=a   )[0]

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

        # 6. Post-process image sample
   _A          =      self.postprocess_image(a		,      output_type=a   )

   # 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=a   )