

import gc
import unittest

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

from diffusers import (
    AutoencoderKL,
    DDIMScheduler,
    PNDMScheduler,
    StableDiffusionLDMaDPipeline,
    UNetaDConditionModel,
)
from diffusers.utils import nightly, 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


enable_full_determinism()






class 	A_		(	unittest.TestCase    ):
							_UpperCAmelCase   :  Optional[Any]										=				StableDiffusionLDMaDPipeline
							_UpperCAmelCase   :  Optional[Any]										=				TEXT_TO_IMAGE_PARAMS
							_UpperCAmelCase   :  Optional[Any]										=				TEXT_TO_IMAGE_BATCH_PARAMS
							_UpperCAmelCase   :  Dict										=				TEXT_TO_IMAGE_IMAGE_PARAMS
							def    lowerCAmelCase					(		self		:      Optional[Any]):
								torch.manual_seed(0)
								__lowerCamelCase    :    str 	=			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       ,)
								__lowerCamelCase    :    Tuple 	=			DDIMScheduler(
								    beta_start=0.00085       ,beta_end=0.012       ,beta_schedule='scaled_linear'       ,clip_sample=SCREAMING_SNAKE_CASE__       ,set_alpha_to_one=SCREAMING_SNAKE_CASE__       ,)
								torch.manual_seed(0)
								__lowerCamelCase    :    Union[str, Any] 	=			AutoencoderKL(
								    block_out_channels=[3_2, 6_4]       ,in_channels=6       ,out_channels=6       ,down_block_types=['DownEncoderBlock2D', 'DownEncoderBlock2D']       ,up_block_types=['UpDecoderBlock2D', 'UpDecoderBlock2D']       ,latent_channels=4       ,)
								torch.manual_seed(0)
								__lowerCamelCase    :    Tuple 	=			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       ,)
								__lowerCamelCase    :    Optional[int] 	=			CLIPTextModel(SCREAMING_SNAKE_CASE__)
								__lowerCamelCase    :    Tuple 	=			CLIPTokenizer.from_pretrained('hf-internal-testing/tiny-random-clip')

								__lowerCamelCase    :    Union[str, Any] 	=			{
								    'unet': unet,
								    'scheduler': scheduler,
								    'vae': vae,
								    'text_encoder': text_encoder,
								    'tokenizer': tokenizer,
								    'safety_checker': None,
								    'feature_extractor': None,
								}
								return components
							def    lowerCAmelCase					(		self		:      int       ,SCREAMING_SNAKE_CASE__		:      Any       ,SCREAMING_SNAKE_CASE__		:      Dict=0):
								if str(SCREAMING_SNAKE_CASE__).startswith('mps'):
									__lowerCamelCase    :    int 	=			torch.manual_seed(SCREAMING_SNAKE_CASE__)
								else:
									__lowerCamelCase    :    Optional[Any] 	=			torch.Generator(device=SCREAMING_SNAKE_CASE__).manual_seed(SCREAMING_SNAKE_CASE__)
								__lowerCamelCase    :    str 	=			{
								    'prompt': 'A painting of a squirrel eating a burger',
								    'generator': generator,
								    'num_inference_steps': 2,
								    'guidance_scale': 6.0,
								    'output_type': 'numpy',
								}
								return inputs
							def    lowerCAmelCase					(		self		:      str):
								__lowerCamelCase    :    Any 	=			'cpu'  # ensure determinism for the device-dependent torch.Generator

								__lowerCamelCase    :    Optional[int] 	=			self.get_dummy_components()
								__lowerCamelCase    :    int 	=			StableDiffusionLDMaDPipeline(**SCREAMING_SNAKE_CASE__)
								__lowerCamelCase    :    Optional[int] 	=			ldmad_pipe.to(SCREAMING_SNAKE_CASE__)
								ldmad_pipe.set_progress_bar_config(disable=SCREAMING_SNAKE_CASE__)

								__lowerCamelCase    :    Dict 	=			self.get_dummy_inputs(SCREAMING_SNAKE_CASE__)
								__lowerCamelCase    :    Optional[int] 	=			ldmad_pipe(**SCREAMING_SNAKE_CASE__)
								__lowerCamelCase	,			__lowerCamelCase    :    Any 	=			output.rgb, output.depth

								__lowerCamelCase    :    Union[str, Any] 	=			rgb[0, -3:, -3:, -1]
								__lowerCamelCase    :    Optional[Any] 	=			depth[0, -3:, -1]

								assert rgb.shape == (1, 6_4, 6_4, 3)
								assert depth.shape == (1, 6_4, 6_4)

								__lowerCamelCase    :    int 	=			np.array(
								    [0.37338176, 0.70247, 0.74203193, 0.51643604, 0.58256793, 0.60932136, 0.4181095, 0.48355877, 0.46535262])
								__lowerCamelCase    :    Any 	=			np.array([103.46727, 85.812004, 87.849236])

								assert np.abs(image_slice_rgb.flatten() - expected_slice_rgb).max() < 1E-2
								assert np.abs(image_slice_depth.flatten() - expected_slice_depth).max() < 1E-2
							def    lowerCAmelCase					(		self		:      Optional[int]):
								__lowerCamelCase    :    Dict 	=			self.get_dummy_components()
								__lowerCamelCase    :    Any 	=			StableDiffusionLDMaDPipeline(**SCREAMING_SNAKE_CASE__)
								__lowerCamelCase    :    Union[str, Any] 	=			ldmad_pipe.to(SCREAMING_SNAKE_CASE__)
								ldmad_pipe.set_progress_bar_config(disable=SCREAMING_SNAKE_CASE__)

								__lowerCamelCase    :    str 	=			self.get_dummy_inputs(SCREAMING_SNAKE_CASE__)
								__lowerCamelCase    :    Any 	=			3 * [inputs['prompt']]

								# forward
								__lowerCamelCase    :    int 	=			ldmad_pipe(**SCREAMING_SNAKE_CASE__)
								__lowerCamelCase	,			__lowerCamelCase    :    int 	=			output.rgb, output.depth
								__lowerCamelCase    :    Tuple 	=			rgb_slice_a[0, -3:, -3:, -1]
								__lowerCamelCase    :    List[str] 	=			depth_slice_a[0, -3:, -1]

								__lowerCamelCase    :    str 	=			self.get_dummy_inputs(SCREAMING_SNAKE_CASE__)
								__lowerCamelCase    :    Union[str, Any] 	=			3 * [inputs.pop('prompt')]

								__lowerCamelCase    :    List[Any] 	=			ldmad_pipe.tokenizer(
								    SCREAMING_SNAKE_CASE__       ,padding='max_length'       ,max_length=ldmad_pipe.tokenizer.model_max_length       ,truncation=SCREAMING_SNAKE_CASE__       ,return_tensors='pt'       ,)
								__lowerCamelCase    :    List[Any] 	=			text_inputs['input_ids'].to(SCREAMING_SNAKE_CASE__)

								__lowerCamelCase    :    Dict 	=			ldmad_pipe.text_encoder(SCREAMING_SNAKE_CASE__)[0]

								__lowerCamelCase    :    Dict 	=			prompt_embeds

								# forward
								__lowerCamelCase    :    Tuple 	=			ldmad_pipe(**SCREAMING_SNAKE_CASE__)
								__lowerCamelCase	,			__lowerCamelCase    :    Any 	=			output.rgb, output.depth
								__lowerCamelCase    :    List[str] 	=			rgb_slice_a[0, -3:, -3:, -1]
								__lowerCamelCase    :    List[Any] 	=			depth_slice_a[0, -3:, -1]

								assert np.abs(rgb_slice_a.flatten() - rgb_slice_a.flatten()).max() < 1E-4
								assert np.abs(depth_slice_a.flatten() - depth_slice_a.flatten()).max() < 1E-4


							def    lowerCAmelCase					(		self		:      Optional[int]):
								__lowerCamelCase    :    Union[str, Any] 	=			'cpu'  # ensure determinism for the device-dependent torch.Generator
								__lowerCamelCase    :    str 	=			self.get_dummy_components()
								__lowerCamelCase    :    List[Any] 	=			PNDMScheduler(skip_prk_steps=SCREAMING_SNAKE_CASE__)
								__lowerCamelCase    :    Union[str, Any] 	=			StableDiffusionLDMaDPipeline(**SCREAMING_SNAKE_CASE__)
								__lowerCamelCase    :    Optional[Any] 	=			ldmad_pipe.to(SCREAMING_SNAKE_CASE__)
								ldmad_pipe.set_progress_bar_config(disable=SCREAMING_SNAKE_CASE__)

								__lowerCamelCase    :    Tuple 	=			self.get_dummy_inputs(SCREAMING_SNAKE_CASE__)
								__lowerCamelCase    :    Dict 	=			'french fries'
								__lowerCamelCase    :    Optional[int] 	=			ldmad_pipe(**SCREAMING_SNAKE_CASE__       ,negative_prompt=SCREAMING_SNAKE_CASE__)

								__lowerCamelCase	,			__lowerCamelCase    :    Any 	=			output.rgb, output.depth
								__lowerCamelCase    :    Dict 	=			rgb[0, -3:, -3:, -1]
								__lowerCamelCase    :    List[str] 	=			depth[0, -3:, -1]

								assert rgb.shape == (1, 6_4, 6_4, 3)
								assert depth.shape == (1, 6_4, 6_4)

								__lowerCamelCase    :    List[Any] 	=			np.array(
								    [0.37044, 0.71811503, 0.7223251, 0.48603675, 0.5638391, 0.6364948, 0.42833704, 0.4901315, 0.47926217])
								__lowerCamelCase    :    List[str] 	=			np.array([107.84738, 84.62802, 89.962135])
								assert np.abs(rgb_slice.flatten() - expected_slice_rgb).max() < 1E-2
								assert np.abs(depth_slice.flatten() - expected_slice_depth).max() < 1E-2






@slow
@require_torch_gpu
class 	A_		(	unittest.TestCase    ):
							def    lowerCAmelCase					(		self		:      str):
								super().tearDown()
								gc.collect()
								torch.cuda.empty_cache()
							def    lowerCAmelCase					(		self		:      List[Any]       ,SCREAMING_SNAKE_CASE__		:      Optional[Any]       ,SCREAMING_SNAKE_CASE__		:      List[str]="cpu"       ,SCREAMING_SNAKE_CASE__		:      Dict=torch.floataa       ,SCREAMING_SNAKE_CASE__		:      Optional[Any]=0):
								__lowerCamelCase    :    Optional[Any] 	=			torch.Generator(device=SCREAMING_SNAKE_CASE__).manual_seed(SCREAMING_SNAKE_CASE__)
								__lowerCamelCase    :    Optional[int] 	=			np.random.RandomState(SCREAMING_SNAKE_CASE__).standard_normal((1, 4, 6_4, 6_4))
								__lowerCamelCase    :    Tuple 	=			torch.from_numpy(SCREAMING_SNAKE_CASE__).to(device=SCREAMING_SNAKE_CASE__       ,dtype=SCREAMING_SNAKE_CASE__)
								__lowerCamelCase    :    Tuple 	=			{
								    'prompt': 'a photograph of an astronaut riding a horse',
								    'latents': latents,
								    'generator': generator,
								    'num_inference_steps': 3,
								    'guidance_scale': 7.5,
								    'output_type': 'numpy',
								}
								return inputs


							def    lowerCAmelCase					(		self		:      str):
								__lowerCamelCase    :    str 	=			StableDiffusionLDMaDPipeline.from_pretrained('Intel/ldm3d')
								__lowerCamelCase    :    Optional[Any] 	=			ldmad_pipe.to(SCREAMING_SNAKE_CASE__)
								ldmad_pipe.set_progress_bar_config(disable=SCREAMING_SNAKE_CASE__)

								__lowerCamelCase    :    Optional[int] 	=			self.get_inputs(SCREAMING_SNAKE_CASE__)
								__lowerCamelCase    :    Optional[int] 	=			ldmad_pipe(**SCREAMING_SNAKE_CASE__)
								__lowerCamelCase	,			__lowerCamelCase    :    Dict 	=			output.rgb, output.depth
								__lowerCamelCase    :    List[Any] 	=			rgb[0, -3:, -3:, -1].flatten()
								__lowerCamelCase    :    int 	=			rgb[0, -3:, -1].flatten()

								assert rgb.shape == (1, 5_1_2, 5_1_2, 3)
								assert depth.shape == (1, 5_1_2, 5_1_2)

								__lowerCamelCase    :    List[Any] 	=			np.array(
								    [0.53805465, 0.56707305, 0.5486515, 0.57012236, 0.5814511, 0.56253487, 0.54843014, 0.55092263, 0.6459706])
								__lowerCamelCase    :    List[str] 	=			np.array(
								    [0.9263781, 0.6678672, 0.5486515, 0.92202145, 0.67831135, 0.56253487, 0.9241694, 0.7551478, 0.6459706])
								assert np.abs(rgb_slice - expected_slice_rgb).max() < 3E-3
								assert np.abs(depth_slice - expected_slice_depth).max() < 3E-3






@nightly
@require_torch_gpu
class 	A_		(	unittest.TestCase    ):
							def    lowerCAmelCase					(		self		:      List[Any]):
								super().tearDown()
								gc.collect()
								torch.cuda.empty_cache()
							def    lowerCAmelCase					(		self		:      Any       ,SCREAMING_SNAKE_CASE__		:      Any       ,SCREAMING_SNAKE_CASE__		:      Optional[Any]="cpu"       ,SCREAMING_SNAKE_CASE__		:      List[str]=torch.floataa       ,SCREAMING_SNAKE_CASE__		:      Tuple=0):
								__lowerCamelCase    :    List[str] 	=			torch.Generator(device=SCREAMING_SNAKE_CASE__).manual_seed(SCREAMING_SNAKE_CASE__)
								__lowerCamelCase    :    Optional[Any] 	=			np.random.RandomState(SCREAMING_SNAKE_CASE__).standard_normal((1, 4, 6_4, 6_4))
								__lowerCamelCase    :    Dict 	=			torch.from_numpy(SCREAMING_SNAKE_CASE__).to(device=SCREAMING_SNAKE_CASE__       ,dtype=SCREAMING_SNAKE_CASE__)
								__lowerCamelCase    :    List[str] 	=			{
								    'prompt': 'a photograph of an astronaut riding a horse',
								    'latents': latents,
								    'generator': generator,
								    'num_inference_steps': 5_0,
								    'guidance_scale': 7.5,
								    'output_type': 'numpy',
								}
								return inputs
							def    lowerCAmelCase					(		self		:      List[Any]):
								__lowerCamelCase    :    Tuple 	=			StableDiffusionLDMaDPipeline.from_pretrained('Intel/ldm3d').to(SCREAMING_SNAKE_CASE__)
								ldmad_pipe.set_progress_bar_config(disable=SCREAMING_SNAKE_CASE__)

								__lowerCamelCase    :    Any 	=			self.get_inputs(SCREAMING_SNAKE_CASE__)
								__lowerCamelCase    :    Optional[Any] 	=			ldmad_pipe(**SCREAMING_SNAKE_CASE__)
								__lowerCamelCase	,			__lowerCamelCase    :    Union[str, Any] 	=			output.rgb, output.depth

								__lowerCamelCase    :    Union[str, Any] 	=			0.495586
								__lowerCamelCase    :    Any 	=			0.33795515
								__lowerCamelCase    :    Dict 	=			112.48518
								__lowerCamelCase    :    Optional[int] 	=			98.489746
								assert np.abs(expected_rgb_mean - rgb.mean()) < 1E-3
								assert np.abs(expected_rgb_std - rgb.std()) < 1E-3
								assert np.abs(expected_depth_mean - depth.mean()) < 1E-3
								assert np.abs(expected_depth_std - depth.std()) < 1E-3


							def    lowerCAmelCase					(		self		:      int):
								__lowerCamelCase    :    Any 	=			StableDiffusionLDMaDPipeline.from_pretrained('Intel/ldm3d-4c').to(SCREAMING_SNAKE_CASE__)
								ldmad_pipe.set_progress_bar_config(disable=SCREAMING_SNAKE_CASE__)

								__lowerCamelCase    :    Tuple 	=			self.get_inputs(SCREAMING_SNAKE_CASE__)
								__lowerCamelCase    :    str 	=			ldmad_pipe(**SCREAMING_SNAKE_CASE__)
								__lowerCamelCase	,			__lowerCamelCase    :    str 	=			output.rgb, output.depth

								__lowerCamelCase    :    Union[str, Any] 	=			0.4194127
								__lowerCamelCase    :    str 	=			0.35375586
								__lowerCamelCase    :    Tuple 	=			0.5638502
								__lowerCamelCase    :    List[Any] 	=			0.34686103

								assert rgb.shape == (1, 5_1_2, 5_1_2, 3)
								assert depth.shape == (1, 5_1_2, 5_1_2, 1)
								assert np.abs(expected_rgb_mean - rgb.mean()) < 1E-3
								assert np.abs(expected_rgb_std - rgb.std()) < 1E-3
								assert np.abs(expected_depth_mean - depth.mean()) < 1E-3
								assert np.abs(expected_depth_std - depth.std()) < 1E-3







import os
import unittest

from huggingface_hub.utils import are_progress_bars_disabled

import transformers.models.bart.tokenization_bart
from transformers import logging
from transformers.testing_utils import CaptureLogger, mockenv, mockenv_context
from transformers.utils.logging import disable_progress_bar, enable_progress_bar






class 	A_		(	unittest.TestCase    ):
							def    lowerCAmelCase					(		self		:      Optional[int]):
								__lowerCamelCase    :    List[Any] 	=			logging.get_logger()

								# the current default level is logging.WARNING
								__lowerCamelCase    :    Dict 	=			logging.get_verbosity()

								logging.set_verbosity_error()
								self.assertEqual(logger.getEffectiveLevel()       ,logging.get_verbosity())

								logging.set_verbosity_warning()
								self.assertEqual(logger.getEffectiveLevel()       ,logging.get_verbosity())

								logging.set_verbosity_info()
								self.assertEqual(logger.getEffectiveLevel()       ,logging.get_verbosity())

								logging.set_verbosity_debug()
								self.assertEqual(logger.getEffectiveLevel()       ,logging.get_verbosity())

								# restore to the original level
								logging.set_verbosity(SCREAMING_SNAKE_CASE__)
							def    lowerCAmelCase					(		self		:      Optional[Any]):
								__lowerCamelCase    :    Optional[int] 	=			logging.get_verbosity()

								__lowerCamelCase    :    str 	=			logging.get_logger('transformers.models.bart.tokenization_bart')
								__lowerCamelCase    :    Tuple 	=			'Testing 1, 2, 3'

								# should be able to log warnings (if default settings weren't overridden by `pytest --log-level-all`)
								if level_origin <= logging.WARNING:
									with CaptureLogger(SCREAMING_SNAKE_CASE__) as cl:
										logger.warning(SCREAMING_SNAKE_CASE__)
									self.assertEqual(cl.out       ,msg + '\n')

								# this is setting the level for all of `transformers.*` loggers
								logging.set_verbosity_error()

								# should not be able to log warnings
								with CaptureLogger(SCREAMING_SNAKE_CASE__) as cl:
									logger.warning(SCREAMING_SNAKE_CASE__)
								self.assertEqual(cl.out       ,'')

								# should be able to log warnings again
								logging.set_verbosity_warning()
								with CaptureLogger(SCREAMING_SNAKE_CASE__) as cl:
									logger.warning(SCREAMING_SNAKE_CASE__)
								self.assertEqual(cl.out       ,msg + '\n')

								# restore to the original level
								logging.set_verbosity(SCREAMING_SNAKE_CASE__)
							@mockenv(TRANSFORMERS_VERBOSITY='error')
							def    lowerCAmelCase					(		self		:      Tuple):
								# reset for the env var to take effect, next time some logger call is made
								transformers.utils.logging._reset_library_root_logger()
								# this action activates the env var
								__lowerCamelCase    :    int 	=			logging.get_logger('transformers.models.bart.tokenization_bart')

								__lowerCamelCase    :    int 	=			os.getenv('TRANSFORMERS_VERBOSITY'       ,SCREAMING_SNAKE_CASE__)
								__lowerCamelCase    :    Optional[Any] 	=			logging.log_levels[env_level_str]

								__lowerCamelCase    :    Tuple 	=			logging.get_verbosity()
								self.assertEqual(
								    SCREAMING_SNAKE_CASE__       ,SCREAMING_SNAKE_CASE__       ,F"TRANSFORMERS_VERBOSITY={env_level_str}/{env_level}, but internal verbosity is {current_level}"       ,)

								# restore to the original level
								__lowerCamelCase    :    List[str] 	=			''
								transformers.utils.logging._reset_library_root_logger()
							@mockenv(TRANSFORMERS_VERBOSITY='super-error')
							def    lowerCAmelCase					(		self		:      List[Any]):
								# reset for the env var to take effect, next time some logger call is made
								transformers.utils.logging._reset_library_root_logger()
								__lowerCamelCase    :    List[str] 	=			logging.logging.getLogger()
								with CaptureLogger(SCREAMING_SNAKE_CASE__) as cl:
									# this action activates the env var
									logging.get_logger('transformers.models.bart.tokenization_bart')
								self.assertIn('Unknown option TRANSFORMERS_VERBOSITY=super-error'       ,cl.out)

								# no need to restore as nothing was changed


							def    lowerCAmelCase					(		self		:      Any):
								# testing `logger.warning_advice()`
								transformers.utils.logging._reset_library_root_logger()

								__lowerCamelCase    :    Tuple 	=			logging.get_logger('transformers.models.bart.tokenization_bart')
								__lowerCamelCase    :    Optional[int] 	=			'Testing 1, 2, 3'

								with mockenv_context(TRANSFORMERS_NO_ADVISORY_WARNINGS='1'):
									# nothing should be logged as env var disables this method
									with CaptureLogger(SCREAMING_SNAKE_CASE__) as cl:
										logger.warning_advice(SCREAMING_SNAKE_CASE__)
									self.assertEqual(cl.out       ,'')

								with mockenv_context(TRANSFORMERS_NO_ADVISORY_WARNINGS=''):
									# should log normally as TRANSFORMERS_NO_ADVISORY_WARNINGS is unset
									with CaptureLogger(SCREAMING_SNAKE_CASE__) as cl:
										logger.warning_advice(SCREAMING_SNAKE_CASE__)
									self.assertEqual(cl.out       ,msg + '\n')






def        SCREAMING_SNAKE_CASE__	(  )  ->					Any:
	disable_progress_bar()
	assert are_progress_bars_disabled()

	enable_progress_bar()
	assert not are_progress_bars_disabled()




