


import gc
import unittest

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

from diffusers import (
    AutoencoderKL,
    DDIMScheduler,
    EulerAncestralDiscreteScheduler,
    LMSDiscreteScheduler,
    PNDMScheduler,
    StableDiffusionPanoramaPipeline,
    UNetaDConditionModel,
)
from diffusers.utils import slow, torch_device
from diffusers.utils.testing_utils import enable_full_determinism, require_torch_gpu, skip_mps

from ..pipeline_params import TEXT_TO_IMAGE_BATCH_PARAMS, TEXT_TO_IMAGE_IMAGE_PARAMS, TEXT_TO_IMAGE_PARAMS
from ..test_pipelines_common import PipelineLatentTesterMixin, PipelineTesterMixin


enable_full_determinism()


@skip_mps
class       a__				( __SCREAMING_SNAKE_CASE							,						__SCREAMING_SNAKE_CASE							,						unittest.TestCase      ):







				"""simple docstring"""



				__UpperCamelCase    :		Optional[int]	=	StableDiffusionPanoramaPipeline
				__UpperCamelCase    :		List[str]	=	TEXT_TO_IMAGE_PARAMS
				__UpperCamelCase    :		Dict	=	TEXT_TO_IMAGE_BATCH_PARAMS
				__UpperCamelCase    :		Any	=	TEXT_TO_IMAGE_IMAGE_PARAMS
				__UpperCamelCase    :		str	=	TEXT_TO_IMAGE_IMAGE_PARAMS




				def 					_snake_case  (self		):
										torch.manual_seed(0		)
										__lowerCAmelCase							       =				UNetaDConditionModel(
										    block_out_channels=(32, 64)       ,			layers_per_block=1       ,			sample_size=32       ,			in_channels=4       ,			out_channels=4       ,			down_block_types=('''DownBlock2D''', '''CrossAttnDownBlock2D''')       ,			up_block_types=('''CrossAttnUpBlock2D''', '''UpBlock2D''')       ,			cross_attention_dim=32       ,			)
										__lowerCAmelCase							       =				DDIMScheduler()
										torch.manual_seed(0		)
										__lowerCAmelCase							       =				AutoencoderKL(
										    block_out_channels=[32, 64]       ,			in_channels=3       ,			out_channels=3       ,			down_block_types=['''DownEncoderBlock2D''', '''DownEncoderBlock2D''']       ,			up_block_types=['''UpDecoderBlock2D''', '''UpDecoderBlock2D''']       ,			latent_channels=4       ,			)
										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=10_00       ,			)
										__lowerCAmelCase							       =				CLIPTextModel(_a		)
										__lowerCAmelCase							       =				CLIPTokenizer.from_pretrained('''hf-internal-testing/tiny-random-clip'''		)

										__lowerCAmelCase							       =				{
										    '''unet''': unet,
										    '''scheduler''': scheduler,
										    '''vae''': vae,
										    '''text_encoder''': text_encoder,
										    '''tokenizer''': tokenizer,
										    '''safety_checker''': None,
										    '''feature_extractor''': None,
										}
										return components




				def 					_snake_case  (self       ,			__lowercase       ,			__lowercase=0		):
										__lowerCAmelCase							       =				torch.manual_seed(_a		)
										__lowerCAmelCase							       =				{
										    '''prompt''': '''a photo of the dolomites''',
										    '''generator''': generator,
										    # Setting height and width to None to prevent OOMs on CPU.
										    '''height''': None,
										    '''width''': None,
										    '''num_inference_steps''': 1,
										    '''guidance_scale''': 6.0,
										    '''output_type''': '''numpy''',
										}
										return inputs




				def 					_snake_case  (self		):
										__lowerCAmelCase							       =				'''cpu'''  # ensure determinism for the device-dependent torch.Generator
										__lowerCAmelCase							       =				self.get_dummy_components()
										__lowerCAmelCase							       =				StableDiffusionPanoramaPipeline(**_a		)
										__lowerCAmelCase							       =				sd_pipe.to(_a		)
										sd_pipe.set_progress_bar_config(disable=_a		)

										__lowerCAmelCase							       =				self.get_dummy_inputs(_a		)
										__lowerCAmelCase							       =				sd_pipe(**_a		).images
										__lowerCAmelCase							       =				image[0, -3:, -3:, -1]
										assert image.shape == (1, 64, 64, 3)

										__lowerCAmelCase							       =				np.array([0.6_1_8_6, 0.5_3_7_4, 0.4_9_1_5, 0.4_1_3_5, 0.4_1_1_4, 0.4_5_6_3, 0.5_1_2_8, 0.4_9_7_7, 0.4_7_5_7]		)

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




				def 					_snake_case  (self		):
										super().test_inference_batch_consistent(batch_sizes=[1, 2]		)




				def 					_snake_case  (self		):
										super().test_inference_batch_single_identical(batch_size=2       ,			expected_max_diff=3.25e-3		)




				def 					_snake_case  (self		):
										__lowerCAmelCase							       =				'''cpu'''  # ensure determinism for the device-dependent torch.Generator
										__lowerCAmelCase							       =				self.get_dummy_components()
										__lowerCAmelCase							       =				StableDiffusionPanoramaPipeline(**_a		)
										__lowerCAmelCase							       =				sd_pipe.to(_a		)
										sd_pipe.set_progress_bar_config(disable=_a		)

										__lowerCAmelCase							       =				self.get_dummy_inputs(_a		)
										__lowerCAmelCase							       =				'''french fries'''
										__lowerCAmelCase							       =				sd_pipe(**_a       ,			negative_prompt=_a		)
										__lowerCAmelCase							       =				output.images
										__lowerCAmelCase							       =				image[0, -3:, -3:, -1]

										assert image.shape == (1, 64, 64, 3)

										__lowerCAmelCase							       =				np.array([0.6_1_8_7, 0.5_3_7_5, 0.4_9_1_5, 0.4_1_3_6, 0.4_1_1_4, 0.4_5_6_3, 0.5_1_2_8, 0.4_9_7_6, 0.4_7_5_7]		)

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




				def 					_snake_case  (self		):
										__lowerCAmelCase							       =				'''cpu'''  # ensure determinism for the device-dependent torch.Generator
										__lowerCAmelCase							       =				self.get_dummy_components()
										__lowerCAmelCase							       =				StableDiffusionPanoramaPipeline(**_a		)
										__lowerCAmelCase							       =				sd_pipe.to(_a		)
										sd_pipe.set_progress_bar_config(disable=_a		)

										__lowerCAmelCase							       =				self.get_dummy_inputs(_a		)
										__lowerCAmelCase							       =				sd_pipe(**_a       ,			view_batch_size=2		)
										__lowerCAmelCase							       =				output.images
										__lowerCAmelCase							       =				image[0, -3:, -3:, -1]

										assert image.shape == (1, 64, 64, 3)

										__lowerCAmelCase							       =				np.array([0.6_1_8_7, 0.5_3_7_5, 0.4_9_1_5, 0.4_1_3_6, 0.4_1_1_4, 0.4_5_6_3, 0.5_1_2_8, 0.4_9_7_6, 0.4_7_5_7]		)

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




				def 					_snake_case  (self		):
										__lowerCAmelCase							       =				'''cpu'''  # ensure determinism for the device-dependent torch.Generator
										__lowerCAmelCase							       =				self.get_dummy_components()
										__lowerCAmelCase							       =				EulerAncestralDiscreteScheduler(
										    beta_start=0.0_0_0_8_5       ,			beta_end=0.0_1_2       ,			beta_schedule='''scaled_linear'''		)
										__lowerCAmelCase							       =				StableDiffusionPanoramaPipeline(**_a		)
										__lowerCAmelCase							       =				sd_pipe.to(_a		)
										sd_pipe.set_progress_bar_config(disable=_a		)

										__lowerCAmelCase							       =				self.get_dummy_inputs(_a		)
										__lowerCAmelCase							       =				sd_pipe(**_a		).images
										__lowerCAmelCase							       =				image[0, -3:, -3:, -1]

										assert image.shape == (1, 64, 64, 3)

										__lowerCAmelCase							       =				np.array([0.4_0_2_4, 0.6_5_1_0, 0.4_9_0_1, 0.5_3_7_8, 0.5_8_1_3, 0.5_6_2_2, 0.4_7_9_5, 0.4_4_6_7, 0.4_9_5_2]		)

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




				def 					_snake_case  (self		):
										__lowerCAmelCase							       =				'''cpu'''  # ensure determinism for the device-dependent torch.Generator
										__lowerCAmelCase							       =				self.get_dummy_components()
										__lowerCAmelCase							       =				PNDMScheduler(
										    beta_start=0.0_0_0_8_5       ,			beta_end=0.0_1_2       ,			beta_schedule='''scaled_linear'''       ,			skip_prk_steps=_a		)
										__lowerCAmelCase							       =				StableDiffusionPanoramaPipeline(**_a		)
										__lowerCAmelCase							       =				sd_pipe.to(_a		)
										sd_pipe.set_progress_bar_config(disable=_a		)

										__lowerCAmelCase							       =				self.get_dummy_inputs(_a		)
										__lowerCAmelCase							       =				sd_pipe(**_a		).images
										__lowerCAmelCase							       =				image[0, -3:, -3:, -1]

										assert image.shape == (1, 64, 64, 3)

										__lowerCAmelCase							       =				np.array([0.6_3_9_1, 0.6_2_9_1, 0.4_8_6_1, 0.5_1_3_4, 0.5_5_5_2, 0.4_5_7_8, 0.5_0_3_2, 0.5_0_2_3, 0.4_5_3_9]		)

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


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







				"""simple docstring"""



				def 					_snake_case  (self		):
										super().tearDown()
										gc.collect()
										torch.cuda.empty_cache()




				def 					_snake_case  (self       ,			__lowercase=0		):
										__lowerCAmelCase							       =				torch.manual_seed(_a		)
										__lowerCAmelCase							       =				{
										    '''prompt''': '''a photo of the dolomites''',
										    '''generator''': generator,
										    '''num_inference_steps''': 3,
										    '''guidance_scale''': 7.5,
										    '''output_type''': '''numpy''',
										}
										return inputs




				def 					_snake_case  (self		):
										__lowerCAmelCase							       =				'''stabilityai/stable-diffusion-2-base'''
										__lowerCAmelCase							       =				DDIMScheduler.from_pretrained(_a       ,			subfolder='''scheduler'''		)
										__lowerCAmelCase							       =				StableDiffusionPanoramaPipeline.from_pretrained(_a       ,			scheduler=_a       ,			safety_checker=_a		)
										pipe.to(_a		)
										pipe.set_progress_bar_config(disable=_a		)
										pipe.enable_attention_slicing()

										__lowerCAmelCase							       =				self.get_inputs()
										__lowerCAmelCase							       =				pipe(**_a		).images
										__lowerCAmelCase							       =				image[0, -3:, -3:, -1].flatten()

										assert image.shape == (1, 5_12, 20_48, 3)

										__lowerCAmelCase							       =				np.array(
										    [
										        0.3_6_9_6_8_3_9_2,
										        0.2_7_0_2_5_3_7_2,
										        0.3_2_4_4_6_7_6_6,
										        0.2_8_3_7_9_3_8_7,
										        0.3_6_3_6_3_2_7_4,
										        0.3_0_7_3_3_3_4_7,
										        0.2_7_1_0_0_0_2_7,
										        0.2_7_0_5_4_1_2_5,
										        0.2_5_5_3_6_0_9_6,
										    ]		)

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




				def 					_snake_case  (self		):
										__lowerCAmelCase							       =				StableDiffusionPanoramaPipeline.from_pretrained(
										    '''stabilityai/stable-diffusion-2-base'''       ,			safety_checker=_a		)
										__lowerCAmelCase							       =				LMSDiscreteScheduler.from_config(pipe.scheduler.config		)
										pipe.to(_a		)
										pipe.set_progress_bar_config(disable=_a		)
										pipe.enable_attention_slicing()

										__lowerCAmelCase							       =				self.get_inputs()
										__lowerCAmelCase							       =				pipe(**_a		).images
										__lowerCAmelCase							       =				image[0, -3:, -3:, -1].flatten()

										assert image.shape == (1, 5_12, 20_48, 3)

										__lowerCAmelCase							       =				np.array(
										    [
										        [
										            0.0,
										            0.0,
										            0.0,
										            0.0,
										            0.0,
										            0.0,
										            0.0,
										            0.0,
										            0.0,
										        ]
										    ]		)

										assert np.abs(expected_slice - image_slice		).max() < 1e-3




				def 					_snake_case  (self		):
										__lowerCAmelCase							       =				0

										def callback_fn(__lowercase       ,			__lowercase       ,			__lowercase		) -> None:
																__lowerCAmelCase							       =				True
																nonlocal number_of_steps
																number_of_steps += 1
																if step == 1:
																						__lowerCAmelCase							       =				latents.detach().cpu().numpy()
																						assert latents.shape == (1, 4, 64, 2_56)
																						__lowerCAmelCase							       =				latents[0, -3:, -3:, -1]

																						__lowerCAmelCase							       =				np.array(
																						    [
																						        0.1_8_6_8_1_8_6_9,
																						        0.3_3_9_0_7_8_1_6,
																						        0.5_3_6_1_2_7_6,
																						        0.1_4_4_3_2_8_6_5,
																						        -0.0_2_8_5_6_6_1_1,
																						        -0.7_3_9_4_1_1_2_3,
																						        0.2_3_3_9_7_9_8_7,
																						        0.4_7_3_2_2_6_8_2,
																						        -0.3_7_8_2_3_1_6_4,
																						    ]		)
																						assert np.abs(latents_slice.flatten() - expected_slice		).max() < 5e-2
																elif step == 2:
																						__lowerCAmelCase							       =				latents.detach().cpu().numpy()
																						assert latents.shape == (1, 4, 64, 2_56)
																						__lowerCAmelCase							       =				latents[0, -3:, -3:, -1]

																						__lowerCAmelCase							       =				np.array(
																						    [
																						        0.1_8_5_3_9_6_4_5,
																						        0.3_3_9_8_7_2_4_8,
																						        0.5_3_7_8_5_5_9,
																						        0.1_4_4_3_7_1_4_2,
																						        -0.0_2_4_5_5_2_6_1,
																						        -0.7_3_3_8_3_1_7,
																						        0.2_3_9_9_0_7_5_5,
																						        0.4_7_3_5_6_2_7_2,
																						        -0.3_7_8_6_5_0_5,
																						    ]		)

																						assert np.abs(latents_slice.flatten() - expected_slice		).max() < 5e-2

										__lowerCAmelCase							       =				False

										__lowerCAmelCase							       =				'''stabilityai/stable-diffusion-2-base'''
										__lowerCAmelCase							       =				DDIMScheduler.from_pretrained(_a       ,			subfolder='''scheduler'''		)
										__lowerCAmelCase							       =				StableDiffusionPanoramaPipeline.from_pretrained(_a       ,			scheduler=_a       ,			safety_checker=_a		)
										__lowerCAmelCase							       =				pipe.to(_a		)
										pipe.set_progress_bar_config(disable=_a		)
										pipe.enable_attention_slicing()

										__lowerCAmelCase							       =				self.get_inputs()
										pipe(**_a       ,			callback=_a       ,			callback_steps=1		)
										assert callback_fn.has_been_called
										assert number_of_steps == 3




				def 					_snake_case  (self		):
										torch.cuda.empty_cache()
										torch.cuda.reset_max_memory_allocated()
										torch.cuda.reset_peak_memory_stats()

										__lowerCAmelCase							       =				'''stabilityai/stable-diffusion-2-base'''
										__lowerCAmelCase							       =				DDIMScheduler.from_pretrained(_a       ,			subfolder='''scheduler'''		)
										__lowerCAmelCase							       =				StableDiffusionPanoramaPipeline.from_pretrained(_a       ,			scheduler=_a       ,			safety_checker=_a		)
										__lowerCAmelCase							       =				pipe.to(_a		)
										pipe.set_progress_bar_config(disable=_a		)
										pipe.enable_attention_slicing(1		)
										pipe.enable_sequential_cpu_offload()

										__lowerCAmelCase							       =				self.get_inputs()
										__lowerCAmelCase							       =				pipe(**_a		)

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





'''simple docstring'''

import json
import os
import unittest

from transformers import MgpstrTokenizer
from transformers.models.mgp_str.tokenization_mgp_str import VOCAB_FILES_NAMES
from transformers.testing_utils import require_tokenizers

from ...test_tokenization_common import TokenizerTesterMixin


@require_tokenizers
class       a__				( __A							,						unittest.TestCase      ):







				"""simple docstring"""



				__UpperCamelCase    :		int	=	MgpstrTokenizer
				__UpperCamelCase    :		Optional[Any]	=	False
				__UpperCamelCase    :		Optional[int]	=	{}
				__UpperCamelCase    :		List[Any]	=	False




				def 					_snake_case  (self		):
										super().setUp()

										# fmt: off
										__lowerCAmelCase							       =				['''[GO]''', '''[s]''', '''0''', '''1''', '''2''', '''3''', '''4''', '''5''', '''6''', '''7''', '''8''', '''9''', '''a''', '''b''', '''c''', '''d''', '''e''', '''f''', '''g''', '''h''', '''i''', '''j''', '''k''', '''l''', '''m''', '''n''', '''o''', '''p''', '''q''', '''r''', '''s''', '''t''', '''u''', '''v''', '''w''', '''x''', '''y''', '''z''']
										# fmt: on
										__lowerCAmelCase							       =				dict(zip(__lowercase       ,			range(len(__lowercase		)		)		)		)

										__lowerCAmelCase							       =				os.path.join(self.tmpdirname       ,			VOCAB_FILES_NAMES['''vocab_file''']		)
										with open(self.vocab_file       ,			'''w'''       ,			encoding='''utf-8'''		) as fp:
																fp.write(json.dumps(__lowercase		) + '''\n'''		)




				def 					_snake_case  (self       ,			**__lowercase		):
										return MgpstrTokenizer.from_pretrained(self.tmpdirname       ,			**__lowercase		)




				def 					_snake_case  (self       ,			__lowercase		):
										__lowerCAmelCase							       =				'''tester'''
										__lowerCAmelCase							       =				'''tester'''
										return input_text, output_text




				@unittest.skip('''MGP-STR always lower cases letters.'''		)
				def 					_snake_case  (self		):
										pass




				def 					_snake_case  (self		):
										__lowerCAmelCase							       =				self.get_tokenizers(do_lower_case=__lowercase		)
										for tokenizer in tokenizers:
																with self.subTest(F"""{tokenizer.__class__.__name__}"""		):
																						__lowerCAmelCase							       =				'''[SPECIAL_TOKEN]'''

																						tokenizer.add_special_tokens({'''cls_token''': special_token}		)
																						__lowerCAmelCase							       =				tokenizer.encode([special_token]       ,			add_special_tokens=__lowercase		)
																						self.assertEqual(len(__lowercase		)       ,			1		)

																						__lowerCAmelCase							       =				tokenizer.decode(__lowercase       ,			skip_special_tokens=__lowercase		)
																						self.assertTrue(special_token not in decoded		)




				def 					_snake_case  (self		):
										__lowerCAmelCase							       =				self.get_tokenizers()
										for tokenizer in tokenizers:
																with self.subTest(F"""{tokenizer.__class__.__name__}"""		):
																						__lowerCAmelCase       ,					__lowerCAmelCase							       =				self.get_input_output_texts(__lowercase		)

																						__lowerCAmelCase							       =				tokenizer.tokenize(__lowercase		)
																						__lowerCAmelCase							       =				tokenizer.convert_tokens_to_ids(__lowercase		)
																						__lowerCAmelCase							       =				tokenizer.encode(__lowercase       ,			add_special_tokens=__lowercase		)
																						self.assertListEqual(__lowercase       ,			__lowercase		)

																						__lowerCAmelCase							       =				tokenizer.convert_ids_to_tokens(__lowercase		)
																						self.assertNotEqual(len(__lowercase		)       ,			0		)
																						__lowerCAmelCase							       =				tokenizer.decode(__lowercase		)
																						self.assertIsInstance(__lowercase       ,			__lowercase		)

																						self.assertEqual(text_a.replace(''' '''       ,			''''''		)       ,			__lowercase		)




				@unittest.skip('''MGP-STR tokenizer only handles one sequence.'''		)
				def 					_snake_case  (self		):
										pass




				@unittest.skip('''inputs cannot be pretokenized in MgpstrTokenizer'''		)
				def 					_snake_case  (self		):
										pass

