






import gc
import unittest

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

from diffusers import (
    AutoencoderKL,
    DDIMScheduler,
    StableDiffusionSAGPipeline,
    UNetaDConditionModel,
)
from diffusers.utils import slow, torch_device
from diffusers.utils.testing_utils import enable_full_determinism, require_torch_gpu

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()



class   lowerCamelCase      (_snake_case ,  _snake_case ,  unittest.TestCase			):







		'''simple docstring'''



		_snake_case    :    Dict       						=  StableDiffusionSAGPipeline
		_snake_case    :    Optional[int]       						=  TEXT_TO_IMAGE_PARAMS
		_snake_case    :    str       						=  TEXT_TO_IMAGE_BATCH_PARAMS
		_snake_case    :    Optional[Any]       						=  TEXT_TO_IMAGE_IMAGE_PARAMS
		_snake_case    :    Optional[Any]       						=  TEXT_TO_IMAGE_IMAGE_PARAMS
		_snake_case    :    str       						=  False



		def 					__UpperCAmelCase			(							self   )	->							Optional[int]:
							torch.manual_seed(0   )
							UpperCAmelCase_    :      List[Any]            =						UNetaDConditionModel(
							    block_out_channels=(3_2, 6_4)				,		layers_per_block=2				,		sample_size=3_2				,		in_channels=4				,		out_channels=4				,		down_block_types=('DownBlock2D', 'CrossAttnDownBlock2D')				,		up_block_types=('CrossAttnUpBlock2D', 'UpBlock2D')				,		cross_attention_dim=3_2				,		)
							UpperCAmelCase_    :      Any            =						DDIMScheduler(
							    beta_start=0.0_00_85				,		beta_end=0.0_12				,		beta_schedule='scaled_linear'				,		clip_sample=_UpperCamelCase				,		set_alpha_to_one=_UpperCamelCase				,		)
							torch.manual_seed(0   )
							UpperCAmelCase_    :      List[str]            =						AutoencoderKL(
							    block_out_channels=[3_2, 6_4]				,		in_channels=3				,		out_channels=3				,		down_block_types=['DownEncoderBlock2D', 'DownEncoderBlock2D']				,		up_block_types=['UpDecoderBlock2D', 'UpDecoderBlock2D']				,		latent_channels=4				,		)
							torch.manual_seed(0   )
							UpperCAmelCase_    :      Optional[int]            =						CLIPTextConfig(
							    bos_token_id=0				,		eos_token_id=2				,		hidden_size=3_2				,		intermediate_size=3_7				,		layer_norm_eps=1E-05				,		num_attention_heads=4				,		num_hidden_layers=5				,		pad_token_id=1				,		vocab_size=1_0_0_0				,		)
							UpperCAmelCase_    :      int            =						CLIPTextModel(_UpperCamelCase   )
							UpperCAmelCase_    :      Dict            =						CLIPTokenizer.from_pretrained('hf-internal-testing/tiny-random-clip'   )

							UpperCAmelCase_    :      List[str]            =						{
							    'unet': unet,
							    'scheduler': scheduler,
							    'vae': vae,
							    'text_encoder': text_encoder,
							    'tokenizer': tokenizer,
							    'safety_checker': None,
							    'feature_extractor': None,
							}
							return components



		def 					__UpperCAmelCase			(							self				,		_UpperCamelCase				,		_UpperCamelCase=0   )	->							Dict:
							if str(_UpperCamelCase   ).startswith('mps'   ):
												UpperCAmelCase_    :      Optional[int]            =						torch.manual_seed(_UpperCamelCase   )
							else:
												UpperCAmelCase_    :      List[Any]            =						torch.Generator(device=_UpperCamelCase   ).manual_seed(_UpperCamelCase   )
							UpperCAmelCase_    :      Tuple            =						{
							    'prompt': '.',
							    'generator': generator,
							    'num_inference_steps': 2,
							    'guidance_scale': 1.0,
							    'sag_scale': 1.0,
							    'output_type': 'numpy',
							}
							return inputs



		def 					__UpperCAmelCase			(							self   )	->							Any:
							super().test_inference_batch_single_identical(expected_max_diff=3E-3   )





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







		'''simple docstring'''



		def 					__UpperCAmelCase			(							self   )	->							int:
							# clean up the VRAM after each test
							super().tearDown()
							gc.collect()
							torch.cuda.empty_cache()



		def 					__UpperCAmelCase			(							self   )	->							int:
							UpperCAmelCase_    :      Any            =						StableDiffusionSAGPipeline.from_pretrained('CompVis/stable-diffusion-v1-4'   )
							UpperCAmelCase_    :      str            =						sag_pipe.to(_UpperCamelCase   )
							sag_pipe.set_progress_bar_config(disable=_UpperCamelCase   )

							UpperCAmelCase_    :      Dict            =						'.'
							UpperCAmelCase_    :      Optional[int]            =						torch.manual_seed(0   )
							UpperCAmelCase_    :      List[str]            =						sag_pipe(
							    [prompt]				,		generator=_UpperCamelCase				,		guidance_scale=7.5				,		sag_scale=1.0				,		num_inference_steps=2_0				,		output_type='np'   )

							UpperCAmelCase_    :      Tuple            =						output.images

							UpperCAmelCase_    :      Optional[Any]            =						image[0, -3:, -3:, -1]

							assert image.shape == (1, 5_1_2, 5_1_2, 3)
							UpperCAmelCase_    :      List[str]            =						np.array([0.15_68, 0.17_38, 0.16_95, 0.16_93, 0.15_07, 0.17_05, 0.15_47, 0.17_51, 0.19_49]   )

							assert np.abs(image_slice.flatten() - expected_slice   ).max() < 5E-2



		def 					__UpperCAmelCase			(							self   )	->							Optional[Any]:
							UpperCAmelCase_    :      int            =						StableDiffusionSAGPipeline.from_pretrained('stabilityai/stable-diffusion-2-1-base'   )
							UpperCAmelCase_    :      int            =						sag_pipe.to(_UpperCamelCase   )
							sag_pipe.set_progress_bar_config(disable=_UpperCamelCase   )

							UpperCAmelCase_    :      List[Any]            =						'.'
							UpperCAmelCase_    :      Union[str, Any]            =						torch.manual_seed(0   )
							UpperCAmelCase_    :      str            =						sag_pipe(
							    [prompt]				,		generator=_UpperCamelCase				,		guidance_scale=7.5				,		sag_scale=1.0				,		num_inference_steps=2_0				,		output_type='np'   )

							UpperCAmelCase_    :      Any            =						output.images

							UpperCAmelCase_    :      str            =						image[0, -3:, -3:, -1]

							assert image.shape == (1, 5_1_2, 5_1_2, 3)
							UpperCAmelCase_    :      Optional[Any]            =						np.array([0.34_59, 0.28_76, 0.25_37, 0.30_02, 0.26_71, 0.21_60, 0.30_26, 0.22_62, 0.23_71]   )

							assert np.abs(image_slice.flatten() - expected_slice   ).max() < 5E-2



		def 					__UpperCAmelCase			(							self   )	->							Union[str, Any]:
							UpperCAmelCase_    :      Tuple            =						StableDiffusionSAGPipeline.from_pretrained('stabilityai/stable-diffusion-2-1-base'   )
							UpperCAmelCase_    :      Optional[int]            =						sag_pipe.to(_UpperCamelCase   )
							sag_pipe.set_progress_bar_config(disable=_UpperCamelCase   )

							UpperCAmelCase_    :      Any            =						'.'
							UpperCAmelCase_    :      int            =						torch.manual_seed(0   )
							UpperCAmelCase_    :      str            =						sag_pipe(
							    [prompt]				,		width=7_6_8				,		height=5_1_2				,		generator=_UpperCamelCase				,		guidance_scale=7.5				,		sag_scale=1.0				,		num_inference_steps=2_0				,		output_type='np'				,		)

							UpperCAmelCase_    :      Dict            =						output.images

							assert image.shape == (1, 5_1_2, 7_6_8, 3)














def      lowercase__      (     __snake_case    :							Dict  ):


					'''simple docstring'''


					if not head:
										return True
					# split the list to two parts
					UpperCAmelCase_       ,  UpperCAmelCase_    :      Any            =						head.next, head
					while fast and fast.next:
										UpperCAmelCase_    :      str            =						fast.next.next
										UpperCAmelCase_    :      Union[str, Any]            =						slow.next
					UpperCAmelCase_    :      int            =						slow.next
					UpperCAmelCase_    :      List[Any]            =						None  # Don't forget here! But forget still works!
					# reverse the second part
					UpperCAmelCase_    :      Tuple            =						None
					while second:
										UpperCAmelCase_    :      int            =						second.next
										UpperCAmelCase_    :      Any            =						node
										UpperCAmelCase_    :      Optional[Any]            =						second
										UpperCAmelCase_    :      Tuple            =						nxt
					# compare two parts
					# second part has the same or one less node
					while node:
										if node.val != head.val:
															return False
										UpperCAmelCase_    :      Optional[Any]            =						node.next
										UpperCAmelCase_    :      Dict            =						head.next
					return True




def      lowercase__      (     __snake_case    :							Union[str, Any]  ):


					'''simple docstring'''


					if not head or not head.next:
										return True

					# 1. Get the midpoint (slow)
					UpperCAmelCase_    :      Any            =						head
					while fast and fast.next:
										UpperCAmelCase_       ,  UpperCAmelCase_    :      Tuple            =						fast.next.next, slow.next

					# 2. Push the second half into the stack
					UpperCAmelCase_    :      List[str]            =						[slow.val]
					while slow.next:
										UpperCAmelCase_    :      List[str]            =						slow.next
										stack.append(slow.val  )

					# 3. Comparison
					while stack:
										if stack.pop() != cur.val:
															return False
										UpperCAmelCase_    :      int            =						cur.next

					return True






def      lowercase__      (     __snake_case    :							Dict  ):


					'''simple docstring'''


					if not head or not head.next:
										return True
					UpperCAmelCase_    :      Tuple            =						{}
					UpperCAmelCase_    :      int            =						0
					while head:
										if head.val in d:
															d[head.val].append(__snake_case  )
										else:
															UpperCAmelCase_    :      List[Any]            =						[pos]
										UpperCAmelCase_    :      Any            =						head.next
										pos += 1
					UpperCAmelCase_    :      Dict            =						pos - 1
					UpperCAmelCase_    :      Optional[int]            =						0
					for v in d.values():
										if len(__snake_case  ) % 2 != 0:
															middle += 1
										else:
															UpperCAmelCase_    :      int            =						0
															for i in range(0     ,       len(__snake_case  )  ):
																				if v[i] + v[len(__snake_case  ) - 1 - step] != checksum:
																									return False
																				step += 1
										if middle > 1:
															return False
					return True






