


"""simple docstring"""






import inspect
import unittest
from math import floor

from transformers import CvtConfig
from transformers.file_utils import cached_property, is_torch_available, is_vision_available
from transformers.testing_utils import require_torch, require_vision, slow, torch_device

from ...test_configuration_common import ConfigTester
from ...test_modeling_common import ModelTesterMixin, floats_tensor, ids_tensor
from ...test_pipeline_mixin import PipelineTesterMixin


if is_torch_available():
					import torch

					from transformers import CvtForImageClassification, CvtModel
					from transformers.models.cvt.modeling_cvt import CVT_PRETRAINED_MODEL_ARCHIVE_LIST


if is_vision_available():
					from PIL import Image

					from transformers import AutoImageProcessor






class      A(  lowerCamelCase__		):

		"""simple docstring"""





		def   _UpperCamelCase( self   )      ->	Any:

					"""simple docstring"""



					_UpperCamelCase					:Tuple					     =	self.config_class(**self.inputs_dict   )
					self.parent.assertTrue(hasattr(SCREAMING_SNAKE_CASE__					,				'''embed_dim'''   )   )
					self.parent.assertTrue(hasattr(SCREAMING_SNAKE_CASE__					,				'''num_heads'''   )   )






class      A:

		"""simple docstring"""





		def __init__( self					,				SCREAMING_SNAKE_CASE__					,				SCREAMING_SNAKE_CASE__=13					,				SCREAMING_SNAKE_CASE__=64					,				SCREAMING_SNAKE_CASE__=3					,				SCREAMING_SNAKE_CASE__=[16, 48, 96]					,				SCREAMING_SNAKE_CASE__=[1, 3, 6]					,				SCREAMING_SNAKE_CASE__=[1, 2, 10]					,				SCREAMING_SNAKE_CASE__=[7, 3, 3]					,				SCREAMING_SNAKE_CASE__=[4, 2, 2]					,				SCREAMING_SNAKE_CASE__=[2, 1, 1]					,				SCREAMING_SNAKE_CASE__=[2, 2, 2]					,				SCREAMING_SNAKE_CASE__=[False, False, True]					,				SCREAMING_SNAKE_CASE__=[0.0, 0.0, 0.0]					,				SCREAMING_SNAKE_CASE__=0.0_2					,				SCREAMING_SNAKE_CASE__=1E-12					,				SCREAMING_SNAKE_CASE__=True					,				SCREAMING_SNAKE_CASE__=True					,				SCREAMING_SNAKE_CASE__=2					,				)      ->	str:

					"""simple docstring"""



					_UpperCamelCase					:str					     =	parent
					_UpperCamelCase					:List[str]					     =	batch_size
					_UpperCamelCase					:Optional[Any]					     =	image_size
					_UpperCamelCase					:Union[str, Any]					     =	patch_sizes
					_UpperCamelCase					:Any					     =	patch_stride
					_UpperCamelCase					:Any					     =	patch_padding
					_UpperCamelCase					:List[str]					     =	is_training
					_UpperCamelCase					:Optional[Any]					     =	use_labels
					_UpperCamelCase					:int					     =	num_labels
					_UpperCamelCase					:Union[str, Any]					     =	num_channels
					_UpperCamelCase					:Any					     =	embed_dim
					_UpperCamelCase					:str					     =	num_heads
					_UpperCamelCase					:Dict					     =	stride_kv
					_UpperCamelCase					:Tuple					     =	depth
					_UpperCamelCase					:Any					     =	cls_token
					_UpperCamelCase					:List[Any]					     =	attention_drop_rate
					_UpperCamelCase					:str					     =	initializer_range
					_UpperCamelCase					:Any					     =	layer_norm_eps
		def   _UpperCamelCase( self   )      ->	str:

					"""simple docstring"""



					_UpperCamelCase					:Any					     =	floats_tensor([self.batch_size, self.num_channels, self.image_size, self.image_size]   )

					_UpperCamelCase					:str					     =	None
					if self.use_labels:
								_UpperCamelCase					:int					     =	ids_tensor([self.batch_size]					,				self.num_labels   )

					_UpperCamelCase					:Union[str, Any]					     =	self.get_config()
					return config, pixel_values, labels
		def   _UpperCamelCase( self   )      ->	int:

					"""simple docstring"""



					return CvtConfig(
					    image_size=self.image_size					,				num_labels=self.num_labels					,				num_channels=self.num_channels					,				embed_dim=self.embed_dim					,				num_heads=self.num_heads					,				patch_sizes=self.patch_sizes					,				patch_padding=self.patch_padding					,				patch_stride=self.patch_stride					,				stride_kv=self.stride_kv					,				depth=self.depth					,				cls_token=self.cls_token					,				attention_drop_rate=self.attention_drop_rate					,				initializer_range=self.initializer_range					,				)
		def   _UpperCamelCase( self					,				SCREAMING_SNAKE_CASE__					,				SCREAMING_SNAKE_CASE__					,				SCREAMING_SNAKE_CASE__   )      ->	Union[str, Any]:

					"""simple docstring"""



					_UpperCamelCase					:Union[str, Any]					     =	CvtModel(config=SCREAMING_SNAKE_CASE__   )
					model.to(SCREAMING_SNAKE_CASE__   )
					model.eval()
					_UpperCamelCase					:str					     =	model(SCREAMING_SNAKE_CASE__   )
					_UpperCamelCase					:str					     =	(self.image_size, self.image_size)
					_UpperCamelCase     ,      _UpperCamelCase					:List[str]					     =	image_size[0], image_size[1]
					for i in range(len(self.depth   )   ):
								_UpperCamelCase					:str					     =	floor(((height + 2 * self.patch_padding[i] - self.patch_sizes[i]) / self.patch_stride[i]) + 1   )
								_UpperCamelCase					:Tuple					     =	floor(((width + 2 * self.patch_padding[i] - self.patch_sizes[i]) / self.patch_stride[i]) + 1   )
					self.parent.assertEqual(result.last_hidden_state.shape					,				(self.batch_size, self.embed_dim[-1], height, width)   )
		def   _UpperCamelCase( self					,				SCREAMING_SNAKE_CASE__					,				SCREAMING_SNAKE_CASE__					,				SCREAMING_SNAKE_CASE__   )      ->	str:

					"""simple docstring"""



					_UpperCamelCase					:Optional[int]					     =	self.num_labels
					_UpperCamelCase					:Dict					     =	CvtForImageClassification(SCREAMING_SNAKE_CASE__   )
					model.to(SCREAMING_SNAKE_CASE__   )
					model.eval()
					_UpperCamelCase					:List[str]					     =	model(SCREAMING_SNAKE_CASE__					,				labels=SCREAMING_SNAKE_CASE__   )
					self.parent.assertEqual(result.logits.shape					,				(self.batch_size, self.num_labels)   )





		def   _UpperCamelCase( self   )      ->	int:

					"""simple docstring"""



					_UpperCamelCase					:Tuple					     =	self.prepare_config_and_inputs()
					_UpperCamelCase     ,      _UpperCamelCase     ,      _UpperCamelCase					:Any					     =	config_and_inputs
					_UpperCamelCase					:List[str]					     =	{'''pixel_values''': pixel_values}
					return config, inputs_dict






@require_torch
class      A(  lowerCamelCase__				,							lowerCamelCase__				,							unittest.TestCase		):

		"""simple docstring"""





		A    =							(CvtModel, CvtForImageClassification) if is_torch_available() else ()
		A    =							(
		    {"feature-extraction": CvtModel, "image-classification": CvtForImageClassification}
		    if is_torch_available()
		    else {}
		)

		A    =							False
		A    =							False
		A    =							False
		A    =							False
		A    =							False
		def   _UpperCamelCase( self   )      ->	Union[str, Any]:

					"""simple docstring"""



					_UpperCamelCase					:List[str]					     =	CvtModelTester(self   )
					_UpperCamelCase					:Any					     =	ConfigTester(self					,				config_class=SCREAMING_SNAKE_CASE__					,				has_text_modality=SCREAMING_SNAKE_CASE__					,				hidden_size=37   )
		def   _UpperCamelCase( self   )      ->	Optional[Any]:

					"""simple docstring"""



					self.create_and_test_config_common_properties()
					self.config_tester.create_and_test_config_to_json_string()
					self.config_tester.create_and_test_config_to_json_file()
					self.config_tester.create_and_test_config_from_and_save_pretrained()
					self.config_tester.create_and_test_config_with_num_labels()
					self.config_tester.check_config_can_be_init_without_params()
					self.config_tester.check_config_arguments_init()
		def   _UpperCamelCase( self   )      ->	Union[str, Any]:

					"""simple docstring"""



					return
		@unittest.skip(reason='''Cvt does not output attentions'''   )
		def   _UpperCamelCase( self   )      ->	int:

					"""simple docstring"""



					pass
		@unittest.skip(reason='''Cvt does not use inputs_embeds'''   )
		def   _UpperCamelCase( self   )      ->	List[str]:

					"""simple docstring"""



					pass
		@unittest.skip(reason='''Cvt does not support input and output embeddings'''   )
		def   _UpperCamelCase( self   )      ->	Union[str, Any]:

					"""simple docstring"""



					pass
		def   _UpperCamelCase( self   )      ->	Any:

					"""simple docstring"""



					_UpperCamelCase     ,      _UpperCamelCase					:Optional[int]					     =	self.model_tester.prepare_config_and_inputs_for_common()

					for model_class in self.all_model_classes:
								_UpperCamelCase					:Dict					     =	model_class(SCREAMING_SNAKE_CASE__   )
								_UpperCamelCase					:List[str]					     =	inspect.signature(model.forward   )
								# signature.parameters is an OrderedDict => so arg_names order is deterministic
								_UpperCamelCase					:List[str]					     =	[*signature.parameters.keys()]

								_UpperCamelCase					:List[Any]					     =	['''pixel_values''']
								self.assertListEqual(arg_names[:1]					,				SCREAMING_SNAKE_CASE__   )
		def   _UpperCamelCase( self   )      ->	str:

					"""simple docstring"""



					_UpperCamelCase					:Union[str, Any]					     =	self.model_tester.prepare_config_and_inputs()
					self.model_tester.create_and_check_model(*SCREAMING_SNAKE_CASE__   )
		def   _UpperCamelCase( self   )      ->	Tuple:

					"""simple docstring"""



					def check_hidden_states_output(SCREAMING_SNAKE_CASE__					,				SCREAMING_SNAKE_CASE__					,				SCREAMING_SNAKE_CASE__   ):
								_UpperCamelCase					:Optional[Any]					     =	model_class(SCREAMING_SNAKE_CASE__   )
								model.to(SCREAMING_SNAKE_CASE__   )
								model.eval()

								with torch.no_grad():
											_UpperCamelCase					:Optional[int]					     =	model(**self._prepare_for_class(SCREAMING_SNAKE_CASE__					,				SCREAMING_SNAKE_CASE__   )   )

								_UpperCamelCase					:Optional[Any]					     =	outputs.hidden_states

								_UpperCamelCase					:Tuple					     =	len(self.model_tester.depth   )
								self.assertEqual(len(SCREAMING_SNAKE_CASE__   )					,				SCREAMING_SNAKE_CASE__   )

								# verify the first hidden states (first block)
								self.assertListEqual(
								    list(hidden_states[0].shape[-3:]   )					,				[
								        self.model_tester.embed_dim[0],
								        self.model_tester.image_size // 4,
								        self.model_tester.image_size // 4,
								    ]					,				)

					_UpperCamelCase     ,      _UpperCamelCase					:Tuple					     =	self.model_tester.prepare_config_and_inputs_for_common()

					for model_class in self.all_model_classes:
								_UpperCamelCase					:Any					     =	True
								check_hidden_states_output(SCREAMING_SNAKE_CASE__					,				SCREAMING_SNAKE_CASE__					,				SCREAMING_SNAKE_CASE__   )

								# check that output_hidden_states also work using config
								del inputs_dict["output_hidden_states"]
								_UpperCamelCase					:List[str]					     =	True

								check_hidden_states_output(SCREAMING_SNAKE_CASE__					,				SCREAMING_SNAKE_CASE__					,				SCREAMING_SNAKE_CASE__   )
		def   _UpperCamelCase( self   )      ->	str:

					"""simple docstring"""



					_UpperCamelCase					:str					     =	self.model_tester.prepare_config_and_inputs()
					self.model_tester.create_and_check_for_image_classification(*SCREAMING_SNAKE_CASE__   )
		@unittest.skip('''Will be fixed soon by reducing the size of the model used for common tests.'''   )
		def   _UpperCamelCase( self   )      ->	Dict:

					"""simple docstring"""



					pass





		@slow
		def   _UpperCamelCase( self   )      ->	str:

					"""simple docstring"""



					for model_name in CVT_PRETRAINED_MODEL_ARCHIVE_LIST[:1]:
								_UpperCamelCase					:List[str]					     =	CvtModel.from_pretrained(SCREAMING_SNAKE_CASE__   )
								self.assertIsNotNone(SCREAMING_SNAKE_CASE__   )





def 				A_       ( )					->  List[str]:
			_UpperCamelCase					:Any					     =	Image.open('''./tests/fixtures/tests_samples/COCO/000000039769.png'''		)
			return image






@require_torch
@require_vision
class      A(  unittest.TestCase		):

		"""simple docstring"""





		@cached_property
		def   _UpperCamelCase( self   )      ->	int:

					"""simple docstring"""



					return AutoImageProcessor.from_pretrained(CVT_PRETRAINED_MODEL_ARCHIVE_LIST[0]   )





		@slow
		def   _UpperCamelCase( self   )      ->	List[Any]:

					"""simple docstring"""



					_UpperCamelCase					:int					     =	CvtForImageClassification.from_pretrained(CVT_PRETRAINED_MODEL_ARCHIVE_LIST[0]   ).to(SCREAMING_SNAKE_CASE__   )

					_UpperCamelCase					:List[str]					     =	self.default_image_processor
					_UpperCamelCase					:List[str]					     =	prepare_img()
					_UpperCamelCase					:List[str]					     =	image_processor(images=SCREAMING_SNAKE_CASE__					,				return_tensors='''pt'''   ).to(SCREAMING_SNAKE_CASE__   )

					# forward pass
					with torch.no_grad():
								_UpperCamelCase					:List[str]					     =	model(**SCREAMING_SNAKE_CASE__   )

					# verify the logits
					_UpperCamelCase					:Optional[Any]					     =	torch.Size((1, 10_00)   )
					self.assertEqual(outputs.logits.shape					,				SCREAMING_SNAKE_CASE__   )

					_UpperCamelCase					:List[Any]					     =	torch.tensor([0.9_2_8_5, 0.9_0_1_5, -0.3_1_5_0]   ).to(SCREAMING_SNAKE_CASE__   )

					self.assertTrue(torch.allclose(outputs.logits[0, :3]					,				SCREAMING_SNAKE_CASE__					,				atol=1E-4   )   )





"""simple docstring"""






import unittest

import numpy as np
import torch

from diffusers import KarrasVePipeline, KarrasVeScheduler, UNetaDModel
from diffusers.utils.testing_utils import enable_full_determinism, require_torch, slow, torch_device


enable_full_determinism()






class      A(  unittest.TestCase		):

		"""simple docstring"""





		@property
		def   _UpperCamelCase( self   )      ->	Union[str, Any]:

					"""simple docstring"""



					torch.manual_seed(0   )
					_UpperCamelCase					:str					     =	UNetaDModel(
					    block_out_channels=(32, 64)					,				layers_per_block=2					,				sample_size=32					,				in_channels=3					,				out_channels=3					,				down_block_types=('''DownBlock2D''', '''AttnDownBlock2D''')					,				up_block_types=('''AttnUpBlock2D''', '''UpBlock2D''')					,				)
					return model





		def   _UpperCamelCase( self   )      ->	str:

					"""simple docstring"""



					_UpperCamelCase					:Dict					     =	self.dummy_uncond_unet
					_UpperCamelCase					:List[Any]					     =	KarrasVeScheduler()

					_UpperCamelCase					:Optional[Any]					     =	KarrasVePipeline(unet=SCREAMING_SNAKE_CASE__					,				scheduler=SCREAMING_SNAKE_CASE__   )
					pipe.to(SCREAMING_SNAKE_CASE__   )
					pipe.set_progress_bar_config(disable=SCREAMING_SNAKE_CASE__   )

					_UpperCamelCase					:Dict					     =	torch.manual_seed(0   )
					_UpperCamelCase					:List[Any]					     =	pipe(num_inference_steps=2					,				generator=SCREAMING_SNAKE_CASE__					,				output_type='''numpy'''   ).images

					_UpperCamelCase					:List[Any]					     =	torch.manual_seed(0   )
					_UpperCamelCase					:Dict					     =	pipe(num_inference_steps=2					,				generator=SCREAMING_SNAKE_CASE__					,				output_type='''numpy'''					,				return_dict=SCREAMING_SNAKE_CASE__   )[0]

					_UpperCamelCase					:Dict					     =	image[0, -3:, -3:, -1]
					_UpperCamelCase					:List[Any]					     =	image_from_tuple[0, -3:, -3:, -1]

					assert image.shape == (1, 32, 32, 3)
					_UpperCamelCase					:List[Any]					     =	np.array([0.0, 1.0, 0.0, 0.0, 0.0, 1.0, 0.0, 0.0, 0.0]   )

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






@slow
@require_torch
class      A(  unittest.TestCase		):

		"""simple docstring"""





		def   _UpperCamelCase( self   )      ->	Union[str, Any]:

					"""simple docstring"""



					_UpperCamelCase					:List[Any]					     =	'''google/ncsnpp-celebahq-256'''
					_UpperCamelCase					:Any					     =	UNetaDModel.from_pretrained(SCREAMING_SNAKE_CASE__   )
					_UpperCamelCase					:Optional[int]					     =	KarrasVeScheduler()

					_UpperCamelCase					:Optional[int]					     =	KarrasVePipeline(unet=SCREAMING_SNAKE_CASE__					,				scheduler=SCREAMING_SNAKE_CASE__   )
					pipe.to(SCREAMING_SNAKE_CASE__   )
					pipe.set_progress_bar_config(disable=SCREAMING_SNAKE_CASE__   )

					_UpperCamelCase					:List[str]					     =	torch.manual_seed(0   )
					_UpperCamelCase					:List[Any]					     =	pipe(num_inference_steps=20					,				generator=SCREAMING_SNAKE_CASE__					,				output_type='''numpy'''   ).images

					_UpperCamelCase					:Dict					     =	image[0, -3:, -3:, -1]
					assert image.shape == (1, 2_56, 2_56, 3)
					_UpperCamelCase					:Any					     =	np.array([0.5_7_8, 0.5_8_1_1, 0.5_9_2_4, 0.5_8_0_9, 0.5_8_7, 0.5_8_8_6, 0.5_8_6_1, 0.5_8_0_2, 0.5_8_6]   )

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

