



"""simple docstring"""


import json
import os
from functools import lru_cache
from typing import List, Optional, Tuple

import regex as re

from ...tokenization_utils import AddedToken, PreTrainedTokenizer
from ...utils import logging


snake_case_    					=	logging.get_logger(__name__)


snake_case_    					=	{'vocab_file': 'vocab.json', 'merges_file': 'merges.txt'}

# See all BART models at https://huggingface.co/models?filter=bart
snake_case_    					=	{
    'vocab_file': {
        'facebook/bart-base': 'https://huggingface.co/facebook/bart-base/resolve/main/vocab.json',
        'facebook/bart-large': 'https://huggingface.co/facebook/bart-large/resolve/main/vocab.json',
        'facebook/bart-large-mnli': 'https://huggingface.co/facebook/bart-large-mnli/resolve/main/vocab.json',
        'facebook/bart-large-cnn': 'https://huggingface.co/facebook/bart-large-cnn/resolve/main/vocab.json',
        'facebook/bart-large-xsum': 'https://huggingface.co/facebook/bart-large-xsum/resolve/main/vocab.json',
        'yjernite/bart_eli5': 'https://huggingface.co/yjernite/bart_eli5/resolve/main/vocab.json',
    },
    'merges_file': {
        'facebook/bart-base': 'https://huggingface.co/facebook/bart-base/resolve/main/merges.txt',
        'facebook/bart-large': 'https://huggingface.co/facebook/bart-large/resolve/main/merges.txt',
        'facebook/bart-large-mnli': 'https://huggingface.co/facebook/bart-large-mnli/resolve/main/merges.txt',
        'facebook/bart-large-cnn': 'https://huggingface.co/facebook/bart-large-cnn/resolve/main/merges.txt',
        'facebook/bart-large-xsum': 'https://huggingface.co/facebook/bart-large-xsum/resolve/main/merges.txt',
        'yjernite/bart_eli5': 'https://huggingface.co/yjernite/bart_eli5/resolve/main/merges.txt',
    },
}

snake_case_    					=	{
    'facebook/bart-base': 1024,
    'facebook/bart-large': 1024,
    'facebook/bart-large-mnli': 1024,
    'facebook/bart-large-cnn': 1024,
    'facebook/bart-large-xsum': 1024,
    'yjernite/bart_eli5': 1024,
}

@lru_cache()
def 			_lowerCAmelCase				(       ):
      UpperCAmelCase					=			(
          list(range(ord('!'						)		,     ord('~'						) + 1						)						) + list(range(ord('¡'						)		,     ord('¬'						) + 1						)						) + list(range(ord('®'						)		,     ord('ÿ'						) + 1						)						)
      )
      UpperCAmelCase					=			bs[:]
      UpperCAmelCase					=			0
      for b in range(2**8						):
            if b not in bs:
                  bs.append(UpperCAmelCase_						)
                  cs.append(2**8 + n						)
                  n += 1
      UpperCAmelCase					=			[chr(UpperCAmelCase_						) for n in cs]
      return dict(zip(UpperCAmelCase_		,     UpperCAmelCase_						)						)

def 			_lowerCAmelCase				(       lowercase_						):
      UpperCAmelCase					=			set()
      UpperCAmelCase					=			word[0]
      for char in word[1:]:
            pairs.add((prev_char, char)						)
            UpperCAmelCase					=			char
      return pairs







class 				A_      (					_lowerCamelCase    ):



      """simple docstring"""
      __UpperCamelCase		    =							VOCAB_FILES_NAMES
      __UpperCamelCase		    =							PRETRAINED_VOCAB_FILES_MAP
      __UpperCamelCase		    =							PRETRAINED_POSITIONAL_EMBEDDINGS_SIZES
      __UpperCamelCase		    =							["""input_ids""", """attention_mask"""]






      def __init__( self			:List[Any]       ,  lowercase_			:List[Any]       ,  lowercase_			:List[str]       ,  lowercase_			:str="replace"       ,  lowercase_			:Optional[Any]="<s>"       ,  lowercase_			:Tuple="</s>"       ,  lowercase_			:int="</s>"       ,  lowercase_			:Any="<s>"       ,  lowercase_			:List[str]="<unk>"       ,  lowercase_			:Dict="<pad>"       ,  lowercase_			:Optional[Any]="<mask>"       ,  lowercase_			:List[Any]=False       ,  **lowercase_			:Optional[int]       ,  )    ->      Optional[Any]:
            UpperCAmelCase					=			AddedToken(lowercase_       ,  lstrip=lowercase_       ,  rstrip=lowercase_ ) if isinstance(lowercase_       ,  lowercase_ ) else bos_token
            UpperCAmelCase					=			AddedToken(lowercase_       ,  lstrip=lowercase_       ,  rstrip=lowercase_ ) if isinstance(lowercase_       ,  lowercase_ ) else eos_token
            UpperCAmelCase					=			AddedToken(lowercase_       ,  lstrip=lowercase_       ,  rstrip=lowercase_ ) if isinstance(lowercase_       ,  lowercase_ ) else sep_token
            UpperCAmelCase					=			AddedToken(lowercase_       ,  lstrip=lowercase_       ,  rstrip=lowercase_ ) if isinstance(lowercase_       ,  lowercase_ ) else cls_token
            UpperCAmelCase					=			AddedToken(lowercase_       ,  lstrip=lowercase_       ,  rstrip=lowercase_ ) if isinstance(lowercase_       ,  lowercase_ ) else unk_token
            UpperCAmelCase					=			AddedToken(lowercase_       ,  lstrip=lowercase_       ,  rstrip=lowercase_ ) if isinstance(lowercase_       ,  lowercase_ ) else pad_token

            # Mask token behave like a normal word, i.e. include the space before it
            UpperCAmelCase					=			AddedToken(lowercase_       ,  lstrip=lowercase_       ,  rstrip=lowercase_ ) if isinstance(lowercase_       ,  lowercase_ ) else mask_token

            super().__init__(
                errors=lowercase_       ,  bos_token=lowercase_       ,  eos_token=lowercase_       ,  unk_token=lowercase_       ,  sep_token=lowercase_       ,  cls_token=lowercase_       ,  pad_token=lowercase_       ,  mask_token=lowercase_       ,  add_prefix_space=lowercase_       ,  **lowercase_       ,  )

            with open(lowercase_       ,  encoding='utf-8' ) as vocab_handle:
                  UpperCAmelCase					=			json.load(lowercase_ )
            UpperCAmelCase					=			{v: k for k, v in self.encoder.items()}
            UpperCAmelCase					=			errors  # how to handle errors in decoding
            UpperCAmelCase					=			bytes_to_unicode()
            UpperCAmelCase					=			{v: k for k, v in self.byte_encoder.items()}
            with open(lowercase_       ,  encoding='utf-8' ) as merges_handle:
                  UpperCAmelCase					=			merges_handle.read().split('\n' )[1:-1]
            UpperCAmelCase					=			[tuple(merge.split() ) for merge in bpe_merges]
            UpperCAmelCase					=			dict(zip(lowercase_       ,  range(len(lowercase_ ) ) ) )
            UpperCAmelCase					=			{}
            UpperCAmelCase					=			add_prefix_space

            # Should have added re.IGNORECASE so BPE merges can happen for capitalized versions of contractions
            UpperCAmelCase					=			re.compile(R'\'s|\'t|\'re|\'ve|\'m|\'ll|\'d| ?\p{L}+| ?\p{N}+| ?[^\s\p{L}\p{N}]+|\s+(?!\S)|\s+' )






      @property
      def      UpperCAmelCase__					( self			:int )    ->      Optional[Any]:
            return len(self.encoder )






      def      UpperCAmelCase__					( self			:Tuple )    ->      List[str]:
            return dict(self.encoder       ,  **self.added_tokens_encoder )






      def      UpperCAmelCase__					( self			:str       ,  lowercase_			:Union[str, Any] )    ->      Optional[Any]:


            if token in self.cache:
                  return self.cache[token]
            UpperCAmelCase					=			tuple(lowercase_ )
            UpperCAmelCase					=			get_pairs(lowercase_ )

            if not pairs:
                  return token

            while True:
                  UpperCAmelCase					=			min(lowercase_       ,  key=lambda lowercase_ : self.bpe_ranks.get(lowercase_       ,  float('inf' ) ) )
                  if bigram not in self.bpe_ranks:
                        break
                  UpperCAmelCase				,   UpperCAmelCase					=			bigram
                  UpperCAmelCase					=			[]
                  UpperCAmelCase					=			0
                  while i < len(lowercase_ ):
                        try:
                              UpperCAmelCase					=			word.index(lowercase_       ,  lowercase_ )
                        except ValueError:
                              new_word.extend(word[i:] )
                              break
                        else:
                              new_word.extend(word[i:j] )
                              UpperCAmelCase					=			j

                        if word[i] == first and i < len(lowercase_ ) - 1 and word[i + 1] == second:
                              new_word.append(first + second )
                              i += 2
                        else:
                              new_word.append(word[i] )
                              i += 1
                  UpperCAmelCase					=			tuple(lowercase_ )
                  UpperCAmelCase					=			new_word
                  if len(lowercase_ ) == 1:
                        break
                  else:
                        UpperCAmelCase					=			get_pairs(lowercase_ )
            UpperCAmelCase					=			' '.join(lowercase_ )
            UpperCAmelCase					=			word
            return word






      def      UpperCAmelCase__					( self			:Tuple       ,  lowercase_			:int )    ->      Any:
            UpperCAmelCase					=			[]
            for token in re.findall(self.pat       ,  lowercase_ ):
                  UpperCAmelCase					=			''.join(
                      self.byte_encoder[b] for b in token.encode('utf-8' ) )  # Maps all our bytes to unicode strings, avoiding control tokens of the BPE (spaces in our case)
                  bpe_tokens.extend(bpe_token for bpe_token in self.bpe(lowercase_ ).split(' ' ) )
            return bpe_tokens






      def      UpperCAmelCase__					( self			:Dict       ,  lowercase_			:Optional[int] )    ->      Union[str, Any]:
            return self.encoder.get(lowercase_       ,  self.encoder.get(self.unk_token ) )






      def      UpperCAmelCase__					( self			:List[Any]       ,  lowercase_			:List[Any] )    ->      Any:
            return self.decoder.get(lowercase_ )






      def      UpperCAmelCase__					( self			:Optional[Any]       ,  lowercase_			:Tuple )    ->      List[str]:
            UpperCAmelCase					=			''.join(lowercase_ )
            UpperCAmelCase					=			bytearray([self.byte_decoder[c] for c in text] ).decode('utf-8'       ,  errors=self.errors )
            return text






      def      UpperCAmelCase__					( self			:List[str]       ,  lowercase_			:str       ,  lowercase_			:Optional[str] = None )    ->      str:


            if not os.path.isdir(lowercase_ ):
                  logger.error(f"""Vocabulary path ({save_directory}) should be a directory""" )
                  return
            UpperCAmelCase					=			os.path.join(
                lowercase_       ,  (filename_prefix + '-' if filename_prefix else '') + VOCAB_FILES_NAMES['vocab_file'] )
            UpperCAmelCase					=			os.path.join(
                lowercase_       ,  (filename_prefix + '-' if filename_prefix else '') + VOCAB_FILES_NAMES['merges_file'] )

            with open(lowercase_       ,  'w'       ,  encoding='utf-8' ) as f:
                  f.write(json.dumps(self.encoder       ,  indent=2       ,  sort_keys=lowercase_       ,  ensure_ascii=lowercase_ ) + '\n' )

            UpperCAmelCase					=			0
            with open(lowercase_       ,  'w'       ,  encoding='utf-8' ) as writer:
                  writer.write('#version: 0.2\n' )
                  for bpe_tokens, token_index in sorted(self.bpe_ranks.items()       ,  key=lambda lowercase_ : kv[1] ):
                        if index != token_index:
                              logger.warning(
                                  f"""Saving vocabulary to {merge_file}: BPE merge indices are not consecutive."""
                                  ' Please check that the tokenizer is not corrupted!' )
                              UpperCAmelCase					=			token_index
                        writer.write(' '.join(lowercase_ ) + '\n' )
                        index += 1

            return vocab_file, merge_file






      def      UpperCAmelCase__					( self			:Union[str, Any]       ,  lowercase_			:List[int]       ,  lowercase_			:Optional[List[int]] = None )    ->      Dict:


            if token_ids_a is None:
                  return [self.cls_token_id] + token_ids_a + [self.sep_token_id]
            UpperCAmelCase					=			[self.cls_token_id]
            UpperCAmelCase					=			[self.sep_token_id]
            return cls + token_ids_a + sep + sep + token_ids_a + sep






      def      UpperCAmelCase__					( self			:List[str]       ,  lowercase_			:List[int]       ,  lowercase_			:Optional[List[int]] = None       ,  lowercase_			:bool = False )    ->      Any:


            if already_has_special_tokens:
                  return super().get_special_tokens_mask(
                      token_ids_a=lowercase_       ,  token_ids_a=lowercase_       ,  already_has_special_tokens=lowercase_ )

            if token_ids_a is None:
                  return [1] + ([0] * len(lowercase_ )) + [1]
            return [1] + ([0] * len(lowercase_ )) + [1, 1] + ([0] * len(lowercase_ )) + [1]






      def      UpperCAmelCase__					( self			:Dict       ,  lowercase_			:List[int]       ,  lowercase_			:Optional[List[int]] = None )    ->      Dict:
            UpperCAmelCase					=			[self.sep_token_id]
            UpperCAmelCase					=			[self.cls_token_id]

            if token_ids_a is None:
                  return len(cls + token_ids_a + sep ) * [0]
            return len(cls + token_ids_a + sep + sep + token_ids_a + sep ) * [0]






      def      UpperCAmelCase__					( self			:List[str]       ,  lowercase_			:Optional[int]       ,  lowercase_			:Tuple=False       ,  **lowercase_			:List[Any] )    ->      Optional[int]:
            UpperCAmelCase					=			kwargs.pop('add_prefix_space'       ,  self.add_prefix_space )
            if (is_split_into_words or add_prefix_space) and (len(lowercase_ ) > 0 and not text[0].isspace()):
                  UpperCAmelCase					=			' ' + text
            return (text, kwargs)










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



						"""simple docstring"""






						def      UpperCAmelCase__					( self			:Tuple )    ->      Union[str, Any]:
												# clean up the VRAM after each test
												super().tearDown()
												gc.collect()
												torch.cuda.empty_cache()






						@property
						def      UpperCAmelCase__					( self			:int )    ->      Union[str, Any]:
												UpperCAmelCase					=			1
												UpperCAmelCase					=			3
												UpperCAmelCase					=			(32, 32)

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






						@property
						def      UpperCAmelCase__					( self			:List[Any] )    ->      Tuple:
												torch.manual_seed(0 )
												UpperCAmelCase					=			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=lowercase_       ,  only_cross_attention=(True, True, False)       ,  num_class_embeds=1_00       ,  )
												return model






						@property
						def      UpperCAmelCase__					( self			:str )    ->      Any:
												torch.manual_seed(0 )
												UpperCAmelCase					=			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			:Optional[int] )    ->      List[str]:
												torch.manual_seed(0 )
												UpperCAmelCase					=			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(lowercase_ )






						def      UpperCAmelCase__					( self			:str )    ->      Union[str, Any]:
												UpperCAmelCase					=			'cpu'  # ensure determinism for the device-dependent torch.Generator
												UpperCAmelCase					=			self.dummy_cond_unet_upscale
												UpperCAmelCase					=			DDPMScheduler()
												UpperCAmelCase					=			DDIMScheduler(prediction_type='v_prediction' )
												UpperCAmelCase					=			self.dummy_vae
												UpperCAmelCase					=			self.dummy_text_encoder
												UpperCAmelCase					=			CLIPTokenizer.from_pretrained('hf-internal-testing/tiny-random-clip' )

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

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

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

												UpperCAmelCase					=			output.images

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

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

												UpperCAmelCase					=			low_res_image.size[0] * 4
												assert image.shape == (1, expected_height_width, expected_height_width, 3)
												UpperCAmelCase					=			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[Any] )    ->      Any:
												UpperCAmelCase					=			'cpu'  # ensure determinism for the device-dependent torch.Generator
												UpperCAmelCase					=			self.dummy_cond_unet_upscale
												UpperCAmelCase					=			DDPMScheduler()
												UpperCAmelCase					=			DDIMScheduler(prediction_type='v_prediction' )
												UpperCAmelCase					=			self.dummy_vae
												UpperCAmelCase					=			self.dummy_text_encoder
												UpperCAmelCase					=			CLIPTokenizer.from_pretrained('hf-internal-testing/tiny-random-clip' )

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

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

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

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






						@unittest.skipIf(torch_device != 'cuda'       ,  'This test requires a GPU' )
						def      UpperCAmelCase__					( self			:Optional[int] )    ->      Optional[Any]:
												UpperCAmelCase					=			self.dummy_cond_unet_upscale
												UpperCAmelCase					=			DDPMScheduler()
												UpperCAmelCase					=			DDIMScheduler(prediction_type='v_prediction' )
												UpperCAmelCase					=			self.dummy_vae
												UpperCAmelCase					=			self.dummy_text_encoder
												UpperCAmelCase					=			CLIPTokenizer.from_pretrained('hf-internal-testing/tiny-random-clip' )

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

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

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

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

												UpperCAmelCase					=			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      UpperCAmelCase__					( self			:Dict )    ->      str:
												# clean up the VRAM after each test
												super().tearDown()
												gc.collect()
												torch.cuda.empty_cache()






						def      UpperCAmelCase__					( self			:Optional[int] )    ->      int:
												UpperCAmelCase					=			load_image(
												    'https://huggingface.co/datasets/hf-internal-testing/diffusers-images/resolve/main'
												    '/sd2-upscale/low_res_cat.png' )
												UpperCAmelCase					=			load_numpy(
												    'https://huggingface.co/datasets/hf-internal-testing/diffusers-images/resolve/main/sd2-upscale'
												    '/upsampled_cat.npy' )

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

												UpperCAmelCase					=			'a cat sitting on a park bench'

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

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






						def      UpperCAmelCase__					( self			:Union[str, Any] )    ->      Tuple:
												UpperCAmelCase					=			load_image(
												    'https://huggingface.co/datasets/hf-internal-testing/diffusers-images/resolve/main'
												    '/sd2-upscale/low_res_cat.png' )
												UpperCAmelCase					=			load_numpy(
												    'https://huggingface.co/datasets/hf-internal-testing/diffusers-images/resolve/main/sd2-upscale'
												    '/upsampled_cat_fp16.npy' )

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

												UpperCAmelCase					=			'a cat sitting on a park bench'

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

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






						def      UpperCAmelCase__					( self			:Any )    ->      List[Any]:
												torch.cuda.empty_cache()
												torch.cuda.reset_max_memory_allocated()
												torch.cuda.reset_peak_memory_stats()

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

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

												UpperCAmelCase					=			'a cat sitting on a park bench'

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

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





