




'''simple docstring'''







import logging
import os
import sys
from dataclasses import dataclass, field
from typing import Optional

import torch
from datasets import load_dataset
from torchvision.transforms import Compose, Lambda, Normalize, RandomHorizontalFlip, RandomResizedCrop, ToTensor
from torchvision.transforms.functional import InterpolationMode

import transformers
from transformers import (
    HfArgumentParser,
    Trainer,
    TrainingArguments,
    ViTImageProcessor,
    ViTMAEConfig,
    ViTMAEForPreTraining,
)
from transformers.trainer_utils import get_last_checkpoint
from transformers.utils import check_min_version, send_example_telemetry
from transformers.utils.versions import require_version
lowerCAmelCase_     						=				logging.getLogger(__name__)

# Will error if the minimal version of Transformers is not installed. Remove at your own risks.
check_min_version('''4.31.0''')

require_version('''datasets>=1.8.0''', '''To fix: pip install -r examples/pytorch/image-pretraining/requirements.txt''')

@dataclass
class 	_snake_case:
 __snake_case:							Optional[str]						=					field(
     default='''cifar10'''       , metadata={'''help''': '''Name of a dataset from the datasets package'''}      )
 __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=UpperCAmelCase       , metadata={'''help''': '''The column name of the images in the files.'''}      )
 __snake_case:							Optional[str]						=					field(default=UpperCAmelCase       , metadata={'''help''': '''A folder containing the training data.'''}      )
 __snake_case:							Optional[str]						=					field(default=UpperCAmelCase       , metadata={'''help''': '''A folder containing the validation data.'''}      )
 __snake_case:							Optional[float]						=					field(
     default=0.15       , metadata={'''help''': '''Percent to split off of train for validation.'''}      )
 __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 evaluation examples to this '''
             '''value if set.'''
         )
     }       , )






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






    """simple docstring"""


    A__       =     {}
    if self.train_dir is not None:
       A__       =     self.train_dir
    if self.validation_dir is not None:
       A__       =     self.validation_dir
    A__       =     data_files if data_files else None




@dataclass
class 	_snake_case:
 __snake_case:							str						=					field(
     default=UpperCAmelCase       , metadata={
         '''help''': (
             '''The model checkpoint for weights initialization.Don\'t set if you want to train a model from scratch.'''
         )
     }       , )
 __snake_case:							Optional[str]						=					field(
     default=UpperCAmelCase       , metadata={'''help''': '''Pretrained config name or path if not the same as model_name_or_path'''}      )
 __snake_case:							Optional[str]						=					field(
     default=UpperCAmelCase       , metadata={
         '''help''': (
             '''Override some existing default config settings when a model is trained from scratch. Example: '''
             '''n_embd=10,resid_pdrop=0.2,scale_attn_weights=false,summary_type=cls_index'''
         )
     }       , )
 __snake_case:							Optional[str]						=					field(
     default=UpperCAmelCase       , metadata={'''help''': '''Where do you want to store the pretrained models downloaded from s3'''}      )
 __snake_case:							str						=					field(
     default='''main'''       , metadata={'''help''': '''The specific model version to use (can be a branch name, tag name or commit id).'''}       , )
 __snake_case:							str						=					field(default=UpperCAmelCase       , metadata={'''help''': '''Name or path of preprocessor config.'''}      )
 __snake_case:							bool						=					field(
     default=UpperCAmelCase       , metadata={
         '''help''': (
             '''Will use the token generated when running `huggingface-cli login` (necessary to use this script '''
             '''with private models).'''
         )
     }       , )
 __snake_case:							float						=					field(
     default=0.75       , metadata={'''help''': '''The ratio of the number of masked tokens in the input sequence.'''}      )
 __snake_case:							bool						=					field(
     default=UpperCAmelCase       , metadata={'''help''': '''Whether or not to train with normalized pixel values as target.'''}      )




@dataclass
class 	_snake_case(			UpperCAmelCase      ):
 __snake_case:							float						=					field(
     default=1E-3       , metadata={'''help''': '''Base learning rate: absolute_lr = base_lr * total_batch_size / 256.'''}      )







def 						_A      ( UpperCAmelCase						):






   '''simple docstring'''







   A__       =     torch.stack([example['pixel_values'] for example in examples]						)
   return {"pixel_values": pixel_values}







def 						_A      ( ):






   '''simple docstring'''







   A__       =     HfArgumentParser((ModelArguments, DataTrainingArguments, CustomTrainingArguments)						)
   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()

   # Sending telemetry. Tracking the example usage helps us better allocate resources to maintain them. The
   # information sent is the one passed as arguments along with your Python/PyTorch versions.
   send_example_telemetry('run_mae'      ,UpperCAmelCase      ,UpperCAmelCase						)

   # 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						)]      ,)

   if training_args.should_log:
      # The default of training_args.log_level is passive, so we set log level at info here to have that default.
      transformers.utils.logging.set_verbosity_info()

   A__       =     training_args.get_process_log_level()
   logger.setLevel(UpperCAmelCase						)
   transformers.utils.logging.set_verbosity(UpperCAmelCase						)
   transformers.utils.logging.enable_default_handler()
   transformers.utils.logging.enable_explicit_format()

   # 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}"""						)
   logger.info(F"""Training/evaluation parameters {training_args}"""						)

   # 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 and training_args.resume_from_checkpoint is 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.'						)

    # Initialize our dataset.
   A__       =     load_dataset(
       data_args.dataset_name      ,data_args.dataset_config_name      ,data_files=data_args.data_files      ,cache_dir=model_args.cache_dir      ,use_auth_token=True if model_args.use_auth_token else None      ,)

   # If we don't have a validation split, split off a percentage of train as validation.
   A__       =     None if 'validation' in ds.keys() else data_args.train_val_split
   if isinstance(data_args.train_val_split      ,UpperCAmelCase						) and data_args.train_val_split > 0.0:
      A__       =     ds['train'].train_test_split(data_args.train_val_split						)
      A__       =     split['train']
      A__       =     split['test']

   # Load pretrained model and image processor
   #
   # Distributed training:
   # The .from_pretrained methods guarantee that only one local process can concurrently
   # download model & vocab.
   A__       =     {
       'cache_dir': model_args.cache_dir,
       'revision': model_args.model_revision,
       'use_auth_token': True if model_args.use_auth_token else None,
   }
   if model_args.config_name:
      A__       =     ViTMAEConfig.from_pretrained(model_args.config_name      ,**UpperCAmelCase						)
   elif model_args.model_name_or_path:
      A__       =     ViTMAEConfig.from_pretrained(model_args.model_name_or_path      ,**UpperCAmelCase						)
   else:
      A__       =     ViTMAEConfig()
      logger.warning('You are instantiating a new config instance from scratch.'						)
      if model_args.config_overrides is not None:
         logger.info(F"""Overriding config: {model_args.config_overrides}"""						)
         config.update_from_string(model_args.config_overrides						)
         logger.info(F"""New config: {config}"""						)

    # adapt config
   config.update(
       {
           'mask_ratio': model_args.mask_ratio,
           'norm_pix_loss': model_args.norm_pix_loss,
       }						)

   # create image processor
   if model_args.image_processor_name:
      A__       =     ViTImageProcessor.from_pretrained(model_args.image_processor_name      ,**UpperCAmelCase						)
   elif model_args.model_name_or_path:
      A__       =     ViTImageProcessor.from_pretrained(model_args.model_name_or_path      ,**UpperCAmelCase						)
   else:
      A__       =     ViTImageProcessor()

   # create model
   if model_args.model_name_or_path:
      A__       =     ViTMAEForPreTraining.from_pretrained(
          model_args.model_name_or_path      ,from_tf=bool('.ckpt' in model_args.model_name_or_path						)      ,config=UpperCAmelCase      ,cache_dir=model_args.cache_dir      ,revision=model_args.model_revision      ,use_auth_token=True if model_args.use_auth_token else None      ,)
   else:
      logger.info('Training new model from scratch'						)
      A__       =     ViTMAEForPreTraining(UpperCAmelCase						)

   if training_args.do_train:
      A__       =     ds['train'].column_names
   else:
      A__       =     ds['validation'].column_names

   if data_args.image_column_name is not None:
      A__       =     data_args.image_column_name
   elif "image" in column_names:
      A__       =     'image'
   elif "img" in column_names:
      A__       =     'img'
   else:
      A__       =     column_names[0]

   # transformations as done in original MAE paper
   # source: https://github.com/facebookresearch/mae/blob/main/main_pretrain.py
   if "shortest_edge" in image_processor.size:
      A__       =     image_processor.size['shortest_edge']
   else:
      A__       =     (image_processor.size['height'], image_processor.size['width'])
   A__       =     Compose(
       [
           Lambda(lambda UpperCAmelCase						: img.convert('RGB'						) if img.mode != "RGB" else img						),
           RandomResizedCrop(UpperCAmelCase      ,scale=(0.2, 1.0)      ,interpolation=InterpolationMode.BICUBIC						),
           RandomHorizontalFlip(),
           ToTensor(),
           Normalize(mean=image_processor.image_mean      ,std=image_processor.image_std						),
       ]						)

   def preprocess_images(UpperCAmelCase						):
      A__       =     [transforms(UpperCAmelCase						) for image in examples[image_column_name]]
      return examples

   if training_args.do_train:
      if "train" not in ds:
         raise ValueError('--do_train requires a train dataset'						)
      if data_args.max_train_samples is not None:
         A__       =     ds['train'].shuffle(seed=training_args.seed						).select(range(data_args.max_train_samples						)						)
      # Set the training transforms
      ds["train"].set_transform(UpperCAmelCase						)

   if training_args.do_eval:
      if "validation" not in ds:
         raise ValueError('--do_eval requires a validation dataset'						)
      if data_args.max_eval_samples is not None:
         A__       =     (
             ds['validation'].shuffle(seed=training_args.seed						).select(range(data_args.max_eval_samples						)						)
         )
      # Set the validation transforms
      ds["validation"].set_transform(UpperCAmelCase						)

   # Compute absolute learning rate
   A__       =     (
       training_args.train_batch_size * training_args.gradient_accumulation_steps * training_args.world_size
   )
   if training_args.base_learning_rate is not None:
      A__       =     training_args.base_learning_rate * total_train_batch_size / 256

   # Initialize our trainer
   A__       =     Trainer(
       model=UpperCAmelCase      ,args=UpperCAmelCase      ,train_dataset=ds['train'] if training_args.do_train else None      ,eval_dataset=ds['validation'] if training_args.do_eval else None      ,tokenizer=UpperCAmelCase      ,data_collator=UpperCAmelCase      ,)

   # Training
   if training_args.do_train:
      A__       =     None
      if training_args.resume_from_checkpoint is not None:
         A__       =     training_args.resume_from_checkpoint
      elif last_checkpoint is not None:
         A__       =     last_checkpoint
      A__       =     trainer.train(resume_from_checkpoint=UpperCAmelCase						)
      trainer.save_model()
      trainer.log_metrics('train'      ,train_result.metrics						)
      trainer.save_metrics('train'      ,train_result.metrics						)
      trainer.save_state()

   # Evaluation
   if training_args.do_eval:
      A__       =     trainer.evaluate()
      trainer.log_metrics('eval'      ,UpperCAmelCase						)
      trainer.save_metrics('eval'      ,UpperCAmelCase						)

   # Write model card and (optionally) push to hub
   A__       =     {
       'tasks': 'masked-auto-encoding',
       'dataset': data_args.dataset_name,
       'tags': ['masked-auto-encoding'],
   }
   if training_args.push_to_hub:
      trainer.push_to_hub(**UpperCAmelCase						)
   else:
      trainer.create_model_card(**UpperCAmelCase						)







def 						_A      ( UpperCAmelCase						):






   '''simple docstring'''







   main()


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


