import json
import logging
import os
import re
import sys
from dataclasses import dataclass, field
from typing import Any, Dict, List, Optional, Union

import datasets
import numpy as np
import torch
import torchaudio
from packaging import version
from torch import nn

import transformers
from transformers import (
    HfArgumentParser,
    Trainer,
    TrainingArguments,
    WavaVecaCTCTokenizer,
    WavaVecaFeatureExtractor,
    WavaVecaForCTC,
    WavaVecaProcessor,
    is_apex_available,
    set_seed,
)
from transformers.trainer_utils import get_last_checkpoint, is_main_process


if is_apex_available():
      from apex import amp


if version.parse(version.parse(torch.__version__).base_version) >= version.parse('''1.6'''):
      UpperCamelCase  							=						True
      from torch.cuda.amp import autocast

UpperCamelCase  							=						logging.getLogger(__name__)

def 			lowercase_				(			_lowerCamelCase							:       Any=None		,	_lowerCamelCase							:       Tuple=None):
    return field(default_factory=lambda: default		,	metadata=_lowerCamelCase)



@dataclass
class   snake_case_       :
   __A	:		str         =				field(
       metadata={"help": "Path to pretrained model or model identifier from huggingface.co/models"}       )
   __A	:		Optional[str]         =				field(
       default=__A  ,metadata={"help": "Where do you want to store the pretrained models downloaded from huggingface.co"}  ,)
   __A	:		Optional[bool]         =				field(
       default=__A  ,metadata={"help": "Whether to freeze the feature extractor layers of the model."}       )
   __A	:		Optional[float]         =				field(
       default=0.1  ,metadata={"help": "The dropout ratio for the attention probabilities."}       )
   __A	:		Optional[float]         =				field(
       default=0.1  ,metadata={"help": "The dropout ratio for activations inside the fully connected layer."}       )
   __A	:		Optional[float]         =				field(
       default=0.1  ,metadata={
           "help": "The dropout probabilitiy for all fully connected layers in the embeddings, encoder, and pooler."
       }  ,)
   __A	:		Optional[float]         =				field(
       default=0.1  ,metadata={"help": "The dropout probabilitiy for all 1D convolutional layers in feature extractor."}  ,)
   __A	:		Optional[float]         =				field(
       default=0.05  ,metadata={
           "help": (
               "Propability of each feature vector along the time axis to be chosen as the start of the vector"
               "span to be masked. Approximately ``mask_time_prob * sequence_length // mask_time_length`` feature"
               "vectors will be masked along the time axis. This is only relevant if ``apply_spec_augment is True``."
           )
       }  ,)
   __A	:		Optional[float]         =				field(default=0.0  ,metadata={"help": "The LayerDrop probability."}       )



@dataclass
class   snake_case_       :
   __A	:		Optional[str]         =				field(
       default=__A  ,metadata={"help": "The configuration name of the dataset to use (via the datasets library)."}       )
   __A	:		Optional[str]         =				field(
       default="train+validation"  ,metadata={
           "help": "The name of the training data set split to use (via the datasets library). Defaults to 'train'"
       }  ,)
   __A	:		bool         =				field(
       default=__A  ,metadata={"help": "Overwrite the cached preprocessed datasets or not."}       )
   __A	:		Optional[int]         =				field(
       default=__A  ,metadata={"help": "The number of processes to use for the preprocessing."}  ,)
   __A	:		Optional[int]         =				field(
       default=__A  ,metadata={
           "help": (
               "For debugging purposes or quicker training, truncate the number of training examples to this "
               "value if set."
           )
       }  ,)
   __A	:		Optional[int]         =				field(
       default=__A  ,metadata={
           "help": (
               "For debugging purposes or quicker training, truncate the number of validation examples to this "
               "value if set."
           )
       }  ,)
   __A	:		List[str]         =				list_field(
       default=[",", "?", ".", "!", "-", ";", ":", "\"\"", "%", "'", "\"", "�"]  ,metadata={"help": "A list of characters to remove from the transcripts."}  ,)



@dataclass
class   snake_case_       :
   __A	:		WavaVecaProcessor
   __A	:		Union[bool, str]         =				True
   __A	:		Optional[int]         =				None
   __A	:		Optional[int]         =				None
   __A	:		Optional[int]         =				None
   __A	:		Optional[int]         =				None






   def __call__(      self				:     Tuple	,						lowercase_				:     List[Dict[str, Union[List[int], torch.Tensor]]]  )					->						Dict[str, torch.Tensor]:
       # split inputs and labels since they have to be of different lenghts and need
       # different padding methods
       lowercase__ :   Union[str, Any]    					=				[{"input_values": feature["input_values"]} for feature in features]
       lowercase__ :   Optional[int]    					=				[{"input_ids": feature["labels"]} for feature in features]

       lowercase__ :   str    					=				self.processor.pad(
           lowercase_	,						padding=self.padding	,						max_length=self.max_length	,						pad_to_multiple_of=self.pad_to_multiple_of	,						return_tensors="pt"	,						)
       lowercase__ :   str    					=				self.processor.pad(
           labels=lowercase_	,						padding=self.padding	,						max_length=self.max_length_labels	,						pad_to_multiple_of=self.pad_to_multiple_of_labels	,						return_tensors="pt"	,						)

       # replace padding with -100 to ignore loss correctly
       lowercase__ :   Tuple    					=				labels_batch["input_ids"].masked_fill(labels_batch.attention_mask.ne(1  )	,						-1_00  )

       lowercase__ :   str    					=				labels

       return batch



class   snake_case_       (		__A       ):






   def       __UpperCamelCase     (      self				:     Optional[int]	,						lowercase_				:     nn.Module	,						lowercase_				:     Dict[str, Union[torch.Tensor, Any]]  )					->						torch.Tensor:
       model.train()
       lowercase__ :   Optional[int]    					=				self._prepare_inputs(lowercase_  )

       if self.use_amp:
           with autocast():
               lowercase__ :   Optional[Any]    					=				self.compute_loss(lowercase_	,						lowercase_  )
       else:
           lowercase__ :   int    					=				self.compute_loss(lowercase_	,						lowercase_  )

       if self.args.n_gpu > 1:
           if model.module.config.ctc_loss_reduction == "mean":
               lowercase__ :   Optional[Any]    					=				loss.mean()
           elif model.module.config.ctc_loss_reduction == "sum":
               lowercase__ :   List[str]    					=				loss.sum() / (inputs["labels"] >= 0).sum()
           else:
               raise ValueError(F'''{model.config.ctc_loss_reduction} is not valid. Choose one of [\'mean\', \'sum\']'''  )

       if self.args.gradient_accumulation_steps > 1:
           lowercase__ :   Union[str, Any]    					=				loss / self.args.gradient_accumulation_steps

       if self.use_amp:
           self.scaler.scale(lowercase_  ).backward()
       elif self.use_apex:
           with amp.scale_loss(lowercase_	,						self.optimizer  ) as scaled_loss:
               scaled_loss.backward()
       elif self.deepspeed:
           self.deepspeed.backward(lowercase_  )
       else:
           loss.backward()

       return loss.detach()



def 			lowercase_				(			):
    # See all possible arguments in src/transformers/training_args.py
    # or by passing the --help flag to this script.
    # We now keep distinct sets of args, for a cleaner separation of concerns.

    lowercase__ :   Optional[int]    					=				HfArgumentParser((ModelArguments, DataTrainingArguments, TrainingArguments))
    if len(sys.argv) == 2 and sys.argv[1].endswith(".json"):
        # If we pass only one argument to the script and it's the path to a json file,
        # let's parse it to get our arguments.
        lowercase__					,   lowercase__					,   lowercase__ :   Any    					=				parser.parse_json_file(json_file=os.path.abspath(sys.argv[1]))
    else:
        lowercase__					,   lowercase__					,   lowercase__ :   List[str]    					=				parser.parse_args_into_dataclasses()

    # Detecting last checkpoint.
    lowercase__ :   Optional[int]    					=				None
    if os.path.isdir(training_args.output_dir) and training_args.do_train and not training_args.overwrite_output_dir:
        lowercase__ :   Any    					=				get_last_checkpoint(training_args.output_dir)
        if last_checkpoint is None and len(os.listdir(training_args.output_dir)) > 0:
            raise ValueError(
                f'''Output directory ({training_args.output_dir}) already exists and is not empty. '''
                "Use --overwrite_output_dir to overcome.")
        elif last_checkpoint is not None:
            logger.info(
                f'''Checkpoint detected, resuming training at {last_checkpoint}. To avoid this behavior, change '''
                "the `--output_dir` or add `--overwrite_output_dir` to train from scratch.")

    # Setup logging
    logging.basicConfig(
        format="%(asctime)s - %(levelname)s - %(name)s - %(message)s"		,	datefmt="%m/%d/%Y %H:%M:%S"		,	handlers=[logging.StreamHandler(sys.stdout)]		,	)
    logger.setLevel(logging.INFO if is_main_process(training_args.local_rank) else logging.WARN)

    # Log on each process the small summary:
    logger.warning(
        f'''Process rank: {training_args.local_rank}, device: {training_args.device}, n_gpu: {training_args.n_gpu}'''
        + f'''distributed training: {bool(training_args.local_rank != -1)}, 16-bits training: {training_args.fpaa}''')
    # Set the verbosity to info of the Transformers logger (on main process only):
    if is_main_process(training_args.local_rank):
        transformers.utils.logging.set_verbosity_info()
    logger.info("Training/evaluation parameters %s"		,	_lowerCamelCase)

    # Set seed before initializing model.
    set_seed(training_args.seed)

    # Get the datasets:
    lowercase__ :   Any    					=				datasets.load_dataset(
        "common_voice"		,	data_args.dataset_config_name		,	split=data_args.train_split_name)
    lowercase__ :   str    					=				datasets.load_dataset("common_voice"		,	data_args.dataset_config_name		,	split="test")

    # Create and save tokenizer
    lowercase__ :   Optional[Any]    					=				f'''[{"".join(data_args.chars_to_ignore)}]'''

    def remove_special_characters(_lowerCamelCase							:       Dict):
        lowercase__ :   str    					=				re.sub(_lowerCamelCase		,	""		,	batch["sentence"]).lower() + " "
        return batch

    lowercase__ :   Union[str, Any]    					=				train_dataset.map(_lowerCamelCase		,	remove_columns=["sentence"])
    lowercase__ :   List[str]    					=				eval_dataset.map(_lowerCamelCase		,	remove_columns=["sentence"])

    def extract_all_chars(_lowerCamelCase							:       List[str]):
        lowercase__ :   Optional[int]    					=				" ".join(batch["text"])
        lowercase__ :   Optional[int]    					=				list(set(_lowerCamelCase))
        return {"vocab": [vocab], "all_text": [all_text]}

    lowercase__ :   Any    					=				train_dataset.map(
        _lowerCamelCase		,	batched=_lowerCamelCase		,	batch_size=-1		,	keep_in_memory=_lowerCamelCase		,	remove_columns=train_dataset.column_names		,	)
    lowercase__ :   Optional[Any]    					=				train_dataset.map(
        _lowerCamelCase		,	batched=_lowerCamelCase		,	batch_size=-1		,	keep_in_memory=_lowerCamelCase		,	remove_columns=eval_dataset.column_names		,	)

    lowercase__ :   str    					=				list(set(vocab_train["vocab"][0]) | set(vocab_test["vocab"][0]))
    lowercase__ :   Optional[Any]    					=				{v: k for k, v in enumerate(_lowerCamelCase)}
    lowercase__ :   Optional[int]    					=				vocab_dict[" "]
    del vocab_dict[" "]
    lowercase__ :   str    					=				len(_lowerCamelCase)
    lowercase__ :   int    					=				len(_lowerCamelCase)

    with open("vocab.json"		,	"w") as vocab_file:
        json.dump(_lowerCamelCase		,	_lowerCamelCase)

    # Load pretrained model and tokenizer
    #
    # Distributed training:
    # The .from_pretrained methods guarantee that only one local process can concurrently
    # download model & vocab.
    lowercase__ :   List[str]    					=				WavaVecaCTCTokenizer(
        "vocab.json"		,	unk_token="[UNK]"		,	pad_token="[PAD]"		,	word_delimiter_token="|"		,	)
    lowercase__ :   List[Any]    					=				WavaVecaFeatureExtractor(
        feature_size=1		,	sampling_rate=1_6000		,	padding_value=0.0		,	do_normalize=_lowerCamelCase		,	return_attention_mask=_lowerCamelCase)
    lowercase__ :   Dict    					=				WavaVecaProcessor(feature_extractor=_lowerCamelCase		,	tokenizer=_lowerCamelCase)
    lowercase__ :   List[str]    					=				WavaVecaForCTC.from_pretrained(
        model_args.model_name_or_path		,	cache_dir=model_args.cache_dir		,	activation_dropout=model_args.activation_dropout		,	attention_dropout=model_args.attention_dropout		,	hidden_dropout=model_args.hidden_dropout		,	feat_proj_dropout=model_args.feat_proj_dropout		,	mask_time_prob=model_args.mask_time_prob		,	gradient_checkpointing=training_args.gradient_checkpointing		,	layerdrop=model_args.layerdrop		,	ctc_loss_reduction="mean"		,	pad_token_id=processor.tokenizer.pad_token_id		,	vocab_size=len(processor.tokenizer)		,	)

    if data_args.max_train_samples is not None:
        lowercase__ :   Union[str, Any]    					=				min(len(_lowerCamelCase)		,	data_args.max_train_samples)
        lowercase__ :   Union[str, Any]    					=				train_dataset.select(range(_lowerCamelCase))

    if data_args.max_val_samples is not None:
        lowercase__ :   List[Any]    					=				eval_dataset.select(range(data_args.max_val_samples))

    lowercase__ :   Optional[Any]    					=				torchaudio.transforms.Resample(4_8000		,	1_6000)

    # Preprocessing the datasets.
    # We need to read the aduio files as arrays and tokenize the targets.
    def speech_file_to_array_fn(_lowerCamelCase							:       int):
        lowercase__					,   lowercase__ :   List[str]    					=				torchaudio.load(batch["path"])
        lowercase__ :   Optional[Any]    					=				resampler(_lowerCamelCase).squeeze().numpy()
        lowercase__ :   List[Any]    					=				1_6000
        lowercase__ :   Optional[int]    					=				batch["text"]
        return batch

    lowercase__ :   Union[str, Any]    					=				train_dataset.map(
        _lowerCamelCase		,	remove_columns=train_dataset.column_names		,	num_proc=data_args.preprocessing_num_workers		,	)
    lowercase__ :   str    					=				eval_dataset.map(
        _lowerCamelCase		,	remove_columns=eval_dataset.column_names		,	num_proc=data_args.preprocessing_num_workers		,	)

    def prepare_dataset(_lowerCamelCase							:       int):
        # check that all files have the correct sampling rate
        assert (
            len(set(batch["sampling_rate"])) == 1
        ), f'''Make sure all inputs have the same sampling rate of {processor.feature_extractor.sampling_rate}.'''

        lowercase__ :   Union[str, Any]    					=				processor(
            audio=batch["speech"]		,	text=batch["target_text"]		,	sampling_rate=batch["sampling_rate"][0])
        batch.update(_lowerCamelCase)
        return batch

    lowercase__ :   str    					=				train_dataset.map(
        _lowerCamelCase		,	remove_columns=train_dataset.column_names		,	batch_size=training_args.per_device_train_batch_size		,	batched=_lowerCamelCase		,	num_proc=data_args.preprocessing_num_workers		,	)
    lowercase__ :   Tuple    					=				eval_dataset.map(
        _lowerCamelCase		,	remove_columns=eval_dataset.column_names		,	batch_size=training_args.per_device_train_batch_size		,	batched=_lowerCamelCase		,	num_proc=data_args.preprocessing_num_workers		,	)

    # Metric
    lowercase__ :   str    					=				datasets.load_metric("wer")

    def compute_metrics(_lowerCamelCase							:       Optional[Any]):
        lowercase__ :   str    					=				pred.predictions
        lowercase__ :   str    					=				np.argmax(_lowerCamelCase		,	axis=-1)

        lowercase__ :   int    					=				processor.tokenizer.pad_token_id

        lowercase__ :   str    					=				processor.batch_decode(_lowerCamelCase)
        # we do not want to group tokens when computing the metrics
        lowercase__ :   Optional[Any]    					=				processor.batch_decode(pred.label_ids		,	group_tokens=_lowerCamelCase)

        lowercase__ :   Tuple    					=				wer_metric.compute(predictions=_lowerCamelCase		,	references=_lowerCamelCase)

        return {"wer": wer}

    if model_args.freeze_feature_extractor:
        model.freeze_feature_extractor()

    # Data collator
    lowercase__ :   List[str]    					=				DataCollatorCTCWithPadding(processor=_lowerCamelCase		,	padding=_lowerCamelCase)

    # Initialize our Trainer
    lowercase__ :   Optional[int]    					=				CTCTrainer(
        model=_lowerCamelCase		,	data_collator=_lowerCamelCase		,	args=_lowerCamelCase		,	compute_metrics=_lowerCamelCase		,	train_dataset=train_dataset if training_args.do_train else None		,	eval_dataset=eval_dataset if training_args.do_eval else None		,	tokenizer=processor.feature_extractor		,	)

    # Training
    if training_args.do_train:
        if last_checkpoint is not None:
            lowercase__ :   List[str]    					=				last_checkpoint
        elif os.path.isdir(model_args.model_name_or_path):
            lowercase__ :   Union[str, Any]    					=				model_args.model_name_or_path
        else:
            lowercase__ :   Union[str, Any]    					=				None

        # Save the feature_extractor and the tokenizer
        if is_main_process(training_args.local_rank):
            processor.save_pretrained(training_args.output_dir)

        lowercase__ :   List[str]    					=				trainer.train(resume_from_checkpoint=_lowerCamelCase)
        trainer.save_model()

        lowercase__ :   Union[str, Any]    					=				train_result.metrics
        lowercase__ :   int    					=				(
            data_args.max_train_samples if data_args.max_train_samples is not None else len(_lowerCamelCase)
        )
        lowercase__ :   int    					=				min(_lowerCamelCase		,	len(_lowerCamelCase))

        trainer.log_metrics("train"		,	_lowerCamelCase)
        trainer.save_metrics("train"		,	_lowerCamelCase)
        trainer.save_state()

    # Evaluation
    lowercase__ :   Optional[Any]    					=				{}
    if training_args.do_eval:
        logger.info("*** Evaluate ***")
        lowercase__ :   Any    					=				trainer.evaluate()
        lowercase__ :   List[str]    					=				data_args.max_val_samples if data_args.max_val_samples is not None else len(_lowerCamelCase)
        lowercase__ :   Union[str, Any]    					=				min(_lowerCamelCase		,	len(_lowerCamelCase))

        trainer.log_metrics("eval"		,	_lowerCamelCase)
        trainer.save_metrics("eval"		,	_lowerCamelCase)

    return results


if __name__ == "__main__":
      main()










"""simple docstring"""
import gc
import unittest

import numpy as np
import torch
from torch.backends.cuda import sdp_kernel

from diffusers import (
    CMStochasticIterativeScheduler,
    ConsistencyModelPipeline,
    UNetaDModel,
)
from diffusers.utils import randn_tensor, slow, torch_device
from diffusers.utils.testing_utils import enable_full_determinism, require_torch_a, require_torch_gpu

from ..pipeline_params import UNCONDITIONAL_IMAGE_GENERATION_BATCH_PARAMS, UNCONDITIONAL_IMAGE_GENERATION_PARAMS
from ..test_pipelines_common import PipelineTesterMixin


enable_full_determinism()






class 					_SCREAMING_SNAKE_CASE(   A    ,	unittest.TestCase  ):
       SCREAMING_SNAKE_CASE_   :      Optional[Any]							=  ConsistencyModelPipeline
       SCREAMING_SNAKE_CASE_   :      Any							=  UNCONDITIONAL_IMAGE_GENERATION_PARAMS
       SCREAMING_SNAKE_CASE_   :      Dict							=  UNCONDITIONAL_IMAGE_GENERATION_BATCH_PARAMS

       # Override required_optional_params to remove num_images_per_prompt
       SCREAMING_SNAKE_CASE_   :      Optional[Any]							=  frozenset(
           [
               '''num_inference_steps''',
               '''generator''',
               '''latents''',
               '''output_type''',
               '''return_dict''',
               '''callback''',
               '''callback_steps''',
           ]  )




       @property
       def     _UpperCamelCase     (						self							)			->      Tuple:





             """simple docstring"""






             __SCREAMING_SNAKE_CASE   :Tuple						=  UNetaDModel.from_pretrained(
                 '''diffusers/consistency-models-test'''		,subfolder='''test_unet'''		,)
             return unet




       @property
       def     _UpperCamelCase     (						self							)			->      List[Any]:





             """simple docstring"""






             __SCREAMING_SNAKE_CASE   :Optional[int]						=  UNetaDModel.from_pretrained(
                 '''diffusers/consistency-models-test'''		,subfolder='''test_unet_class_cond'''		,)
             return unet




       def     _UpperCamelCase     (						self		,SCREAMING_SNAKE_CASE__=False							)			->      Union[str, Any]:





             """simple docstring"""






             if class_cond:
                   __SCREAMING_SNAKE_CASE   :str						=  self.dummy_cond_unet
             else:
                   __SCREAMING_SNAKE_CASE   :Optional[Any]						=  self.dummy_uncond_unet

             # Default to CM multistep sampler
             __SCREAMING_SNAKE_CASE   :List[str]						=  CMStochasticIterativeScheduler(
                 num_train_timesteps=40		,sigma_min=0.0_0_2		,sigma_max=8_0.0		,)

             __SCREAMING_SNAKE_CASE   :List[str]						=  {
                 '''unet''': unet,
                 '''scheduler''': scheduler,
             }

             return components




       def     _UpperCamelCase     (						self		,SCREAMING_SNAKE_CASE__		,SCREAMING_SNAKE_CASE__=0							)			->      Dict:





             """simple docstring"""






             if str(SCREAMING_SNAKE_CASE__							).startswith('''mps'''							):
                   __SCREAMING_SNAKE_CASE   :Tuple						=  torch.manual_seed(SCREAMING_SNAKE_CASE__							)
             else:
                   __SCREAMING_SNAKE_CASE   :Optional[Any]						=  torch.Generator(device=SCREAMING_SNAKE_CASE__							).manual_seed(SCREAMING_SNAKE_CASE__							)

             __SCREAMING_SNAKE_CASE   :Dict						=  {
                 '''batch_size''': 1,
                 '''num_inference_steps''': None,
                 '''timesteps''': [22, 0],
                 '''generator''': generator,
                 '''output_type''': '''np''',
             }

             return inputs




       def     _UpperCamelCase     (						self							)			->      str:





             """simple docstring"""






             __SCREAMING_SNAKE_CASE   :Union[str, Any]						=  '''cpu'''  # ensure determinism for the device-dependent torch.Generator
             __SCREAMING_SNAKE_CASE   :List[str]						=  self.get_dummy_components()
             __SCREAMING_SNAKE_CASE   :Optional[Any]						=  ConsistencyModelPipeline(**SCREAMING_SNAKE_CASE__							)
             __SCREAMING_SNAKE_CASE   :str						=  pipe.to(SCREAMING_SNAKE_CASE__							)
             pipe.set_progress_bar_config(disable=SCREAMING_SNAKE_CASE__							)

             __SCREAMING_SNAKE_CASE   :Tuple						=  self.get_dummy_inputs(SCREAMING_SNAKE_CASE__							)
             __SCREAMING_SNAKE_CASE   :int						=  pipe(**SCREAMING_SNAKE_CASE__							).images
             assert image.shape == (1, 32, 32, 3)

             __SCREAMING_SNAKE_CASE   :List[str]						=  image[0, -3:, -3:, -1]
             __SCREAMING_SNAKE_CASE   :Any						=  np.array([0.3_5_7_2, 0.6_2_7_3, 0.4_0_3_1, 0.3_9_6_1, 0.4_3_2_1, 0.5_7_3_0, 0.5_2_6_6, 0.4_7_8_0, 0.5_0_0_4]							)

             assert np.abs(image_slice.flatten() - expected_slice							).max() < 1E-3




       def     _UpperCamelCase     (						self							)			->      Dict:





             """simple docstring"""






             __SCREAMING_SNAKE_CASE   :Union[str, Any]						=  '''cpu'''  # ensure determinism for the device-dependent torch.Generator
             __SCREAMING_SNAKE_CASE   :List[Any]						=  self.get_dummy_components(class_cond=SCREAMING_SNAKE_CASE__							)
             __SCREAMING_SNAKE_CASE   :str						=  ConsistencyModelPipeline(**SCREAMING_SNAKE_CASE__							)
             __SCREAMING_SNAKE_CASE   :Optional[int]						=  pipe.to(SCREAMING_SNAKE_CASE__							)
             pipe.set_progress_bar_config(disable=SCREAMING_SNAKE_CASE__							)

             __SCREAMING_SNAKE_CASE   :Union[str, Any]						=  self.get_dummy_inputs(SCREAMING_SNAKE_CASE__							)
             __SCREAMING_SNAKE_CASE   :Optional[int]						=  0
             __SCREAMING_SNAKE_CASE   :Optional[int]						=  pipe(**SCREAMING_SNAKE_CASE__							).images
             assert image.shape == (1, 32, 32, 3)

             __SCREAMING_SNAKE_CASE   :Dict						=  image[0, -3:, -3:, -1]
             __SCREAMING_SNAKE_CASE   :List[Any]						=  np.array([0.3_5_7_2, 0.6_2_7_3, 0.4_0_3_1, 0.3_9_6_1, 0.4_3_2_1, 0.5_7_3_0, 0.5_2_6_6, 0.4_7_8_0, 0.5_0_0_4]							)

             assert np.abs(image_slice.flatten() - expected_slice							).max() < 1E-3




       def     _UpperCamelCase     (						self							)			->      List[Any]:





             """simple docstring"""






             __SCREAMING_SNAKE_CASE   :List[str]						=  '''cpu'''  # ensure determinism for the device-dependent torch.Generator
             __SCREAMING_SNAKE_CASE   :Tuple						=  self.get_dummy_components()
             __SCREAMING_SNAKE_CASE   :Any						=  ConsistencyModelPipeline(**SCREAMING_SNAKE_CASE__							)
             __SCREAMING_SNAKE_CASE   :List[str]						=  pipe.to(SCREAMING_SNAKE_CASE__							)
             pipe.set_progress_bar_config(disable=SCREAMING_SNAKE_CASE__							)

             __SCREAMING_SNAKE_CASE   :str						=  self.get_dummy_inputs(SCREAMING_SNAKE_CASE__							)
             __SCREAMING_SNAKE_CASE   :Dict						=  1
             __SCREAMING_SNAKE_CASE   :List[str]						=  None
             __SCREAMING_SNAKE_CASE   :List[str]						=  pipe(**SCREAMING_SNAKE_CASE__							).images
             assert image.shape == (1, 32, 32, 3)

             __SCREAMING_SNAKE_CASE   :List[str]						=  image[0, -3:, -3:, -1]
             __SCREAMING_SNAKE_CASE   :int						=  np.array([0.5_0_0_4, 0.5_0_0_4, 0.4_9_9_4, 0.5_0_0_8, 0.4_9_7_6, 0.5_0_1_8, 0.4_9_9_0, 0.4_9_8_2, 0.4_9_8_7]							)

             assert np.abs(image_slice.flatten() - expected_slice							).max() < 1E-3




       def     _UpperCamelCase     (						self							)			->      Any:





             """simple docstring"""






             __SCREAMING_SNAKE_CASE   :str						=  '''cpu'''  # ensure determinism for the device-dependent torch.Generator
             __SCREAMING_SNAKE_CASE   :Any						=  self.get_dummy_components(class_cond=SCREAMING_SNAKE_CASE__							)
             __SCREAMING_SNAKE_CASE   :str						=  ConsistencyModelPipeline(**SCREAMING_SNAKE_CASE__							)
             __SCREAMING_SNAKE_CASE   :Dict						=  pipe.to(SCREAMING_SNAKE_CASE__							)
             pipe.set_progress_bar_config(disable=SCREAMING_SNAKE_CASE__							)

             __SCREAMING_SNAKE_CASE   :str						=  self.get_dummy_inputs(SCREAMING_SNAKE_CASE__							)
             __SCREAMING_SNAKE_CASE   :int						=  1
             __SCREAMING_SNAKE_CASE   :Optional[Any]						=  None
             __SCREAMING_SNAKE_CASE   :List[Any]						=  0
             __SCREAMING_SNAKE_CASE   :Any						=  pipe(**SCREAMING_SNAKE_CASE__							).images
             assert image.shape == (1, 32, 32, 3)

             __SCREAMING_SNAKE_CASE   :int						=  image[0, -3:, -3:, -1]
             __SCREAMING_SNAKE_CASE   :Optional[Any]						=  np.array([0.5_0_0_4, 0.5_0_0_4, 0.4_9_9_4, 0.5_0_0_8, 0.4_9_7_6, 0.5_0_1_8, 0.4_9_9_0, 0.4_9_8_2, 0.4_9_8_7]							)

             assert np.abs(image_slice.flatten() - expected_slice							).max() < 1E-3






@slow
@require_torch_gpu
class 					_SCREAMING_SNAKE_CASE(   unittest.TestCase  ):




       def     _UpperCamelCase     (						self							)			->      List[str]:





             """simple docstring"""






             super().tearDown()
             gc.collect()
             torch.cuda.empty_cache()




       def     _UpperCamelCase     (						self		,SCREAMING_SNAKE_CASE__=0		,SCREAMING_SNAKE_CASE__=False		,SCREAMING_SNAKE_CASE__="cpu"		,SCREAMING_SNAKE_CASE__=torch.floataa		,SCREAMING_SNAKE_CASE__=(1, 3, 64, 64)							)			->      Dict:





             """simple docstring"""






             __SCREAMING_SNAKE_CASE   :Tuple						=  torch.manual_seed(SCREAMING_SNAKE_CASE__							)

             __SCREAMING_SNAKE_CASE   :Tuple						=  {
                 '''num_inference_steps''': None,
                 '''timesteps''': [22, 0],
                 '''class_labels''': 0,
                 '''generator''': generator,
                 '''output_type''': '''np''',
             }

             if get_fixed_latents:
                   __SCREAMING_SNAKE_CASE   :int						=  self.get_fixed_latents(seed=SCREAMING_SNAKE_CASE__		,device=SCREAMING_SNAKE_CASE__		,dtype=SCREAMING_SNAKE_CASE__		,shape=SCREAMING_SNAKE_CASE__							)
                   __SCREAMING_SNAKE_CASE   :int						=  latents

             return inputs




       def     _UpperCamelCase     (						self		,SCREAMING_SNAKE_CASE__=0		,SCREAMING_SNAKE_CASE__="cpu"		,SCREAMING_SNAKE_CASE__=torch.floataa		,SCREAMING_SNAKE_CASE__=(1, 3, 64, 64)							)			->      int:





             """simple docstring"""






             if type(SCREAMING_SNAKE_CASE__							) == str:
                   __SCREAMING_SNAKE_CASE   :int						=  torch.device(SCREAMING_SNAKE_CASE__							)
             __SCREAMING_SNAKE_CASE   :Optional[int]						=  torch.Generator(device=SCREAMING_SNAKE_CASE__							).manual_seed(SCREAMING_SNAKE_CASE__							)
             __SCREAMING_SNAKE_CASE   :int						=  randn_tensor(SCREAMING_SNAKE_CASE__		,generator=SCREAMING_SNAKE_CASE__		,device=SCREAMING_SNAKE_CASE__		,dtype=SCREAMING_SNAKE_CASE__							)
             return latents




       def     _UpperCamelCase     (						self							)			->      Any:





             """simple docstring"""






             __SCREAMING_SNAKE_CASE   :List[Any]						=  UNetaDModel.from_pretrained('''diffusers/consistency_models'''		,subfolder='''diffusers_cd_imagenet64_l2'''							)
             __SCREAMING_SNAKE_CASE   :List[str]						=  CMStochasticIterativeScheduler(
                 num_train_timesteps=40		,sigma_min=0.0_0_2		,sigma_max=8_0.0		,)
             __SCREAMING_SNAKE_CASE   :Dict						=  ConsistencyModelPipeline(unet=SCREAMING_SNAKE_CASE__		,scheduler=SCREAMING_SNAKE_CASE__							)
             pipe.to(torch_device=SCREAMING_SNAKE_CASE__							)
             pipe.set_progress_bar_config(disable=SCREAMING_SNAKE_CASE__							)

             __SCREAMING_SNAKE_CASE   :int						=  self.get_inputs()
             __SCREAMING_SNAKE_CASE   :List[str]						=  pipe(**SCREAMING_SNAKE_CASE__							).images
             assert image.shape == (1, 64, 64, 3)

             __SCREAMING_SNAKE_CASE   :Union[str, Any]						=  image[0, -3:, -3:, -1]

             __SCREAMING_SNAKE_CASE   :Dict						=  np.array([0.0_8_8_8, 0.0_8_8_1, 0.0_6_6_6, 0.0_4_7_9, 0.0_2_9_2, 0.0_1_9_5, 0.0_2_0_1, 0.0_1_6_3, 0.0_2_5_4]							)

             assert np.abs(image_slice.flatten() - expected_slice							).max() < 2E-2




       def     _UpperCamelCase     (						self							)			->      List[Any]:





             """simple docstring"""






             __SCREAMING_SNAKE_CASE   :List[Any]						=  UNetaDModel.from_pretrained('''diffusers/consistency_models'''		,subfolder='''diffusers_cd_imagenet64_l2'''							)
             __SCREAMING_SNAKE_CASE   :List[Any]						=  CMStochasticIterativeScheduler(
                 num_train_timesteps=40		,sigma_min=0.0_0_2		,sigma_max=8_0.0		,)
             __SCREAMING_SNAKE_CASE   :Any						=  ConsistencyModelPipeline(unet=SCREAMING_SNAKE_CASE__		,scheduler=SCREAMING_SNAKE_CASE__							)
             pipe.to(torch_device=SCREAMING_SNAKE_CASE__							)
             pipe.set_progress_bar_config(disable=SCREAMING_SNAKE_CASE__							)

             __SCREAMING_SNAKE_CASE   :Optional[int]						=  self.get_inputs()
             __SCREAMING_SNAKE_CASE   :int						=  1
             __SCREAMING_SNAKE_CASE   :int						=  None
             __SCREAMING_SNAKE_CASE   :Union[str, Any]						=  pipe(**SCREAMING_SNAKE_CASE__							).images
             assert image.shape == (1, 64, 64, 3)

             __SCREAMING_SNAKE_CASE   :str						=  image[0, -3:, -3:, -1]

             __SCREAMING_SNAKE_CASE   :List[str]						=  np.array([0.0_3_4_0, 0.0_1_5_2, 0.0_0_6_3, 0.0_2_6_7, 0.0_2_2_1, 0.0_1_0_7, 0.0_4_1_6, 0.0_1_8_6, 0.0_2_1_7]							)

             assert np.abs(image_slice.flatten() - expected_slice							).max() < 2E-2




       @require_torch_a
       def     _UpperCamelCase     (						self							)			->      str:





             """simple docstring"""






             __SCREAMING_SNAKE_CASE   :List[Any]						=  UNetaDModel.from_pretrained('''diffusers/consistency_models'''		,subfolder='''diffusers_cd_imagenet64_l2'''							)
             __SCREAMING_SNAKE_CASE   :Any						=  CMStochasticIterativeScheduler(
                 num_train_timesteps=40		,sigma_min=0.0_0_2		,sigma_max=8_0.0		,)
             __SCREAMING_SNAKE_CASE   :Any						=  ConsistencyModelPipeline(unet=SCREAMING_SNAKE_CASE__		,scheduler=SCREAMING_SNAKE_CASE__							)
             pipe.to(torch_device=SCREAMING_SNAKE_CASE__		,torch_dtype=torch.floataa							)
             pipe.set_progress_bar_config(disable=SCREAMING_SNAKE_CASE__							)

             __SCREAMING_SNAKE_CASE   :str						=  self.get_inputs(get_fixed_latents=SCREAMING_SNAKE_CASE__		,device=SCREAMING_SNAKE_CASE__							)
             # Ensure usage of flash attention in torch 2.0
             with sdp_kernel(enable_flash=SCREAMING_SNAKE_CASE__		,enable_math=SCREAMING_SNAKE_CASE__		,enable_mem_efficient=SCREAMING_SNAKE_CASE__							):
                   __SCREAMING_SNAKE_CASE   :Optional[Any]						=  pipe(**SCREAMING_SNAKE_CASE__							).images
             assert image.shape == (1, 64, 64, 3)

             __SCREAMING_SNAKE_CASE   :List[str]						=  image[0, -3:, -3:, -1]

             __SCREAMING_SNAKE_CASE   :List[Any]						=  np.array([0.1_8_7_5, 0.1_4_2_8, 0.1_2_8_9, 0.2_1_5_1, 0.2_0_9_2, 0.1_4_7_7, 0.1_8_7_7, 0.1_6_4_1, 0.1_3_5_3]							)

             assert np.abs(image_slice.flatten() - expected_slice							).max() < 1E-3




       @require_torch_a
       def     _UpperCamelCase     (						self							)			->      List[Any]:





             """simple docstring"""






             __SCREAMING_SNAKE_CASE   :str						=  UNetaDModel.from_pretrained('''diffusers/consistency_models'''		,subfolder='''diffusers_cd_imagenet64_l2'''							)
             __SCREAMING_SNAKE_CASE   :Dict						=  CMStochasticIterativeScheduler(
                 num_train_timesteps=40		,sigma_min=0.0_0_2		,sigma_max=8_0.0		,)
             __SCREAMING_SNAKE_CASE   :int						=  ConsistencyModelPipeline(unet=SCREAMING_SNAKE_CASE__		,scheduler=SCREAMING_SNAKE_CASE__							)
             pipe.to(torch_device=SCREAMING_SNAKE_CASE__		,torch_dtype=torch.floataa							)
             pipe.set_progress_bar_config(disable=SCREAMING_SNAKE_CASE__							)

             __SCREAMING_SNAKE_CASE   :Dict						=  self.get_inputs(get_fixed_latents=SCREAMING_SNAKE_CASE__		,device=SCREAMING_SNAKE_CASE__							)
             __SCREAMING_SNAKE_CASE   :int						=  1
             __SCREAMING_SNAKE_CASE   :int						=  None
             # Ensure usage of flash attention in torch 2.0
             with sdp_kernel(enable_flash=SCREAMING_SNAKE_CASE__		,enable_math=SCREAMING_SNAKE_CASE__		,enable_mem_efficient=SCREAMING_SNAKE_CASE__							):
                   __SCREAMING_SNAKE_CASE   :str						=  pipe(**SCREAMING_SNAKE_CASE__							).images
             assert image.shape == (1, 64, 64, 3)

             __SCREAMING_SNAKE_CASE   :str						=  image[0, -3:, -3:, -1]

             __SCREAMING_SNAKE_CASE   :Optional[int]						=  np.array([0.1_6_6_3, 0.1_9_4_8, 0.2_2_7_5, 0.1_6_8_0, 0.1_2_0_4, 0.1_2_4_5, 0.1_8_5_8, 0.1_3_3_8, 0.2_0_9_5]							)

             assert np.abs(image_slice.flatten() - expected_slice							).max() < 1E-3