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 			__a			(   self		)     ->  List[Any]:



									'''simple docstring'''







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




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



									'''simple docstring'''







									snake_case__					:	Union[str, Any]												=      1
									snake_case__					:	Union[str, Any]												=      3
									snake_case__					:	Any												=      (32, 32)

									snake_case__					:	Any												=      floats_tensor((batch_size, num_channels) + sizes    ,       rng=random.Random(0		)		).to(__UpperCamelCase		)
									return image




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



									'''simple docstring'''







									torch.manual_seed(0		)
									snake_case__					:	Any												=      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=__UpperCamelCase    ,       only_cross_attention=(True, True, False)    ,       num_class_embeds=100    ,       )
									return model




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



									'''simple docstring'''







									torch.manual_seed(0		)
									snake_case__					:	Optional[Any]												=      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		)     ->  List[Any]:



									'''simple docstring'''







									torch.manual_seed(0		)
									snake_case__					:	List[str]												=      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(__UpperCamelCase		)




					def 			__a			(   self		)     ->  str:



									'''simple docstring'''







									snake_case__					:	str												=      'cpu'  # ensure determinism for the device-dependent torch.Generator
									snake_case__					:	Tuple												=      self.dummy_cond_unet_upscale
									snake_case__					:	Tuple												=      DDPMScheduler()
									snake_case__					:	Optional[int]												=      DDIMScheduler(prediction_type='v_prediction'		)
									snake_case__					:	Any												=      self.dummy_vae
									snake_case__					:	List[str]												=      self.dummy_text_encoder
									snake_case__					:	List[str]												=      CLIPTokenizer.from_pretrained('hf-internal-testing/tiny-random-clip'		)

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

									# make sure here that pndm scheduler skips prk
									snake_case__					:	Optional[int]												=      StableDiffusionUpscalePipeline(
									    unet=__UpperCamelCase    ,       low_res_scheduler=__UpperCamelCase    ,       scheduler=__UpperCamelCase    ,       vae=__UpperCamelCase    ,       text_encoder=__UpperCamelCase    ,       tokenizer=__UpperCamelCase    ,       max_noise_level=350    ,       )
									snake_case__					:	str												=      sd_pipe.to(__UpperCamelCase		)
									sd_pipe.set_progress_bar_config(disable=__UpperCamelCase		)

									snake_case__					:	List[str]												=      'A painting of a squirrel eating a burger'
									snake_case__					:	Optional[Any]												=      torch.Generator(device=__UpperCamelCase		).manual_seed(0		)
									snake_case__					:	Union[str, Any]												=      sd_pipe(
									    [prompt]    ,       image=__UpperCamelCase    ,       generator=__UpperCamelCase    ,       guidance_scale=6.0    ,       noise_level=20    ,       num_inference_steps=2    ,       output_type='np'    ,       )

									snake_case__					:	Union[str, Any]												=      output.images

									snake_case__					:	List[Any]												=      torch.Generator(device=__UpperCamelCase		).manual_seed(0		)
									snake_case__					:	List[Any]												=      sd_pipe(
									    [prompt]    ,       image=__UpperCamelCase    ,       generator=__UpperCamelCase    ,       guidance_scale=6.0    ,       noise_level=20    ,       num_inference_steps=2    ,       output_type='np'    ,       return_dict=__UpperCamelCase    ,       )[0]

									snake_case__					:	Any												=      image[0, -3:, -3:, -1]
									snake_case__					:	Tuple												=      image_from_tuple[0, -3:, -3:, -1]

									snake_case__					:	Any												=      low_res_image.size[0] * 4
									assert image.shape == (1, expected_height_width, expected_height_width, 3)
									snake_case__					:	str												=      np.array([0.3_1_1_3, 0.3_9_1_0, 0.4_2_7_2, 0.4_8_5_9, 0.5_0_6_1, 0.4_6_5_2, 0.5_3_6_2, 0.5_7_1_5, 0.5_6_6_1]		)

									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		)     ->  Optional[int]:



									'''simple docstring'''







									snake_case__					:	str												=      'cpu'  # ensure determinism for the device-dependent torch.Generator
									snake_case__					:	str												=      self.dummy_cond_unet_upscale
									snake_case__					:	List[str]												=      DDPMScheduler()
									snake_case__					:	Optional[int]												=      DDIMScheduler(prediction_type='v_prediction'		)
									snake_case__					:	List[Any]												=      self.dummy_vae
									snake_case__					:	Optional[Any]												=      self.dummy_text_encoder
									snake_case__					:	Dict												=      CLIPTokenizer.from_pretrained('hf-internal-testing/tiny-random-clip'		)

									snake_case__					:	List[Any]												=      self.dummy_image.cpu().permute(0    ,       2    ,       3    ,       1		)[0]
									snake_case__					:	Optional[Any]												=      Image.fromarray(np.uinta(__UpperCamelCase		)		).convert('RGB'		).resize((64, 64)		)

									# make sure here that pndm scheduler skips prk
									snake_case__					:	int												=      StableDiffusionUpscalePipeline(
									    unet=__UpperCamelCase    ,       low_res_scheduler=__UpperCamelCase    ,       scheduler=__UpperCamelCase    ,       vae=__UpperCamelCase    ,       text_encoder=__UpperCamelCase    ,       tokenizer=__UpperCamelCase    ,       max_noise_level=350    ,       )
									snake_case__					:	Optional[int]												=      sd_pipe.to(__UpperCamelCase		)
									sd_pipe.set_progress_bar_config(disable=__UpperCamelCase		)

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

									snake_case__					:	int												=      torch.Generator(device=__UpperCamelCase		).manual_seed(0		)
									snake_case__					:	List[Any]												=      sd_pipe(
									    [prompt]    ,       image=__UpperCamelCase    ,       generator=__UpperCamelCase    ,       num_images_per_prompt=2    ,       guidance_scale=6.0    ,       noise_level=20    ,       num_inference_steps=2    ,       output_type='np'    ,       )
									snake_case__					:	List[Any]												=      output.images
									assert image.shape[0] == 2




					@unittest.skipIf(torch_device != 'cuda'    ,       'This test requires a GPU'		)
					def 			__a			(   self		)     ->  Tuple:



									'''simple docstring'''







									snake_case__					:	str												=      self.dummy_cond_unet_upscale
									snake_case__					:	str												=      DDPMScheduler()
									snake_case__					:	List[Any]												=      DDIMScheduler(prediction_type='v_prediction'		)
									snake_case__					:	Union[str, Any]												=      self.dummy_vae
									snake_case__					:	Tuple												=      self.dummy_text_encoder
									snake_case__					:	Optional[Any]												=      CLIPTokenizer.from_pretrained('hf-internal-testing/tiny-random-clip'		)

									snake_case__					:	Dict												=      self.dummy_image.cpu().permute(0    ,       2    ,       3    ,       1		)[0]
									snake_case__					:	Optional[int]												=      Image.fromarray(np.uinta(__UpperCamelCase		)		).convert('RGB'		).resize((64, 64)		)

									# put models in fp16, except vae as it overflows in fp16
									snake_case__					:	List[Any]												=      unet.half()
									snake_case__					:	Tuple												=      text_encoder.half()

									# make sure here that pndm scheduler skips prk
									snake_case__					:	List[str]												=      StableDiffusionUpscalePipeline(
									    unet=__UpperCamelCase    ,       low_res_scheduler=__UpperCamelCase    ,       scheduler=__UpperCamelCase    ,       vae=__UpperCamelCase    ,       text_encoder=__UpperCamelCase    ,       tokenizer=__UpperCamelCase    ,       max_noise_level=350    ,       )
									snake_case__					:	Optional[Any]												=      sd_pipe.to(__UpperCamelCase		)
									sd_pipe.set_progress_bar_config(disable=__UpperCamelCase		)

									snake_case__					:	str												=      'A painting of a squirrel eating a burger'
									snake_case__					:	Dict												=      torch.manual_seed(0		)
									snake_case__					:	int												=      sd_pipe(
									    [prompt]    ,       image=__UpperCamelCase    ,       generator=__UpperCamelCase    ,       num_inference_steps=2    ,       output_type='np'    ,       ).images

									snake_case__					:	int												=      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 			__a			(   self		)     ->  Tuple:



									'''simple docstring'''







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




					def 			__a			(   self		)     ->  int:



									'''simple docstring'''







									snake_case__					:	Dict												=      load_image(
									    'https://huggingface.co/datasets/hf-internal-testing/diffusers-images/resolve/main'
									    '/sd2-upscale/low_res_cat.png'		)
									snake_case__					:	Optional[Any]												=      load_numpy(
									    'https://huggingface.co/datasets/hf-internal-testing/diffusers-images/resolve/main/sd2-upscale'
									    '/upsampled_cat.npy'		)

									snake_case__					:	int												=      'stabilityai/stable-diffusion-x4-upscaler'
									snake_case__					:	List[Any]												=      StableDiffusionUpscalePipeline.from_pretrained(__UpperCamelCase		)
									pipe.to(__UpperCamelCase		)
									pipe.set_progress_bar_config(disable=__UpperCamelCase		)
									pipe.enable_attention_slicing()

									snake_case__					:	Tuple												=      'a cat sitting on a park bench'

									snake_case__					:	Union[str, Any]												=      torch.manual_seed(0		)
									snake_case__					:	str												=      pipe(
									    prompt=__UpperCamelCase    ,       image=__UpperCamelCase    ,       generator=__UpperCamelCase    ,       output_type='np'    ,       )
									snake_case__					:	str												=      output.images[0]

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




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



									'''simple docstring'''







									snake_case__					:	List[str]												=      load_image(
									    'https://huggingface.co/datasets/hf-internal-testing/diffusers-images/resolve/main'
									    '/sd2-upscale/low_res_cat.png'		)
									snake_case__					:	int												=      load_numpy(
									    'https://huggingface.co/datasets/hf-internal-testing/diffusers-images/resolve/main/sd2-upscale'
									    '/upsampled_cat_fp16.npy'		)

									snake_case__					:	Dict												=      'stabilityai/stable-diffusion-x4-upscaler'
									snake_case__					:	str												=      StableDiffusionUpscalePipeline.from_pretrained(
									    __UpperCamelCase    ,       torch_dtype=torch.floataa    ,       )
									pipe.to(__UpperCamelCase		)
									pipe.set_progress_bar_config(disable=__UpperCamelCase		)
									pipe.enable_attention_slicing()

									snake_case__					:	str												=      'a cat sitting on a park bench'

									snake_case__					:	int												=      torch.manual_seed(0		)
									snake_case__					:	Optional[Any]												=      pipe(
									    prompt=__UpperCamelCase    ,       image=__UpperCamelCase    ,       generator=__UpperCamelCase    ,       output_type='np'    ,       )
									snake_case__					:	int												=      output.images[0]

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




					def 			__a			(   self		)     ->  Tuple:



									'''simple docstring'''







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

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

									snake_case__					:	Dict												=      'stabilityai/stable-diffusion-x4-upscaler'
									snake_case__					:	Tuple												=      StableDiffusionUpscalePipeline.from_pretrained(
									    __UpperCamelCase    ,       torch_dtype=torch.floataa    ,       )
									pipe.to(__UpperCamelCase		)
									pipe.set_progress_bar_config(disable=__UpperCamelCase		)
									pipe.enable_attention_slicing(1		)
									pipe.enable_sequential_cpu_offload()

									snake_case__					:	Optional[int]												=      'a cat sitting on a park bench'

									snake_case__					:	Dict												=      torch.manual_seed(0		)
									snake_case__					:	str												=      pipe(
									    prompt=__UpperCamelCase    ,       image=__UpperCamelCase    ,       generator=__UpperCamelCase    ,       num_inference_steps=5    ,       output_type='np'    ,       )

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



import contextlib
import importlib
import io
import unittest

import transformers

# Try to import everything from transformers to ensure every object can be loaded.
from transformers import *  # noqa F406
from transformers.testing_utils import DUMMY_UNKNOWN_IDENTIFIER, require_flax, require_tf, require_torch
from transformers.utils import ContextManagers, find_labels, is_flax_available, is_tf_available, is_torch_available


if is_torch_available():
      from transformers import BertForPreTraining, BertForQuestionAnswering, BertForSequenceClassification

if is_tf_available():
      from transformers import TFBertForPreTraining, TFBertForQuestionAnswering, TFBertForSequenceClassification

if is_flax_available():
      from transformers import FlaxBertForPreTraining, FlaxBertForQuestionAnswering, FlaxBertForSequenceClassification


A   :     Tuple       =				DUMMY_UNKNOWN_IDENTIFIER
# An actual model hosted on huggingface.co

A   :     Dict       =				"main"
# Default branch name
A   :     List[str]       =				"f2c752cfc5c0ab6f4bdec59acea69eefbee381c2"
# One particular commit (not the top of `main`)
A   :     Tuple       =				"aaaaaaa"
# This commit does not exist, so we should 404.

A   :     int       =				"d9e9f15bc825e4b2c9249e9578f884bbcb5e3684"
# Sha-1 of config.json on the top of `main`, for checking purposes
A   :     Tuple       =				"4b243c475af8d0a7754e87d7d096c92e5199ec2fe168a2ee7998e3b8e9bcb1d3"


@contextlib.contextmanager
def    a__       (						):
      print("Welcome!" )
      yield
      print("Bye!" )


@contextlib.contextmanager
def    a__       (						):
      print("Bonjour!" )
      yield
      print("Au revoir!" )


class      lowerCamelCase    (unittest.TestCase    ):
  """simple docstring"""







  def       __A   (							self       :				Union[str, Any]      )     ->		Any:
        # If the spec is missing, importlib would not be able to import the module dynamically.
        assert transformers.__spec__ is not None
        assert importlib.util.find_spec("transformers"      ) is not None



class      lowerCamelCase    (unittest.TestCase    ):
  """simple docstring"""







  @unittest.mock.patch("sys.stdout"     ,   new_callable=io.StringIO      )
  def       __A   (							self       :				Tuple     ,   __magic_name__       :				Union[str, Any]      )     ->		Union[str, Any]:
        with ContextManagers([]      ):
              print("Transformers are awesome!"      )
        # The print statement adds a new line at the end of the output
        self.assertEqual(mock_stdout.getvalue()     ,   "Transformers are awesome!\n"      )







  @unittest.mock.patch("sys.stdout"     ,   new_callable=io.StringIO      )
  def       __A   (							self       :				Dict     ,   __magic_name__       :				Union[str, Any]      )     ->		int:
        with ContextManagers([context_en()]      ):
              print("Transformers are awesome!"      )
        # The output should be wrapped with an English welcome and goodbye
        self.assertEqual(mock_stdout.getvalue()     ,   "Welcome!\nTransformers are awesome!\nBye!\n"      )







  @unittest.mock.patch("sys.stdout"     ,   new_callable=io.StringIO      )
  def       __A   (							self       :				Tuple     ,   __magic_name__       :				str      )     ->		Union[str, Any]:
        with ContextManagers([context_fr(), context_en()]      ):
              print("Transformers are awesome!"      )
        # The output should be wrapped with an English and French welcome and goodbye
        self.assertEqual(mock_stdout.getvalue()     ,   "Bonjour!\nWelcome!\nTransformers are awesome!\nBye!\nAu revoir!\n"      )







  @require_torch
  def       __A   (							self       :				List[str]      )     ->		Union[str, Any]:
        self.assertEqual(find_labels(__magic_name__      )     ,   ["labels"]      )
        self.assertEqual(find_labels(__magic_name__      )     ,   ["labels", "next_sentence_label"]      )
        self.assertEqual(find_labels(__magic_name__      )     ,   ["start_positions", "end_positions"]      )


        class      lowerCamelCase    (SCREAMING_SNAKE_CASE__    ):
          """simple docstring"""







          pass



        self.assertEqual(find_labels(__magic_name__      )     ,   ["labels"]      )







  @require_tf
  def       __A   (							self       :				List[str]      )     ->		Optional[Any]:
        self.assertEqual(find_labels(__magic_name__      )     ,   ["labels"]      )
        self.assertEqual(find_labels(__magic_name__      )     ,   ["labels", "next_sentence_label"]      )
        self.assertEqual(find_labels(__magic_name__      )     ,   ["start_positions", "end_positions"]      )


        class      lowerCamelCase    (SCREAMING_SNAKE_CASE__    ):
          """simple docstring"""







          pass



        self.assertEqual(find_labels(__magic_name__      )     ,   ["labels"]      )







  @require_flax
  def       __A   (							self       :				int      )     ->		Tuple:
        # Flax models don't have labels
        self.assertEqual(find_labels(__magic_name__      )     ,   []      )
        self.assertEqual(find_labels(__magic_name__      )     ,   []      )
        self.assertEqual(find_labels(__magic_name__      )     ,   []      )


        class      lowerCamelCase    (SCREAMING_SNAKE_CASE__    ):
          """simple docstring"""







          pass



        self.assertEqual(find_labels(__magic_name__      )     ,   []      )


