


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'''):
     snake_case    :   Tuple	    =					True
     from torch.cuda.amp import autocast

snake_case    :   Optional[int]	    =					logging.getLogger(__name__)
def     __lowerCamelCase						(			UpperCAmelCase_						:		Tuple=None			,  UpperCAmelCase_						:		List[Any]=None						):




      """simple docstring"""





      return field(default_factory=lambda: default			,  metadata=UpperCAmelCase_						)







@dataclass
class 		_snake_case  :
 SCREAMING_SNAKE_CASE__				=	field(
     metadata={'help': 'Path to pretrained model or model identifier from huggingface.co/models'}							)
 SCREAMING_SNAKE_CASE__				=	field(
     default=_snake_case						,   metadata={'help': 'Where do you want to store the pretrained models downloaded from huggingface.co'}						,   )
 SCREAMING_SNAKE_CASE__				=	field(
     default=_snake_case						,   metadata={'help': 'Whether to freeze the feature extractor layers of the model.'}							)
 SCREAMING_SNAKE_CASE__				=	field(
     default=0.1						,   metadata={'help': 'The dropout ratio for the attention probabilities.'}							)
 SCREAMING_SNAKE_CASE__				=	field(
     default=0.1						,   metadata={'help': 'The dropout ratio for activations inside the fully connected layer.'}							)
 SCREAMING_SNAKE_CASE__				=	field(
     default=0.1						,   metadata={
         'help': 'The dropout probabilitiy for all fully connected layers in the embeddings, encoder, and pooler.'
     }						,   )
 SCREAMING_SNAKE_CASE__				=	field(
     default=0.1						,   metadata={'help': 'The dropout probabilitiy for all 1D convolutional layers in feature extractor.'}						,   )
 SCREAMING_SNAKE_CASE__				=	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``.'
         )
     }						,   )
 SCREAMING_SNAKE_CASE__				=	field(default=0.0						,   metadata={'help': 'The LayerDrop probability.'}							)







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







@dataclass
class 		_snake_case  :
 SCREAMING_SNAKE_CASE__				=	42
 SCREAMING_SNAKE_CASE__				=	True
 SCREAMING_SNAKE_CASE__				=	None
 SCREAMING_SNAKE_CASE__				=	None
 SCREAMING_SNAKE_CASE__				=	None
 SCREAMING_SNAKE_CASE__				=	None




 def __call__(		self ,  _lowerCamelCase   ):
       # split inputs and labels since they have to be of different lenghts and need
       # different padding methods
       a						:Any										=	[{'''input_values''': feature['''input_values''']} for feature in features]
       a						:List[str]										=	[{'''input_ids''': feature['''labels''']} for feature in features]

       a						:Dict										=	self.processor.pad(
           _lowerCamelCase ,  padding=self.padding ,  max_length=self.max_length ,  pad_to_multiple_of=self.pad_to_multiple_of ,  return_tensors='''pt''' ,  )
       a						:Union[str, Any]										=	self.processor.pad(
           labels=_lowerCamelCase ,  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
       a						:Any										=	labels_batch['''input_ids'''].masked_fill(labels_batch.attention_mask.ne(1   ) ,  -100   )

       a						:Optional[Any]										=	labels

       return batch







class 		_snake_case  (				_snake_case							):




 def 	SCREAMING_SNAKE_CASE__    (		self ,  _lowerCamelCase ,  _lowerCamelCase   ):
       model.train()
       a						:Union[str, Any]										=	self._prepare_inputs(_lowerCamelCase   )

       if self.use_amp:
             with autocast():
                   a						:Any										=	self.compute_loss(_lowerCamelCase ,  _lowerCamelCase   )
       else:
             a						:List[Any]										=	self.compute_loss(_lowerCamelCase ,  _lowerCamelCase   )

       if self.args.n_gpu > 1:
             if model.module.config.ctc_loss_reduction == "mean":
                   a						:Optional[int]										=	loss.mean()
             elif model.module.config.ctc_loss_reduction == "sum":
                   a						:Optional[Any]										=	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:
             a						:Union[str, Any]										=	loss / self.args.gradient_accumulation_steps

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

       return loss.detach()







def     __lowerCamelCase						(			):




      """simple docstring"""





      a						:str										=	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.
            a							,    a							,    a						:List[str]										=	parser.parse_json_file(json_file=os.path.abspath(sys.argv[1]						)						)
      else:
            a							,    a							,    a						:Tuple										=	parser.parse_args_into_dataclasses()

      # Detecting last checkpoint.
      a						:int										=	None
      if os.path.isdir(training_args.output_dir						) and training_args.do_train and not training_args.overwrite_output_dir:
            a						:Union[str, 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'''			,  UpperCAmelCase_						)

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

      # Get the datasets:
      a						:List[Any]										=	datasets.load_dataset(
          '''common_voice'''			,  data_args.dataset_config_name			,  split=data_args.train_split_name						)
      a						:Union[str, Any]										=	datasets.load_dataset('''common_voice'''			,  data_args.dataset_config_name			,  split='''test'''						)

      # Create and save tokenizer
      a						:Any										=	F'''[{''.join(data_args.chars_to_ignore						)}]'''

      def remove_special_characters(UpperCAmelCase_						:		Tuple						):
            a						:Union[str, Any]										=	re.sub(UpperCAmelCase_			,  ''''''			,  batch['''sentence''']						).lower() + ''' '''
            return batch

      a						:Dict										=	train_dataset.map(UpperCAmelCase_			,  remove_columns=['''sentence''']						)
      a						:str										=	eval_dataset.map(UpperCAmelCase_			,  remove_columns=['''sentence''']						)

      def extract_all_chars(UpperCAmelCase_						:		Optional[int]						):
            a						:List[Any]										=	''' '''.join(batch['''text''']						)
            a						:int										=	list(set(UpperCAmelCase_						)						)
            return {"vocab": [vocab], "all_text": [all_text]}

      a						:Tuple										=	train_dataset.map(
          UpperCAmelCase_			,  batched=UpperCAmelCase_			,  batch_size=-1			,  keep_in_memory=UpperCAmelCase_			,  remove_columns=train_dataset.column_names			,  )
      a						:Optional[int]										=	train_dataset.map(
          UpperCAmelCase_			,  batched=UpperCAmelCase_			,  batch_size=-1			,  keep_in_memory=UpperCAmelCase_			,  remove_columns=eval_dataset.column_names			,  )

      a						:Dict										=	list(set(vocab_train['''vocab'''][0]						) | set(vocab_test['''vocab'''][0]						)						)
      a						:List[Any]										=	{v: k for k, v in enumerate(UpperCAmelCase_						)}
      a						:Dict										=	vocab_dict[''' ''']
      del vocab_dict[" "]
      a						:str										=	len(UpperCAmelCase_						)
      a						:Dict										=	len(UpperCAmelCase_						)

      with open('''vocab.json'''			,  '''w'''						) as vocab_file:
            json.dump(UpperCAmelCase_			,  UpperCAmelCase_						)

      # Load pretrained model and tokenizer
      #
      # Distributed training:
      # The .from_pretrained methods guarantee that only one local process can concurrently
      # download model & vocab.
      a						:Optional[Any]										=	WavaVecaCTCTokenizer(
          '''vocab.json'''			,  unk_token='''[UNK]'''			,  pad_token='''[PAD]'''			,  word_delimiter_token='''|'''			,  )
      a						:str										=	WavaVecaFeatureExtractor(
          feature_size=1			,  sampling_rate=1_6000			,  padding_value=0.0			,  do_normalize=UpperCAmelCase_			,  return_attention_mask=UpperCAmelCase_						)
      a						:Dict										=	WavaVecaProcessor(feature_extractor=UpperCAmelCase_			,  tokenizer=UpperCAmelCase_						)
      a						:Optional[int]										=	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:
            a						:List[Any]										=	min(len(UpperCAmelCase_						)			,  data_args.max_train_samples						)
            a						:Dict										=	train_dataset.select(range(UpperCAmelCase_						)						)

      if data_args.max_val_samples is not None:
            a						:Dict										=	eval_dataset.select(range(data_args.max_val_samples						)						)

      a						:Dict										=	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(UpperCAmelCase_						:		List[Any]						):
            a							,    a						:Tuple										=	torchaudio.load(batch['''path''']						)
            a						:Optional[Any]										=	resampler(UpperCAmelCase_						).squeeze().numpy()
            a						:List[Any]										=	1_6000
            a						:str										=	batch['''text''']
            return batch

      a						:List[str]										=	train_dataset.map(
          UpperCAmelCase_			,  remove_columns=train_dataset.column_names			,  num_proc=data_args.preprocessing_num_workers			,  )
      a						:Optional[Any]										=	eval_dataset.map(
          UpperCAmelCase_			,  remove_columns=eval_dataset.column_names			,  num_proc=data_args.preprocessing_num_workers			,  )

      def prepare_dataset(UpperCAmelCase_						:		List[str]						):
            # 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}.'''

            a						:Dict										=	processor(
                audio=batch['''speech''']			,  text=batch['''target_text''']			,  sampling_rate=batch['''sampling_rate'''][0]						)
            batch.update(UpperCAmelCase_						)
            return batch

      a						:Optional[Any]										=	train_dataset.map(
          UpperCAmelCase_			,  remove_columns=train_dataset.column_names			,  batch_size=training_args.per_device_train_batch_size			,  batched=UpperCAmelCase_			,  num_proc=data_args.preprocessing_num_workers			,  )
      a						:List[str]										=	eval_dataset.map(
          UpperCAmelCase_			,  remove_columns=eval_dataset.column_names			,  batch_size=training_args.per_device_train_batch_size			,  batched=UpperCAmelCase_			,  num_proc=data_args.preprocessing_num_workers			,  )

      # Metric
      a						:Optional[Any]										=	datasets.load_metric('''wer'''						)

      def compute_metrics(UpperCAmelCase_						:		List[Any]						):
            a						:List[str]										=	pred.predictions
            a						:Dict										=	np.argmax(UpperCAmelCase_			,  axis=-1						)

            a						:Dict										=	processor.tokenizer.pad_token_id

            a						:int										=	processor.batch_decode(UpperCAmelCase_						)
            # we do not want to group tokens when computing the metrics
            a						:Dict										=	processor.batch_decode(pred.label_ids			,  group_tokens=UpperCAmelCase_						)

            a						:Optional[Any]										=	wer_metric.compute(predictions=UpperCAmelCase_			,  references=UpperCAmelCase_						)

            return {"wer": wer}

      if model_args.freeze_feature_extractor:
            model.freeze_feature_extractor()

      # Data collator
      a						:int										=	DataCollatorCTCWithPadding(processor=UpperCAmelCase_			,  padding=UpperCAmelCase_						)

      # Initialize our Trainer
      a						:Tuple										=	CTCTrainer(
          model=UpperCAmelCase_			,  data_collator=UpperCAmelCase_			,  args=UpperCAmelCase_			,  compute_metrics=UpperCAmelCase_			,  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:
                  a						:int										=	last_checkpoint
            elif os.path.isdir(model_args.model_name_or_path						):
                  a						:Tuple										=	model_args.model_name_or_path
            else:
                  a						:Optional[int]										=	None

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

            a						:int										=	trainer.train(resume_from_checkpoint=UpperCAmelCase_						)
            trainer.save_model()

            a						:Optional[int]										=	train_result.metrics
            a						:int										=	(
                data_args.max_train_samples if data_args.max_train_samples is not None else len(UpperCAmelCase_						)
            )
            a						:Optional[Any]										=	min(UpperCAmelCase_			,  len(UpperCAmelCase_						)						)

            trainer.log_metrics('''train'''			,  UpperCAmelCase_						)
            trainer.save_metrics('''train'''			,  UpperCAmelCase_						)
            trainer.save_state()

      # Evaluation
      a						:Dict										=	{}
      if training_args.do_eval:
            logger.info('''*** Evaluate ***'''						)
            a						:Optional[int]										=	trainer.evaluate()
            a						:Tuple										=	data_args.max_val_samples if data_args.max_val_samples is not None else len(UpperCAmelCase_						)
            a						:Optional[Any]										=	min(UpperCAmelCase_			,  len(UpperCAmelCase_						)						)

            trainer.log_metrics('''eval'''			,  UpperCAmelCase_						)
            trainer.save_metrics('''eval'''			,  UpperCAmelCase_						)

      return results


if __name__ == "__main__":
     main()









import gc
import random
import unittest

import numpy as np
import torch
from transformers import CLIPTextConfig, CLIPTextModel, CLIPTokenizer

from diffusers import AutoencoderKL, CycleDiffusionPipeline, DDIMScheduler, UNetaDConditionModel
from diffusers.utils import floats_tensor, load_image, load_numpy, slow, torch_device
from diffusers.utils.testing_utils import enable_full_determinism, require_torch_gpu, skip_mps

from ..pipeline_params import (
    IMAGE_TO_IMAGE_IMAGE_PARAMS,
    TEXT_GUIDED_IMAGE_VARIATION_BATCH_PARAMS,
    TEXT_GUIDED_IMAGE_VARIATION_PARAMS,
)
from ..test_pipelines_common import PipelineLatentTesterMixin, PipelineTesterMixin


enable_full_determinism()







class 		_snake_case  (				_snake_case						,   _snake_case						,   unittest.TestCase							):
 SCREAMING_SNAKE_CASE__				=	CycleDiffusionPipeline
 SCREAMING_SNAKE_CASE__				=	TEXT_GUIDED_IMAGE_VARIATION_PARAMS - {
     'negative_prompt',
     'height',
     'width',
     'negative_prompt_embeds',
 }
 SCREAMING_SNAKE_CASE__				=	PipelineTesterMixin.required_optional_params - {'latents'}
 SCREAMING_SNAKE_CASE__				=	TEXT_GUIDED_IMAGE_VARIATION_BATCH_PARAMS.union({'source_prompt'}							)
 SCREAMING_SNAKE_CASE__				=	IMAGE_TO_IMAGE_IMAGE_PARAMS
 SCREAMING_SNAKE_CASE__				=	IMAGE_TO_IMAGE_IMAGE_PARAMS




 def 	SCREAMING_SNAKE_CASE__    (		self   ):
       torch.manual_seed(0   )
       a						:Optional[Any]										=	UNetaDConditionModel(
           block_out_channels=(32, 64) ,  layers_per_block=2 ,  sample_size=32 ,  in_channels=4 ,  out_channels=4 ,  down_block_types=('''DownBlock2D''', '''CrossAttnDownBlock2D''') ,  up_block_types=('''CrossAttnUpBlock2D''', '''UpBlock2D''') ,  cross_attention_dim=32 ,  )
       a						:List[str]										=	DDIMScheduler(
           beta_start=0.0_0085 ,  beta_end=0.012 ,  beta_schedule='''scaled_linear''' ,  num_train_timesteps=1000 ,  clip_sample=_lowerCamelCase ,  set_alpha_to_one=_lowerCamelCase ,  )
       torch.manual_seed(0   )
       a						:List[str]										=	AutoencoderKL(
           block_out_channels=[32, 64] ,  in_channels=3 ,  out_channels=3 ,  down_block_types=['''DownEncoderBlock2D''', '''DownEncoderBlock2D'''] ,  up_block_types=['''UpDecoderBlock2D''', '''UpDecoderBlock2D'''] ,  latent_channels=4 ,  )
       torch.manual_seed(0   )
       a						:Dict										=	CLIPTextConfig(
           bos_token_id=0 ,  eos_token_id=2 ,  hidden_size=32 ,  intermediate_size=37 ,  layer_norm_eps=1e-05 ,  num_attention_heads=4 ,  num_hidden_layers=5 ,  pad_token_id=1 ,  vocab_size=1000 ,  )
       a						:str										=	CLIPTextModel(_lowerCamelCase   )
       a						:List[str]										=	CLIPTokenizer.from_pretrained('''hf-internal-testing/tiny-random-clip'''   )

       a						:Union[str, Any]										=	{
           '''unet''': unet,
           '''scheduler''': scheduler,
           '''vae''': vae,
           '''text_encoder''': text_encoder,
           '''tokenizer''': tokenizer,
           '''safety_checker''': None,
           '''feature_extractor''': None,
       }
       return components




 def 	SCREAMING_SNAKE_CASE__    (		self ,  _lowerCamelCase ,  _lowerCamelCase=0   ):
       a						:Tuple										=	floats_tensor((1, 3, 32, 32) ,  rng=random.Random(_lowerCamelCase   )   ).to(_lowerCamelCase   )
       a						:Tuple										=	image / 2 + 0.5
       if str(_lowerCamelCase   ).startswith('''mps'''   ):
             a						:List[str]										=	torch.manual_seed(_lowerCamelCase   )
       else:
             a						:Any										=	torch.Generator(device=_lowerCamelCase   ).manual_seed(_lowerCamelCase   )
       a						:int										=	{
           '''prompt''': '''An astronaut riding an elephant''',
           '''source_prompt''': '''An astronaut riding a horse''',
           '''image''': image,
           '''generator''': generator,
           '''num_inference_steps''': 2,
           '''eta''': 0.1,
           '''strength''': 0.8,
           '''guidance_scale''': 3,
           '''source_guidance_scale''': 1,
           '''output_type''': '''numpy''',
       }
       return inputs




 def 	SCREAMING_SNAKE_CASE__    (		self   ):
       a						:Union[str, Any]										=	'''cpu'''  # ensure determinism for the device-dependent torch.Generator

       a						:Optional[Any]										=	self.get_dummy_components()
       a						:Dict										=	CycleDiffusionPipeline(**_lowerCamelCase   )
       a						:Optional[Any]										=	pipe.to(_lowerCamelCase   )
       pipe.set_progress_bar_config(disable=_lowerCamelCase   )

       a						:List[str]										=	self.get_dummy_inputs(_lowerCamelCase   )
       a						:Any										=	pipe(**_lowerCamelCase   )
       a						:List[Any]										=	output.images

       a						:str										=	images[0, -3:, -3:, -1]

       assert images.shape == (1, 32, 32, 3)
       a						:List[Any]										=	np.array([0.4459, 0.4943, 0.4544, 0.6643, 0.5474, 0.4327, 0.5701, 0.5959, 0.5179]   )

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




 @unittest.skipIf(torch_device != '''cuda''' ,  '''This test requires a GPU'''   )
 def 	SCREAMING_SNAKE_CASE__    (		self   ):
       a						:Optional[int]										=	self.get_dummy_components()
       for name, module in components.items():
             if hasattr(_lowerCamelCase ,  '''half'''   ):
                   a						:Union[str, Any]										=	module.half()
       a						:List[Any]										=	CycleDiffusionPipeline(**_lowerCamelCase   )
       a						:Dict										=	pipe.to(_lowerCamelCase   )
       pipe.set_progress_bar_config(disable=_lowerCamelCase   )

       a						:Tuple										=	self.get_dummy_inputs(_lowerCamelCase   )
       a						:Optional[int]										=	pipe(**_lowerCamelCase   )
       a						:Optional[Any]										=	output.images

       a						:List[Any]										=	images[0, -3:, -3:, -1]

       assert images.shape == (1, 32, 32, 3)
       a						:str										=	np.array([0.3506, 0.4543, 0.446, 0.4575, 0.5195, 0.4155, 0.5273, 0.518, 0.4116]   )

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




 @skip_mps
 def 	SCREAMING_SNAKE_CASE__    (		self   ):
       return super().test_save_load_local()




 @unittest.skip('''non-deterministic pipeline'''   )
 def 	SCREAMING_SNAKE_CASE__    (		self   ):
       return super().test_inference_batch_single_identical()




 @skip_mps
 def 	SCREAMING_SNAKE_CASE__    (		self   ):
       return super().test_dict_tuple_outputs_equivalent()




 @skip_mps
 def 	SCREAMING_SNAKE_CASE__    (		self   ):
       return super().test_save_load_optional_components()




 @skip_mps
 def 	SCREAMING_SNAKE_CASE__    (		self   ):
       return super().test_attention_slicing_forward_pass()







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




 def 	SCREAMING_SNAKE_CASE__    (		self   ):
       # clean up the VRAM after each test
       super().tearDown()
       gc.collect()
       torch.cuda.empty_cache()




 def 	SCREAMING_SNAKE_CASE__    (		self   ):
       a						:str										=	load_image(
           '''https://huggingface.co/datasets/hf-internal-testing/diffusers-images/resolve/main'''
           '''/cycle-diffusion/black_colored_car.png'''   )
       a						:Optional[int]										=	load_numpy(
           '''https://huggingface.co/datasets/hf-internal-testing/diffusers-images/resolve/main/cycle-diffusion/blue_colored_car_fp16.npy'''   )
       a						:Optional[Any]										=	init_image.resize((512, 512)   )

       a						:List[str]										=	'''CompVis/stable-diffusion-v1-4'''
       a						:List[str]										=	DDIMScheduler.from_pretrained(_lowerCamelCase ,  subfolder='''scheduler'''   )
       a						:Tuple										=	CycleDiffusionPipeline.from_pretrained(
           _lowerCamelCase ,  scheduler=_lowerCamelCase ,  safety_checker=_lowerCamelCase ,  torch_dtype=torch.floataa ,  revision='''fp16'''   )

       pipe.to(_lowerCamelCase   )
       pipe.set_progress_bar_config(disable=_lowerCamelCase   )
       pipe.enable_attention_slicing()

       a						:Optional[Any]										=	'''A black colored car'''
       a						:Any										=	'''A blue colored car'''

       a						:str										=	torch.manual_seed(0   )
       a						:List[Any]										=	pipe(
           prompt=_lowerCamelCase ,  source_prompt=_lowerCamelCase ,  image=_lowerCamelCase ,  num_inference_steps=100 ,  eta=0.1 ,  strength=0.85 ,  guidance_scale=3 ,  source_guidance_scale=1 ,  generator=_lowerCamelCase ,  output_type='''np''' ,  )
       a						:int										=	output.images

       # the values aren't exactly equal, but the images look the same visually
       assert np.abs(image - expected_image   ).max() < 5e-1




 def 	SCREAMING_SNAKE_CASE__    (		self   ):
       a						:str										=	load_image(
           '''https://huggingface.co/datasets/hf-internal-testing/diffusers-images/resolve/main'''
           '''/cycle-diffusion/black_colored_car.png'''   )
       a						:Optional[int]										=	load_numpy(
           '''https://huggingface.co/datasets/hf-internal-testing/diffusers-images/resolve/main/cycle-diffusion/blue_colored_car.npy'''   )
       a						:List[str]										=	init_image.resize((512, 512)   )

       a						:List[str]										=	'''CompVis/stable-diffusion-v1-4'''
       a						:Any										=	DDIMScheduler.from_pretrained(_lowerCamelCase ,  subfolder='''scheduler'''   )
       a						:int										=	CycleDiffusionPipeline.from_pretrained(_lowerCamelCase ,  scheduler=_lowerCamelCase ,  safety_checker=_lowerCamelCase   )

       pipe.to(_lowerCamelCase   )
       pipe.set_progress_bar_config(disable=_lowerCamelCase   )
       pipe.enable_attention_slicing()

       a						:Optional[int]										=	'''A black colored car'''
       a						:Any										=	'''A blue colored car'''

       a						:Optional[int]										=	torch.manual_seed(0   )
       a						:Union[str, Any]										=	pipe(
           prompt=_lowerCamelCase ,  source_prompt=_lowerCamelCase ,  image=_lowerCamelCase ,  num_inference_steps=100 ,  eta=0.1 ,  strength=0.85 ,  guidance_scale=3 ,  source_guidance_scale=1 ,  generator=_lowerCamelCase ,  output_type='''np''' ,  )
       a						:Optional[int]										=	output.images

       assert np.abs(image - expected_image   ).max() < 2e-2





