





import argparse
from typing import List

import evaluate
import numpy as np
import torch
from datasets import DatasetDict, load_dataset

# New Code #
# We'll be using StratifiedKFold for this example
from sklearn.model_selection import StratifiedKFold
from torch.optim import AdamW
from torch.utils.data import DataLoader
from transformers import AutoModelForSequenceClassification, AutoTokenizer, get_linear_schedule_with_warmup, set_seed

from accelerate import Accelerator, DistributedType


########################################################################
# This is a fully working simple example to use Accelerate,
# specifically showcasing how to perform Cross Validation,
# and builds off the `nlp_example.py` script.
#
# This example trains a Bert base model on GLUE MRPC
# in any of the following settings (with the same script):
#   - single CPU or single GPU
#   - multi GPUS (using PyTorch distributed mode)
#   - (multi) TPUs
#   - fp16 (mixed-precision) or fp32 (normal precision)
#
# To help focus on the differences in the code, building `DataLoaders`
# was refactored into its own function.
# New additions from the base script can be found quickly by
# looking for the # New Code # tags
#
# To run it in each of these various modes, follow the instructions
# in the readme for examples:
# https://github.com/huggingface/accelerate/tree/main/examples
#
########################################################################


lowerCAmelCase_    =				1_6
lowerCAmelCase_    =				3_2






def      lowerCamelCase_						(				_UpperCamelCase ,				_UpperCamelCase ,				_UpperCamelCase ,				_UpperCamelCase ,				_UpperCamelCase = 16 )		->						Optional[int]:






				"""simple docstring"""


				snake_case_						:    List[str]				=  AutoTokenizer.from_pretrained('''bert-base-cased''' )
				snake_case_						:    str				=  DatasetDict(
				    {
				        '''train''': dataset['''train'''].select(_UpperCamelCase ),
				        '''validation''': dataset['''train'''].select(_UpperCamelCase ),
				        '''test''': dataset['''validation'''],
				    } )

				def tokenize_function(_UpperCamelCase ):
								# max_length=None => use the model max length (it's actually the default)
								snake_case_						:    Union[str, Any]				=  tokenizer(examples['''sentence1'''] ,				examples['''sentence2'''] ,				truncation=_UpperCamelCase ,				max_length=_UpperCamelCase )
								return outputs

				# Apply the method we just defined to all the examples in all the splits of the dataset
				# starting with the main process first:
				with accelerator.main_process_first():
								snake_case_						:    Any				=  datasets.map(
								    _UpperCamelCase ,				batched=_UpperCamelCase ,				remove_columns=['''idx''', '''sentence1''', '''sentence2'''] ,				)

				# We also rename the 'label' column to 'labels' which is the expected name for labels by the models of the
				# transformers library
				snake_case_						:    Dict				=  tokenized_datasets.rename_column('''label''' ,				'''labels''' )

				def collate_fn(_UpperCamelCase ):
								# On TPU it's best to pad everything to the same length or training will be very slow.
								snake_case_						:    Optional[int]				=  128 if accelerator.distributed_type == DistributedType.TPU else None
								# When using mixed precision we want round multiples of 8/16
								if accelerator.mixed_precision == "fp8":
												snake_case_						:    Optional[Any]				=  16
								elif accelerator.mixed_precision != "no":
												snake_case_						:    Union[str, Any]				=  8
								else:
												snake_case_						:    Optional[Any]				=  None

								return tokenizer.pad(
								    _UpperCamelCase ,				padding='''longest''' ,				max_length=_UpperCamelCase ,				pad_to_multiple_of=_UpperCamelCase ,				return_tensors='''pt''' ,				)

				# Instantiate dataloaders.
				snake_case_						:    Optional[int]				=  DataLoader(
				    tokenized_datasets['''train'''] ,				shuffle=_UpperCamelCase ,				collate_fn=_UpperCamelCase ,				batch_size=_UpperCamelCase )
				snake_case_						:    Union[str, Any]				=  DataLoader(
				    tokenized_datasets['''validation'''] ,				shuffle=_UpperCamelCase ,				collate_fn=_UpperCamelCase ,				batch_size=_UpperCamelCase )

				snake_case_						:    Optional[int]				=  DataLoader(
				    tokenized_datasets['''test'''] ,				shuffle=_UpperCamelCase ,				collate_fn=_UpperCamelCase ,				batch_size=_UpperCamelCase )

				return train_dataloader, eval_dataloader, test_dataloader






def      lowerCamelCase_						(				_UpperCamelCase ,				_UpperCamelCase )		->						Any:






				"""simple docstring"""


				snake_case_						:    Union[str, Any]				=  []
				# Download the dataset
				snake_case_						:    int				=  load_dataset('''glue''' ,				'''mrpc''' )
				# Create our splits
				snake_case_						:    int				=  StratifiedKFold(n_splits=int(args.num_folds ) )
				# Initialize accelerator
				snake_case_						:    Any				=  Accelerator(cpu=args.cpu ,				mixed_precision=args.mixed_precision )
				# Sample hyper-parameters for learning rate, batch size, seed and a few other HPs
				snake_case_						:    str				=  config['''lr''']
				snake_case_						:    Union[str, Any]				=  int(config['''num_epochs'''] )
				snake_case_						:    Any				=  int(config['''seed'''] )
				snake_case_						:    Any				=  int(config['''batch_size'''] )

				snake_case_						:    Optional[Any]				=  evaluate.load('''glue''' ,				'''mrpc''' )

				# If the batch size is too big we use gradient accumulation
				snake_case_						:    List[str]				=  1
				if batch_size > MAX_GPU_BATCH_SIZE and accelerator.distributed_type != DistributedType.TPU:
								snake_case_						:    List[str]				=  batch_size // MAX_GPU_BATCH_SIZE
								snake_case_						:    str				=  MAX_GPU_BATCH_SIZE

				set_seed(_UpperCamelCase )

				# New Code #
				# Create our folds:
				snake_case_						:    List[str]				=  kfold.split(np.zeros(datasets['''train'''].num_rows ) ,				datasets['''train''']['''label'''] )
				snake_case_						:    List[str]				=  []
				# Iterate over them
				for i, (train_idxs, valid_idxs) in enumerate(_UpperCamelCase ):
								snake_case_			,							snake_case_			,							snake_case_						:    Tuple				=  get_fold_dataloaders(
								    _UpperCamelCase ,				_UpperCamelCase ,				_UpperCamelCase ,				_UpperCamelCase ,				)
								# Instantiate the model (we build the model here so that the seed also control new weights initialization)
								snake_case_						:    Dict				=  AutoModelForSequenceClassification.from_pretrained('''bert-base-cased''' ,				return_dict=_UpperCamelCase )

								# We could avoid this line since the accelerator is set with `device_placement=True` (default value).
								# Note that if you are placing tensors on devices manually, this line absolutely needs to be before the optimizer
								# creation otherwise training will not work on TPU (`accelerate` will kindly throw an error to make us aware of that).
								snake_case_						:    int				=  model.to(accelerator.device )

								# Instantiate optimizer
								snake_case_						:    Any				=  AdamW(params=model.parameters() ,				lr=_UpperCamelCase )

								# Instantiate scheduler
								snake_case_						:    List[Any]				=  get_linear_schedule_with_warmup(
								    optimizer=_UpperCamelCase ,				num_warmup_steps=100 ,				num_training_steps=(len(_UpperCamelCase ) * num_epochs) // gradient_accumulation_steps ,				)

								# Prepare everything
								# There is no specific order to remember, we just need to unpack the objects in the same order we gave them to the
								# prepare method.
								snake_case_			,							snake_case_			,							snake_case_			,							snake_case_			,							snake_case_						:    Union[str, Any]				=  accelerator.prepare(
								    _UpperCamelCase ,				_UpperCamelCase ,				_UpperCamelCase ,				_UpperCamelCase ,				_UpperCamelCase )

								# Now we train the model
								for epoch in range(_UpperCamelCase ):
												model.train()
												for step, batch in enumerate(_UpperCamelCase ):
																# We could avoid this line since we set the accelerator with `device_placement=True`.
																batch.to(accelerator.device )
																snake_case_						:    List[str]				=  model(**_UpperCamelCase )
																snake_case_						:    int				=  outputs.loss
																snake_case_						:    Optional[Any]				=  loss / gradient_accumulation_steps
																accelerator.backward(_UpperCamelCase )
																if step % gradient_accumulation_steps == 0:
																				optimizer.step()
																				lr_scheduler.step()
																				optimizer.zero_grad()

												model.eval()
												for step, batch in enumerate(_UpperCamelCase ):
																# We could avoid this line since we set the accelerator with `device_placement=True`.
																batch.to(accelerator.device )
																with torch.no_grad():
																				snake_case_						:    str				=  model(**_UpperCamelCase )
																snake_case_						:    List[str]				=  outputs.logits.argmax(dim=-1 )
																snake_case_			,							snake_case_						:    Dict				=  accelerator.gather_for_metrics((predictions, batch['''labels''']) )
																metric.add_batch(
																    predictions=_UpperCamelCase ,				references=_UpperCamelCase ,				)

												snake_case_						:    int				=  metric.compute()
												# Use accelerator.print to print only on the main process.
												accelerator.print(f'''epoch {epoch}:''' ,				_UpperCamelCase )

								# New Code #
								# We also run predictions on the test set at the very end
								snake_case_						:    Optional[int]				=  []
								for step, batch in enumerate(_UpperCamelCase ):
												# We could avoid this line since we set the accelerator with `device_placement=True`.
												batch.to(accelerator.device )
												with torch.no_grad():
																snake_case_						:    List[Any]				=  model(**_UpperCamelCase )
												snake_case_						:    Tuple				=  outputs.logits
												snake_case_			,							snake_case_						:    Union[str, Any]				=  accelerator.gather_for_metrics((predictions, batch['''labels''']) )
												fold_predictions.append(predictions.cpu() )
												if i == 0:
																# We need all of the test predictions
																test_references.append(references.cpu() )
        # Use accelerator.print to print only on the main process.
								test_predictions.append(torch.cat(_UpperCamelCase ,				dim=0 ) )
								# We now need to release all our memory and get rid of the current model, optimizer, etc
								accelerator.free_memory()
				# New Code #
				# Finally we check the accuracy of our folded results:
				snake_case_						:    List[str]				=  torch.cat(_UpperCamelCase ,				dim=0 )
				snake_case_						:    Optional[int]				=  torch.stack(_UpperCamelCase ,				dim=0 ).sum(dim=0 ).div(int(args.num_folds ) ).argmax(dim=-1 )
				snake_case_						:    Optional[Any]				=  metric.compute(predictions=_UpperCamelCase ,				references=_UpperCamelCase )
				accelerator.print('''Average test metrics from all folds:''' ,				_UpperCamelCase )






def      lowerCamelCase_						(				)		->						str:






				"""simple docstring"""


				snake_case_						:    List[Any]				=  argparse.ArgumentParser(description='''Simple example of training script.''' )
				parser.add_argument(
				    '''--mixed_precision''' ,				type=_UpperCamelCase ,				default=_UpperCamelCase ,				choices=['''no''', '''fp16''', '''bf16''', '''fp8'''] ,				help='''Whether to use mixed precision. Choose'''
				    '''between fp16 and bf16 (bfloat16). Bf16 requires PyTorch >= 1.10.'''
				    '''and an Nvidia Ampere GPU.''' ,				)
				parser.add_argument('''--cpu''' ,				action='''store_true''' ,				help='''If passed, will train on the CPU.''' )
				# New Code #
				parser.add_argument('''--num_folds''' ,				type=_UpperCamelCase ,				default=3 ,				help='''The number of splits to perform across the dataset''' )
				snake_case_						:    Optional[Any]				=  parser.parse_args()
				snake_case_						:    Dict				=  {'''lr''': 2E-5, '''num_epochs''': 3, '''seed''': 42, '''batch_size''': 16}
				training_function(_UpperCamelCase ,				_UpperCamelCase )


if __name__ == "__main__":
	main()






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   A(						unittest.TestCase   ):



 '''simple docstring'''


 def 				a__ (				self					:  Optional[Any]  )   ->	Optional[Any]:

       """simple docstring"""






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

 @property
 def 				a__ (				self					:  int  )   ->	int:

       """simple docstring"""






       lowerCamelCase_		     =    1
       lowerCamelCase_		     =    3
       lowerCamelCase_		     =    (32, 32)

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

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

       """simple docstring"""






       torch.manual_seed(0  )
       lowerCamelCase_		     =    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=100						,							)
       return model

 @property
 def 				a__ (				self					:  Optional[int]  )   ->	Optional[int]:

       """simple docstring"""






       torch.manual_seed(0  )
       lowerCamelCase_		     =    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 				a__ (				self					:  Union[str, Any]  )   ->	Union[str, Any]:

       """simple docstring"""






       torch.manual_seed(0  )
       lowerCamelCase_		     =    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						,							hidden_act='gelu'						,							projection_dim=512						,							)
       return CLIPTextModel(A_  )

 def 				a__ (				self					:  Optional[int]  )   ->	List[str]:

       """simple docstring"""






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

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

       # make sure here that pndm scheduler skips prk
       lowerCamelCase_		     =    StableDiffusionUpscalePipeline(
           unet=A_						,							low_res_scheduler=A_						,							scheduler=A_						,							vae=A_						,							text_encoder=A_						,							tokenizer=A_						,							max_noise_level=350						,							)
       lowerCamelCase_		     =    sd_pipe.to(A_  )
       sd_pipe.set_progress_bar_config(disable=A_  )

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

       lowerCamelCase_		     =    output.images

       lowerCamelCase_		     =    torch.Generator(device=A_  ).manual_seed(0  )
       lowerCamelCase_		     =    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]

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

       lowerCamelCase_		     =    low_res_image.size[0] * 4
       assert image.shape == (1, expected_height_width, expected_height_width, 3)
       lowerCamelCase_		     =    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 				a__ (				self					:  List[Any]  )   ->	int:

       """simple docstring"""






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

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

       # make sure here that pndm scheduler skips prk
       lowerCamelCase_		     =    StableDiffusionUpscalePipeline(
           unet=A_						,							low_res_scheduler=A_						,							scheduler=A_						,							vae=A_						,							text_encoder=A_						,							tokenizer=A_						,							max_noise_level=350						,							)
       lowerCamelCase_		     =    sd_pipe.to(A_  )
       sd_pipe.set_progress_bar_config(disable=A_  )

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

       lowerCamelCase_		     =    torch.Generator(device=A_  ).manual_seed(0  )
       lowerCamelCase_		     =    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'						,							)
       lowerCamelCase_		     =    output.images
       assert image.shape[0] == 2





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

       """simple docstring"""






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

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

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

       # make sure here that pndm scheduler skips prk
       lowerCamelCase_		     =    StableDiffusionUpscalePipeline(
           unet=A_						,							low_res_scheduler=A_						,							scheduler=A_						,							vae=A_						,							text_encoder=A_						,							tokenizer=A_						,							max_noise_level=350						,							)
       lowerCamelCase_		     =    sd_pipe.to(A_  )
       sd_pipe.set_progress_bar_config(disable=A_  )

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

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







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



 '''simple docstring'''


 def 				a__ (				self					:  Tuple  )   ->	str:

       """simple docstring"""






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

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

       """simple docstring"""






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

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

       lowerCamelCase_		     =    'a cat sitting on a park bench'

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

       assert image.shape == (512, 512, 3)
       assert np.abs(expected_image - image  ).max() < 1E-3

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

       """simple docstring"""






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

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

       lowerCamelCase_		     =    'a cat sitting on a park bench'

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

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





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

       """simple docstring"""






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

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

       lowerCamelCase_		     =    'stabilityai/stable-diffusion-x4-upscaler'
       lowerCamelCase_		     =    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()

       lowerCamelCase_		     =    'a cat sitting on a park bench'

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

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



