



import csv
import dataclasses
import json
from dataclasses import dataclass
from typing import List, Optional, Union

from ...utils import is_tf_available, is_torch_available, logging


__lowerCamelCase								=   logging.get_logger(__name__)



@dataclass
class 						_snake_case :





 """simple docstring"""



 lowerCamelCase_       =     42
 lowerCamelCase_       =     42
 lowerCamelCase_       =     None
 lowerCamelCase_       =     None
 def lowercase_						(  self   )		->							Optional[Any]:




   """simple docstring"""







   return json.dumps(dataclasses.asdict(self   )		,      indent=2   ) + "\n"







@dataclass(frozen=lowerCamelCase			)
class 						_snake_case :





 """simple docstring"""



 lowerCamelCase_       =     42
 lowerCamelCase_       =     None
 lowerCamelCase_       =     None
 lowerCamelCase_       =     None
 def lowercase_						(  self   )		->							Optional[Any]:




   """simple docstring"""







   return json.dumps(dataclasses.asdict(self   )   ) + "\n"







class 						_snake_case :





 """simple docstring"""



 def lowercase_						(  self		,      a   )		->							Union[str, Any]:




   """simple docstring"""







   raise NotImplementedError()
 def lowercase_						(  self		,      a   )		->							Tuple:




   """simple docstring"""







   raise NotImplementedError()
 def lowercase_						(  self		,      a   )		->							List[Any]:




   """simple docstring"""







   raise NotImplementedError()
 def lowercase_						(  self		,      a   )		->							List[str]:




   """simple docstring"""







   raise NotImplementedError()
 def lowercase_						(  self   )		->							Optional[int]:




   """simple docstring"""







   raise NotImplementedError()
 def lowercase_						(  self		,      a   )		->							int:




   """simple docstring"""







   if len(self.get_labels()   ) > 1:
     _A          =      self.get_labels()[int(example.label   )]
   return example



 @classmethod
 def lowercase_						(  cls		,      a		,      a=None   )		->							int:




   """simple docstring"""







   with open(a		,      '''r'''		,      encoding='''utf-8-sig'''   ) as f:
     return list(csv.reader(a		,      delimiter='''\t'''		,      quotechar=a   )   )







class 						_snake_case (     lowerCamelCase			):





 """simple docstring"""



 def __init__(  self		,      a=None		,      a=None		,      a="classification"		,      a=False   )		->							str:




   """simple docstring"""







   _A          =      [] if labels is None else labels
   _A          =      [] if examples is None else examples
   _A          =      mode
   _A          =      verbose
 def __len__(  self   )		->							List[Any]:




   """simple docstring"""







   return len(self.examples   )
 def __getitem__(  self		,      a   )		->							Dict:




   """simple docstring"""







   if isinstance(a		,      a   ):
     return SingleSentenceClassificationProcessor(labels=self.labels		,      examples=self.examples[idx]   )
   return self.examples[idx]
 @classmethod
 def lowercase_						(  cls		,      a		,      a=""		,      a=0		,      a=1		,      a=None		,      a=False		,      **a   )		->							List[str]:




   """simple docstring"""







   _A          =      cls(**a   )
   processor.add_examples_from_csv(
       a		,      split_name=a		,      column_label=a		,      column_text=a		,      column_id=a		,      skip_first_row=a		,      overwrite_labels=a		,      overwrite_examples=a		,      )
   return processor
 @classmethod
 def lowercase_						(  cls		,      a		,      a=None		,      **a   )		->							Dict:




   """simple docstring"""







   _A          =      cls(**a   )
   processor.add_examples(a		,      labels=a   )
   return processor
 def lowercase_						(  self		,      a		,      a=""		,      a=0		,      a=1		,      a=None		,      a=False		,      a=False		,      a=False		,      )		->							Union[str, Any]:




   """simple docstring"""







   _A          =      self._read_tsv(a   )
   if skip_first_row:
     _A          =      lines[1:]
   _A          =      []
   _A          =      []
   _A          =      []
   for i, line in enumerate(a   ):
     texts.append(line[column_text]   )
     labels.append(line[column_label]   )
     if column_id is not None:
       ids.append(line[column_id]   )
     else:
       _A          =      f'''{split_name}-{i}''' if split_name else str(a   )
       ids.append(a   )

   return self.add_examples(
       a		,      a		,      a		,      overwrite_labels=a		,      overwrite_examples=a   )
 def lowercase_						(  self		,      a		,      a=None		,      a=None		,      a=False		,      a=False   )		->							List[Any]:




   """simple docstring"""







   if labels is not None and len(a   ) != len(a   ):
     raise ValueError(
         f'''Text and labels have mismatched lengths {len(a   )} and {len(a   )}'''   )
   if ids is not None and len(a   ) != len(a   ):
     raise ValueError(f'''Text and ids have mismatched lengths {len(a   )} and {len(a   )}'''   )
   if ids is None:
     _A          =      [None] * len(a   )
   if labels is None:
     _A          =      [None] * len(a   )
   _A          =      []
   _A          =      set()
   for text_or_text_and_label, label, guid in zip(a		,      a		,      a   ):
     if isinstance(a		,      (tuple, list)   ) and label is None:
       _A      ,				_A          =      text_or_text_and_label
     else:
       _A          =      text_or_text_and_label
     added_labels.add(a   )
     examples.append(InputExample(guid=a		,      text_a=a		,      text_b=a		,      label=a   )   )

   # Update examples
   if overwrite_examples:
     _A          =      examples
   else:
     self.examples.extend(a   )

   # Update labels
   if overwrite_labels:
     _A          =      list(a   )
   else:
     _A          =      list(set(self.labels   ).union(a   )   )

   return self.examples



 def lowercase_						(  self		,      a		,      a=None		,      a=False		,      a=0		,      a=True		,      a=None		,      )		->							Any:




   """simple docstring"""







   if max_length is None:
     _A          =      tokenizer.max_len

   _A          =      {label: i for i, label in enumerate(self.labels   )}

   _A          =      []
   for ex_index, example in enumerate(self.examples   ):
     if ex_index % 1_0_0_0_0 == 0:
       logger.info(f'''Tokenizing example {ex_index}'''   )

     _A          =      tokenizer.encode(
         example.text_a		,      add_special_tokens=a		,      max_length=min(a		,      tokenizer.max_len   )		,      )
     all_input_ids.append(a   )

   _A          =      max(len(a   ) for input_ids in all_input_ids   )

   _A          =      []
   for ex_index, (input_ids, example) in enumerate(zip(a		,      self.examples   )   ):
     if ex_index % 1_0_0_0_0 == 0:
       logger.info(f'''Writing example {ex_index}/{len(self.examples   )}'''   )
     # The mask has 1 for real tokens and 0 for padding tokens. Only real
     # tokens are attended to.
     _A          =      [1 if mask_padding_with_zero else 0] * len(a   )

     # Zero-pad up to the sequence length.
     _A          =      batch_length - len(a   )
     if pad_on_left:
       _A          =      ([pad_token] * padding_length) + input_ids
       _A          =      ([0 if mask_padding_with_zero else 1] * padding_length) + attention_mask
     else:
       _A          =      input_ids + ([pad_token] * padding_length)
       _A          =      attention_mask + ([0 if mask_padding_with_zero else 1] * padding_length)

     if len(a   ) != batch_length:
       raise ValueError(f'''Error with input length {len(a   )} vs {batch_length}'''   )
     if len(a   ) != batch_length:
       raise ValueError(f'''Error with input length {len(a   )} vs {batch_length}'''   )

     if self.mode == "classification":
       _A          =      label_map[example.label]
     elif self.mode == "regression":
       _A          =      float(example.label   )
     else:
       raise ValueError(self.mode   )

     if ex_index < 5 and self.verbose:
       logger.info('''*** Example ***'''   )
       logger.info(f'''guid: {example.guid}'''   )
       logger.info(f'''input_ids: {" ".join([str(a   ) for x in input_ids]   )}'''   )
       logger.info(f'''attention_mask: {" ".join([str(a   ) for x in attention_mask]   )}'''   )
       logger.info(f'''label: {example.label} (id = {label})'''   )

     features.append(InputFeatures(input_ids=a		,      attention_mask=a		,      label=a   )   )

   if return_tensors is None:
     return features
   elif return_tensors == "tf":
     if not is_tf_available():
       raise RuntimeError('''return_tensors set to \'tf\' but TensorFlow 2.0 can\'t be imported'''   )
     import tensorflow as tf

     def gen():
       for ex in features:
         yield ({"input_ids": ex.input_ids, "attention_mask": ex.attention_mask}, ex.label)

     _A          =      tf.data.Dataset.from_generator(
         a		,      ({'''input_ids''': tf.intaa, '''attention_mask''': tf.intaa}, tf.intaa)		,      ({'''input_ids''': tf.TensorShape([None]   ), '''attention_mask''': tf.TensorShape([None]   )}, tf.TensorShape([]   ))		,      )
     return dataset
   elif return_tensors == "pt":
     if not is_torch_available():
       raise RuntimeError('''return_tensors set to \'pt\' but PyTorch can\'t be imported'''   )
     import torch
     from torch.utils.data import TensorDataset

     _A          =      torch.tensor([f.input_ids for f in features]		,      dtype=torch.long   )
     _A          =      torch.tensor([f.attention_mask for f in features]		,      dtype=torch.long   )
     if self.mode == "classification":
       _A          =      torch.tensor([f.label for f in features]		,      dtype=torch.long   )
     elif self.mode == "regression":
       _A          =      torch.tensor([f.label for f in features]		,      dtype=torch.float   )

     _A          =      TensorDataset(a		,      a		,      a   )
     return dataset
   else:
     raise ValueError('''return_tensors should be one of \'tf\' or \'pt\''''   )




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   )