




'''simple docstring'''







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

lowerCAmelCase_     						=				logging.getLogger(__name__)







def 						_A      ( UpperCAmelCase=None      ,UpperCAmelCase=None						):






   '''simple docstring'''







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

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




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




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






 def __call__(self       :  List[str]    ,		a       :  List[Dict[str, Union[List[int], torch.Tensor]]]    )       ->   Dict[str, torch.Tensor]:






    """simple docstring"""


    A__       =     [{'input_values': feature['input_values']} for feature in features]
    A__       =     [{'input_ids': feature['labels']} for feature in features]

    A__       =     self.processor.pad(
        a    ,		padding=self.padding    ,		max_length=self.max_length    ,		pad_to_multiple_of=self.pad_to_multiple_of    ,		return_tensors='pt'    ,		)
    A__       =     self.processor.pad(
        labels=a    ,		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__       =     labels_batch['input_ids'].masked_fill(labels_batch.attention_mask.ne(1    )    ,		-1_00    )

    A__       =     labels

    return batch




class 	_snake_case(			UpperCAmelCase      ):






 def 						_UpperCamelCase (self       :  Optional[Any]    ,		a       :  nn.Module    ,		a       :  Dict[str, Union[torch.Tensor, Any]]    )       ->   torch.Tensor:






    """simple docstring"""


    model.train()
    A__       =     self._prepare_inputs(a    )

    if self.use_amp:
       with autocast():
          A__       =     self.compute_loss(a    ,		a    )
    else:
       A__       =     self.compute_loss(a    ,		a    )

    if self.args.n_gpu > 1:
       if model.module.config.ctc_loss_reduction == "mean":
          A__       =     loss.mean()
       elif model.module.config.ctc_loss_reduction == "sum":
          A__       =     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__       =     loss / self.args.gradient_accumulation_steps

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

    return loss.detach()







def 						_A      ( ):






   '''simple docstring'''







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

   # Detecting last checkpoint.
   A__       =     None
   if os.path.isdir(training_args.output_dir						) and training_args.do_train and not training_args.overwrite_output_dir:
      A__       =     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__       =     datasets.load_dataset(
       'common_voice'      ,data_args.dataset_config_name      ,split=data_args.train_split_name						)
   A__       =     datasets.load_dataset('common_voice'      ,data_args.dataset_config_name      ,split='test'						)

   # Create and save tokenizer
   A__       =     F"""[{"".join(data_args.chars_to_ignore						)}]"""

   def remove_special_characters(UpperCAmelCase						):
      A__       =     re.sub(UpperCAmelCase      ,''      ,batch['sentence']						).lower() + ' '
      return batch

   A__       =     train_dataset.map(UpperCAmelCase      ,remove_columns=['sentence']						)
   A__       =     eval_dataset.map(UpperCAmelCase      ,remove_columns=['sentence']						)

   def extract_all_chars(UpperCAmelCase						):
      A__       =     ' '.join(batch['text']						)
      A__       =     list(set(UpperCAmelCase						)						)
      return {"vocab": [vocab], "all_text": [all_text]}

   A__       =     train_dataset.map(
       UpperCAmelCase      ,batched=UpperCAmelCase      ,batch_size=-1      ,keep_in_memory=UpperCAmelCase      ,remove_columns=train_dataset.column_names      ,)
   A__       =     train_dataset.map(
       UpperCAmelCase      ,batched=UpperCAmelCase      ,batch_size=-1      ,keep_in_memory=UpperCAmelCase      ,remove_columns=eval_dataset.column_names      ,)

   A__       =     list(set(vocab_train['vocab'][0]						) | set(vocab_test['vocab'][0]						)						)
   A__       =     {v: k for k, v in enumerate(UpperCAmelCase						)}
   A__       =     vocab_dict[' ']
   del vocab_dict[" "]
   A__       =     len(UpperCAmelCase						)
   A__       =     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__       =     WavaVecaCTCTokenizer(
       'vocab.json'      ,unk_token='[UNK]'      ,pad_token='[PAD]'      ,word_delimiter_token='|'      ,)
   A__       =     WavaVecaFeatureExtractor(
       feature_size=1      ,sampling_rate=16000      ,padding_value=0.0      ,do_normalize=UpperCAmelCase      ,return_attention_mask=UpperCAmelCase						)
   A__       =     WavaVecaProcessor(feature_extractor=UpperCAmelCase      ,tokenizer=UpperCAmelCase						)
   A__       =     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__       =     min(len(UpperCAmelCase						)      ,data_args.max_train_samples						)
      A__       =     train_dataset.select(range(UpperCAmelCase						)						)

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

   A__       =     torchaudio.transforms.Resample(48000      ,16000						)

   # Preprocessing the datasets.
   # We need to read the aduio files as arrays and tokenize the targets.
   def speech_file_to_array_fn(UpperCAmelCase						):
      A__  ,			A__       =     torchaudio.load(batch['path']						)
      A__       =     resampler(UpperCAmelCase						).squeeze().numpy()
      A__       =     16000
      A__       =     batch['text']
      return batch

   A__       =     train_dataset.map(
       UpperCAmelCase      ,remove_columns=train_dataset.column_names      ,num_proc=data_args.preprocessing_num_workers      ,)
   A__       =     eval_dataset.map(
       UpperCAmelCase      ,remove_columns=eval_dataset.column_names      ,num_proc=data_args.preprocessing_num_workers      ,)

   def prepare_dataset(UpperCAmelCase						):
      # 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__       =     processor(
          audio=batch['speech']      ,text=batch['target_text']      ,sampling_rate=batch['sampling_rate'][0]						)
      batch.update(UpperCAmelCase						)
      return batch

   A__       =     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__       =     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__       =     datasets.load_metric('wer'						)

   def compute_metrics(UpperCAmelCase						):
      A__       =     pred.predictions
      A__       =     np.argmax(UpperCAmelCase      ,axis=-1						)

      A__       =     processor.tokenizer.pad_token_id

      A__       =     processor.batch_decode(UpperCAmelCase						)
      # we do not want to group tokens when computing the metrics
      A__       =     processor.batch_decode(pred.label_ids      ,group_tokens=UpperCAmelCase						)

      A__       =     wer_metric.compute(predictions=UpperCAmelCase      ,references=UpperCAmelCase						)

      return {"wer": wer}

   if model_args.freeze_feature_extractor:
      model.freeze_feature_extractor()

   # Data collator
   A__       =     DataCollatorCTCWithPadding(processor=UpperCAmelCase      ,padding=UpperCAmelCase						)

   # Initialize our Trainer
   A__       =     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__       =     last_checkpoint
      elif os.path.isdir(model_args.model_name_or_path						):
         A__       =     model_args.model_name_or_path
      else:
         A__       =     None

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

      A__       =     trainer.train(resume_from_checkpoint=UpperCAmelCase						)
      trainer.save_model()

      A__       =     train_result.metrics
      A__       =     (
          data_args.max_train_samples if data_args.max_train_samples is not None else len(UpperCAmelCase						)
      )
      A__       =     min(UpperCAmelCase      ,len(UpperCAmelCase						)						)

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

   # Evaluation
   A__       =     {}
   if training_args.do_eval:
      logger.info('*** Evaluate ***'						)
      A__       =     trainer.evaluate()
      A__       =     data_args.max_val_samples if data_args.max_val_samples is not None else len(UpperCAmelCase						)
      A__       =     min(UpperCAmelCase      ,len(UpperCAmelCase						)						)

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

   return results


if __name__ == "__main__":
    main()








'''simple docstring'''







import gc
import random
import unittest

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

from diffusers import AutoencoderKL, DDIMScheduler, DDPMScheduler, StableDiffusionUpscalePipeline, 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


enable_full_determinism()

class 	_snake_case(			unittest.TestCase      ):






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






    """simple docstring"""


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






 @property
 def 						_UpperCamelCase (self       :  int    )       ->   Any:






    """simple docstring"""


    A__       =     1
    A__       =     3
    A__       =     (32, 32)

    A__       =     floats_tensor((batch_size, num_channels) + sizes    ,		rng=random.Random(0    )    ).to(a    )
    return image






 @property
 def 						_UpperCamelCase (self       :  Union[str, Any]    )       ->   Tuple:






    """simple docstring"""


    torch.manual_seed(0    )
    A__       =     UNetaDConditionModel(
        block_out_channels=(32, 32, 64)    ,		layers_per_block=2    ,		sample_size=32    ,		in_channels=7    ,		out_channels=4    ,		down_block_types=('DownBlock2D', 'CrossAttnDownBlock2D', 'CrossAttnDownBlock2D')    ,		up_block_types=('CrossAttnUpBlock2D', 'CrossAttnUpBlock2D', 'UpBlock2D')    ,		cross_attention_dim=32    ,		attention_head_dim=8    ,		use_linear_projection=a    ,		only_cross_attention=(True, True, False)    ,		num_class_embeds=1_00    ,		)
    return model






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






    """simple docstring"""


    torch.manual_seed(0    )
    A__       =     AutoencoderKL(
        block_out_channels=[32, 32, 64]    ,		in_channels=3    ,		out_channels=3    ,		down_block_types=['DownEncoderBlock2D', 'DownEncoderBlock2D', 'DownEncoderBlock2D']    ,		up_block_types=['UpDecoderBlock2D', 'UpDecoderBlock2D', 'UpDecoderBlock2D']    ,		latent_channels=4    ,		)
    return model






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






    """simple docstring"""


    torch.manual_seed(0    )
    A__       =     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=10_00    ,		hidden_act='gelu'    ,		projection_dim=5_12    ,		)
    return CLIPTextModel(a    )






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






    """simple docstring"""


    A__       =     'cpu'  # ensure determinism for the device-dependent torch.Generator
    A__       =     self.dummy_cond_unet_upscale
    A__       =     DDPMScheduler()
    A__       =     DDIMScheduler(prediction_type='v_prediction'    )
    A__       =     self.dummy_vae
    A__       =     self.dummy_text_encoder
    A__       =     CLIPTokenizer.from_pretrained('hf-internal-testing/tiny-random-clip'    )

    A__       =     self.dummy_image.cpu().permute(0    ,		2    ,		3    ,		1    )[0]
    A__       =     Image.fromarray(np.uinta(a    )    ).convert('RGB'    ).resize((64, 64)    )

    # make sure here that pndm scheduler skips prk
    A__       =     StableDiffusionUpscalePipeline(
        unet=a    ,		low_res_scheduler=a    ,		scheduler=a    ,		vae=a    ,		text_encoder=a    ,		tokenizer=a    ,		max_noise_level=3_50    ,		)
    A__       =     sd_pipe.to(a    )
    sd_pipe.set_progress_bar_config(disable=a    )

    A__       =     'A painting of a squirrel eating a burger'
    A__       =     torch.Generator(device=a    ).manual_seed(0    )
    A__       =     sd_pipe(
        [prompt]    ,		image=a    ,		generator=a    ,		guidance_scale=6.0    ,		noise_level=20    ,		num_inference_steps=2    ,		output_type='np'    ,		)

    A__       =     output.images

    A__       =     torch.Generator(device=a    ).manual_seed(0    )
    A__       =     sd_pipe(
        [prompt]    ,		image=a    ,		generator=a    ,		guidance_scale=6.0    ,		noise_level=20    ,		num_inference_steps=2    ,		output_type='np'    ,		return_dict=a    ,		)[0]

    A__       =     image[0, -3:, -3:, -1]
    A__       =     image_from_tuple[0, -3:, -3:, -1]

    A__       =     low_res_image.size[0] * 4
    assert image.shape == (1, expected_height_width, expected_height_width, 3)
    A__       =     np.array([0.3113, 0.3910, 0.4272, 0.4859, 0.5061, 0.4652, 0.5362, 0.5715, 0.5661]    )

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






 def 						_UpperCamelCase (self       :  Optional[int]    )       ->   Optional[int]:






    """simple docstring"""


    A__       =     'cpu'  # ensure determinism for the device-dependent torch.Generator
    A__       =     self.dummy_cond_unet_upscale
    A__       =     DDPMScheduler()
    A__       =     DDIMScheduler(prediction_type='v_prediction'    )
    A__       =     self.dummy_vae
    A__       =     self.dummy_text_encoder
    A__       =     CLIPTokenizer.from_pretrained('hf-internal-testing/tiny-random-clip'    )

    A__       =     self.dummy_image.cpu().permute(0    ,		2    ,		3    ,		1    )[0]
    A__       =     Image.fromarray(np.uinta(a    )    ).convert('RGB'    ).resize((64, 64)    )

    # make sure here that pndm scheduler skips prk
    A__       =     StableDiffusionUpscalePipeline(
        unet=a    ,		low_res_scheduler=a    ,		scheduler=a    ,		vae=a    ,		text_encoder=a    ,		tokenizer=a    ,		max_noise_level=3_50    ,		)
    A__       =     sd_pipe.to(a    )
    sd_pipe.set_progress_bar_config(disable=a    )

    A__       =     'A painting of a squirrel eating a burger'
    A__       =     sd_pipe(
        2 * [prompt]    ,		image=2 * [low_res_image]    ,		guidance_scale=6.0    ,		noise_level=20    ,		num_inference_steps=2    ,		output_type='np'    ,		)
    A__       =     output.images
    assert image.shape[0] == 2

    A__       =     torch.Generator(device=a    ).manual_seed(0    )
    A__       =     sd_pipe(
        [prompt]    ,		image=a    ,		generator=a    ,		num_images_per_prompt=2    ,		guidance_scale=6.0    ,		noise_level=20    ,		num_inference_steps=2    ,		output_type='np'    ,		)
    A__       =     output.images
    assert image.shape[0] == 2






 @unittest.skipIf(torch_device != 'cuda'    ,		'This test requires a GPU'    )
 def 						_UpperCamelCase (self       :  List[Any]    )       ->   Union[str, Any]:






    """simple docstring"""


    A__       =     self.dummy_cond_unet_upscale
    A__       =     DDPMScheduler()
    A__       =     DDIMScheduler(prediction_type='v_prediction'    )
    A__       =     self.dummy_vae
    A__       =     self.dummy_text_encoder
    A__       =     CLIPTokenizer.from_pretrained('hf-internal-testing/tiny-random-clip'    )

    A__       =     self.dummy_image.cpu().permute(0    ,		2    ,		3    ,		1    )[0]
    A__       =     Image.fromarray(np.uinta(a    )    ).convert('RGB'    ).resize((64, 64)    )

    # put models in fp16, except vae as it overflows in fp16
    A__       =     unet.half()
    A__       =     text_encoder.half()

    # make sure here that pndm scheduler skips prk
    A__       =     StableDiffusionUpscalePipeline(
        unet=a    ,		low_res_scheduler=a    ,		scheduler=a    ,		vae=a    ,		text_encoder=a    ,		tokenizer=a    ,		max_noise_level=3_50    ,		)
    A__       =     sd_pipe.to(a    )
    sd_pipe.set_progress_bar_config(disable=a    )

    A__       =     'A painting of a squirrel eating a burger'
    A__       =     torch.manual_seed(0    )
    A__       =     sd_pipe(
        [prompt]    ,		image=a    ,		generator=a    ,		num_inference_steps=2    ,		output_type='np'    ,		).images

    A__       =     low_res_image.size[0] * 4
    assert image.shape == (1, expected_height_width, expected_height_width, 3)




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






 def 						_UpperCamelCase (self       :  Union[str, Any]    )       ->   Dict:






    """simple docstring"""


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






 def 						_UpperCamelCase (self       :  Optional[Any]    )       ->   Optional[int]:






    """simple docstring"""


    A__       =     load_image(
        'https://huggingface.co/datasets/hf-internal-testing/diffusers-images/resolve/main'
        '/sd2-upscale/low_res_cat.png'    )
    A__       =     load_numpy(
        'https://huggingface.co/datasets/hf-internal-testing/diffusers-images/resolve/main/sd2-upscale'
        '/upsampled_cat.npy'    )

    A__       =     'stabilityai/stable-diffusion-x4-upscaler'
    A__       =     StableDiffusionUpscalePipeline.from_pretrained(a    )
    pipe.to(a    )
    pipe.set_progress_bar_config(disable=a    )
    pipe.enable_attention_slicing()

    A__       =     'a cat sitting on a park bench'

    A__       =     torch.manual_seed(0    )
    A__       =     pipe(
        prompt=a    ,		image=a    ,		generator=a    ,		output_type='np'    ,		)
    A__       =     output.images[0]

    assert image.shape == (5_12, 5_12, 3)
    assert np.abs(expected_image - image    ).max() < 1e-3






 def 						_UpperCamelCase (self       :  Any    )       ->   str:






    """simple docstring"""


    A__       =     load_image(
        'https://huggingface.co/datasets/hf-internal-testing/diffusers-images/resolve/main'
        '/sd2-upscale/low_res_cat.png'    )
    A__       =     load_numpy(
        'https://huggingface.co/datasets/hf-internal-testing/diffusers-images/resolve/main/sd2-upscale'
        '/upsampled_cat_fp16.npy'    )

    A__       =     'stabilityai/stable-diffusion-x4-upscaler'
    A__       =     StableDiffusionUpscalePipeline.from_pretrained(
        a    ,		torch_dtype=torch.floataa    ,		)
    pipe.to(a    )
    pipe.set_progress_bar_config(disable=a    )
    pipe.enable_attention_slicing()

    A__       =     'a cat sitting on a park bench'

    A__       =     torch.manual_seed(0    )
    A__       =     pipe(
        prompt=a    ,		image=a    ,		generator=a    ,		output_type='np'    ,		)
    A__       =     output.images[0]

    assert image.shape == (5_12, 5_12, 3)
    assert np.abs(expected_image - image    ).max() < 5e-1






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






    """simple docstring"""


    torch.cuda.empty_cache()
    torch.cuda.reset_max_memory_allocated()
    torch.cuda.reset_peak_memory_stats()

    A__       =     load_image(
        'https://huggingface.co/datasets/hf-internal-testing/diffusers-images/resolve/main'
        '/sd2-upscale/low_res_cat.png'    )

    A__       =     'stabilityai/stable-diffusion-x4-upscaler'
    A__       =     StableDiffusionUpscalePipeline.from_pretrained(
        a    ,		torch_dtype=torch.floataa    ,		)
    pipe.to(a    )
    pipe.set_progress_bar_config(disable=a    )
    pipe.enable_attention_slicing(1    )
    pipe.enable_sequential_cpu_offload()

    A__       =     'a cat sitting on a park bench'

    A__       =     torch.manual_seed(0    )
    A__       =     pipe(
        prompt=a    ,		image=a    ,		generator=a    ,		num_inference_steps=5    ,		output_type='np'    ,		)

    A__       =     torch.cuda.max_memory_allocated()
    # make sure that less than 2.9 GB is allocated
    assert mem_bytes < 2.9 * 10**9


