




import inspect
import unittest

from transformers import YolosConfig
from transformers.testing_utils import require_torch, require_vision, slow, torch_device
from transformers.utils import cached_property, is_torch_available, is_vision_available

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


if is_torch_available():
				import torch
				from torch import nn

				from transformers import YolosForObjectDetection, YolosModel
				from transformers.models.yolos.modeling_yolos import YOLOS_PRETRAINED_MODEL_ARCHIVE_LIST


if is_vision_available():
				from PIL import Image

				from transformers import AutoImageProcessor



class       a_       :





	def __init__(							self      ,     SCREAMING_SNAKE_CASE      ,     SCREAMING_SNAKE_CASE=13      ,     SCREAMING_SNAKE_CASE=[30, 30]      ,     SCREAMING_SNAKE_CASE=2      ,     SCREAMING_SNAKE_CASE=3      ,     SCREAMING_SNAKE_CASE=True      ,     SCREAMING_SNAKE_CASE=True      ,     SCREAMING_SNAKE_CASE=32      ,     SCREAMING_SNAKE_CASE=5      ,     SCREAMING_SNAKE_CASE=4      ,     SCREAMING_SNAKE_CASE=37      ,     SCREAMING_SNAKE_CASE="gelu"      ,     SCREAMING_SNAKE_CASE=0.1      ,     SCREAMING_SNAKE_CASE=0.1      ,     SCREAMING_SNAKE_CASE=10      ,     SCREAMING_SNAKE_CASE=0.0_2      ,     SCREAMING_SNAKE_CASE=3      ,     SCREAMING_SNAKE_CASE=None      ,     SCREAMING_SNAKE_CASE=8      ,     SCREAMING_SNAKE_CASE=10      ,     )  ->					Optional[int]:




				"""simple docstring"""



				SCREAMING_SNAKE_CASE_								=						parent
				SCREAMING_SNAKE_CASE_								=						batch_size
				SCREAMING_SNAKE_CASE_								=						image_size
				SCREAMING_SNAKE_CASE_								=						patch_size
				SCREAMING_SNAKE_CASE_								=						num_channels
				SCREAMING_SNAKE_CASE_								=						is_training
				SCREAMING_SNAKE_CASE_								=						use_labels
				SCREAMING_SNAKE_CASE_								=						hidden_size
				SCREAMING_SNAKE_CASE_								=						num_hidden_layers
				SCREAMING_SNAKE_CASE_								=						num_attention_heads
				SCREAMING_SNAKE_CASE_								=						intermediate_size
				SCREAMING_SNAKE_CASE_								=						hidden_act
				SCREAMING_SNAKE_CASE_								=						hidden_dropout_prob
				SCREAMING_SNAKE_CASE_								=						attention_probs_dropout_prob
				SCREAMING_SNAKE_CASE_								=						type_sequence_label_size
				SCREAMING_SNAKE_CASE_								=						initializer_range
				SCREAMING_SNAKE_CASE_								=						num_labels
				SCREAMING_SNAKE_CASE_								=						scope
				SCREAMING_SNAKE_CASE_								=						n_targets
				SCREAMING_SNAKE_CASE_								=						num_detection_tokens
				# we set the expected sequence length (which is used in several tests)
				# expected sequence length = num_patches + 1 (we add 1 for the [CLS] token) + num_detection_tokens
				SCREAMING_SNAKE_CASE_								=						(image_size[1] // patch_size) * (image_size[0] // patch_size)
				SCREAMING_SNAKE_CASE_								=						num_patches + 1 + self.num_detection_tokens





	def 						A_(							self      )  ->					List[str]:




				"""simple docstring"""



				SCREAMING_SNAKE_CASE_								=						floats_tensor([self.batch_size, self.num_channels, self.image_size[0], self.image_size[1]]      )

				SCREAMING_SNAKE_CASE_								=						None
				if self.use_labels:
							# labels is a list of Dict (each Dict being the labels for a given example in the batch)
							SCREAMING_SNAKE_CASE_								=						[]
							for i in range(self.batch_size      ):
										SCREAMING_SNAKE_CASE_								=						{}
										SCREAMING_SNAKE_CASE_								=						torch.randint(
										    high=self.num_labels      ,     size=(self.n_targets,)      ,     device=SCREAMING_SNAKE_CASE      )
										SCREAMING_SNAKE_CASE_								=						torch.rand(self.n_targets      ,     4      ,     device=SCREAMING_SNAKE_CASE      )
										labels.append(SCREAMING_SNAKE_CASE      )

				SCREAMING_SNAKE_CASE_								=						self.get_config()

				return config, pixel_values, labels





	def 						A_(							self      )  ->					Dict:




				"""simple docstring"""



				return YolosConfig(
				    image_size=self.image_size      ,     patch_size=self.patch_size      ,     num_channels=self.num_channels      ,     hidden_size=self.hidden_size      ,     num_hidden_layers=self.num_hidden_layers      ,     num_attention_heads=self.num_attention_heads      ,     intermediate_size=self.intermediate_size      ,     hidden_act=self.hidden_act      ,     hidden_dropout_prob=self.hidden_dropout_prob      ,     attention_probs_dropout_prob=self.attention_probs_dropout_prob      ,     is_decoder=SCREAMING_SNAKE_CASE      ,     initializer_range=self.initializer_range      ,     num_detection_tokens=self.num_detection_tokens      ,     num_labels=self.num_labels      ,     )





	def 						A_(							self      ,     SCREAMING_SNAKE_CASE      ,     SCREAMING_SNAKE_CASE      ,     SCREAMING_SNAKE_CASE      )  ->					Any:




				"""simple docstring"""



				SCREAMING_SNAKE_CASE_								=						YolosModel(config=SCREAMING_SNAKE_CASE      )
				model.to(SCREAMING_SNAKE_CASE      )
				model.eval()
				SCREAMING_SNAKE_CASE_								=						model(SCREAMING_SNAKE_CASE      )
				self.parent.assertEqual(
				    result.last_hidden_state.shape      ,     (self.batch_size, self.expected_seq_len, self.hidden_size)      )





	def 						A_(							self      ,     SCREAMING_SNAKE_CASE      ,     SCREAMING_SNAKE_CASE      ,     SCREAMING_SNAKE_CASE      )  ->					List[str]:




				"""simple docstring"""



				SCREAMING_SNAKE_CASE_								=						YolosForObjectDetection(SCREAMING_SNAKE_CASE      )
				model.to(SCREAMING_SNAKE_CASE      )
				model.eval()

				SCREAMING_SNAKE_CASE_								=						model(pixel_values=SCREAMING_SNAKE_CASE      )
				SCREAMING_SNAKE_CASE_								=						model(SCREAMING_SNAKE_CASE      )

				self.parent.assertEqual(result.logits.shape      ,     (self.batch_size, self.num_detection_tokens, self.num_labels + 1)      )
				self.parent.assertEqual(result.pred_boxes.shape      ,     (self.batch_size, self.num_detection_tokens, 4)      )

				SCREAMING_SNAKE_CASE_								=						model(pixel_values=SCREAMING_SNAKE_CASE      ,     labels=SCREAMING_SNAKE_CASE      )

				self.parent.assertEqual(result.loss.shape      ,     ()      )
				self.parent.assertEqual(result.logits.shape      ,     (self.batch_size, self.num_detection_tokens, self.num_labels + 1)      )
				self.parent.assertEqual(result.pred_boxes.shape      ,     (self.batch_size, self.num_detection_tokens, 4)      )





	def 						A_(							self      )  ->					str:




				"""simple docstring"""



				SCREAMING_SNAKE_CASE_								=						self.prepare_config_and_inputs()
				SCREAMING_SNAKE_CASE_						,		SCREAMING_SNAKE_CASE_						,		SCREAMING_SNAKE_CASE_								=						config_and_inputs
				SCREAMING_SNAKE_CASE_								=						{'pixel_values': pixel_values}
				return config, inputs_dict




@require_torch
class       a_       (     SCREAMING_SNAKE_CASE__  ,    SCREAMING_SNAKE_CASE__  ,    unittest.TestCase     ):
	A    							= (YolosModel, YolosForObjectDetection) if is_torch_available() else ()
	A    							= (
	    {'''feature-extraction''': YolosModel, '''object-detection''': YolosForObjectDetection} if is_torch_available() else {}
	)

	A    							= False
	A    							= False
	A    							= False
	A    							= False





	def 						A_(							self      ,     SCREAMING_SNAKE_CASE      ,     SCREAMING_SNAKE_CASE      ,     SCREAMING_SNAKE_CASE=False      )  ->					List[Any]:




				"""simple docstring"""



				SCREAMING_SNAKE_CASE_								=						super()._prepare_for_class(SCREAMING_SNAKE_CASE      ,     SCREAMING_SNAKE_CASE      ,     return_labels=SCREAMING_SNAKE_CASE      )

				if return_labels:
							if model_class.__name__ == "YolosForObjectDetection":
										SCREAMING_SNAKE_CASE_								=						[]
										for i in range(self.model_tester.batch_size      ):
													SCREAMING_SNAKE_CASE_								=						{}
													SCREAMING_SNAKE_CASE_								=						torch.ones(
													    size=(self.model_tester.n_targets,)      ,     device=SCREAMING_SNAKE_CASE      ,     dtype=torch.long      )
													SCREAMING_SNAKE_CASE_								=						torch.ones(
													    self.model_tester.n_targets      ,     4      ,     device=SCREAMING_SNAKE_CASE      ,     dtype=torch.float      )
													labels.append(SCREAMING_SNAKE_CASE      )
										SCREAMING_SNAKE_CASE_								=						labels

				return inputs_dict





	def 						A_(							self      )  ->					List[str]:




				"""simple docstring"""



				SCREAMING_SNAKE_CASE_								=						YolosModelTester(self      )
				SCREAMING_SNAKE_CASE_								=						ConfigTester(self      ,     config_class=SCREAMING_SNAKE_CASE      ,     has_text_modality=SCREAMING_SNAKE_CASE      ,     hidden_size=37      )





	def 						A_(							self      )  ->					List[str]:




				"""simple docstring"""



				self.config_tester.run_common_tests()





	def 						A_(							self      )  ->					Optional[Any]:




				"""simple docstring"""



				pass





	def 						A_(							self      )  ->					int:




				"""simple docstring"""



				SCREAMING_SNAKE_CASE_						,		SCREAMING_SNAKE_CASE_								=						self.model_tester.prepare_config_and_inputs_for_common()

				for model_class in self.all_model_classes:
							SCREAMING_SNAKE_CASE_								=						model_class(SCREAMING_SNAKE_CASE      )
							self.assertIsInstance(model.get_input_embeddings()      ,     (nn.Module)      )
							SCREAMING_SNAKE_CASE_								=						model.get_output_embeddings()
							self.assertTrue(x is None or isinstance(SCREAMING_SNAKE_CASE      ,     nn.Linear      )      )





	def 						A_(							self      )  ->					str:




				"""simple docstring"""



				SCREAMING_SNAKE_CASE_						,		SCREAMING_SNAKE_CASE_								=						self.model_tester.prepare_config_and_inputs_for_common()

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

							SCREAMING_SNAKE_CASE_								=						['pixel_values']
							self.assertListEqual(arg_names[:1]      ,     SCREAMING_SNAKE_CASE      )





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




				"""simple docstring"""



				SCREAMING_SNAKE_CASE_								=						self.model_tester.prepare_config_and_inputs()
				self.model_tester.create_and_check_model(*SCREAMING_SNAKE_CASE      )





	def 						A_(							self      )  ->					Optional[Any]:




				"""simple docstring"""



				SCREAMING_SNAKE_CASE_						,		SCREAMING_SNAKE_CASE_								=						self.model_tester.prepare_config_and_inputs_for_common()
				SCREAMING_SNAKE_CASE_								=						True

				# in YOLOS, the seq_len is different
				SCREAMING_SNAKE_CASE_								=						self.model_tester.expected_seq_len
				for model_class in self.all_model_classes:
							SCREAMING_SNAKE_CASE_								=						True
							SCREAMING_SNAKE_CASE_								=						False
							SCREAMING_SNAKE_CASE_								=						True
							SCREAMING_SNAKE_CASE_								=						model_class(SCREAMING_SNAKE_CASE      )
							model.to(SCREAMING_SNAKE_CASE      )
							model.eval()
							with torch.no_grad():
										SCREAMING_SNAKE_CASE_								=						model(**self._prepare_for_class(SCREAMING_SNAKE_CASE      ,     SCREAMING_SNAKE_CASE      )      )
							SCREAMING_SNAKE_CASE_								=						outputs.attentions
							self.assertEqual(len(SCREAMING_SNAKE_CASE      )      ,     self.model_tester.num_hidden_layers      )

							# check that output_attentions also work using config
							del inputs_dict["output_attentions"]
							SCREAMING_SNAKE_CASE_								=						True
							SCREAMING_SNAKE_CASE_								=						model_class(SCREAMING_SNAKE_CASE      )
							model.to(SCREAMING_SNAKE_CASE      )
							model.eval()
							with torch.no_grad():
										SCREAMING_SNAKE_CASE_								=						model(**self._prepare_for_class(SCREAMING_SNAKE_CASE      ,     SCREAMING_SNAKE_CASE      )      )
							SCREAMING_SNAKE_CASE_								=						outputs.attentions
							self.assertEqual(len(SCREAMING_SNAKE_CASE      )      ,     self.model_tester.num_hidden_layers      )

							self.assertListEqual(
							    list(attentions[0].shape[-3:]      )      ,     [self.model_tester.num_attention_heads, seq_len, seq_len]      ,     )
							SCREAMING_SNAKE_CASE_								=						len(SCREAMING_SNAKE_CASE      )

							# Check attention is always last and order is fine
							SCREAMING_SNAKE_CASE_								=						True
							SCREAMING_SNAKE_CASE_								=						True
							SCREAMING_SNAKE_CASE_								=						model_class(SCREAMING_SNAKE_CASE      )
							model.to(SCREAMING_SNAKE_CASE      )
							model.eval()
							with torch.no_grad():
										SCREAMING_SNAKE_CASE_								=						model(**self._prepare_for_class(SCREAMING_SNAKE_CASE      ,     SCREAMING_SNAKE_CASE      )      )

							SCREAMING_SNAKE_CASE_								=						1
							self.assertEqual(out_len + added_hidden_states      ,     len(SCREAMING_SNAKE_CASE      )      )

							SCREAMING_SNAKE_CASE_								=						outputs.attentions

							self.assertEqual(len(SCREAMING_SNAKE_CASE      )      ,     self.model_tester.num_hidden_layers      )
							self.assertListEqual(
							    list(self_attentions[0].shape[-3:]      )      ,     [self.model_tester.num_attention_heads, seq_len, seq_len]      ,     )





	def 						A_(							self      )  ->					str:




				"""simple docstring"""



				def check_hidden_states_output(SCREAMING_SNAKE_CASE      ,     SCREAMING_SNAKE_CASE      ,     SCREAMING_SNAKE_CASE      ):
							SCREAMING_SNAKE_CASE_								=						model_class(SCREAMING_SNAKE_CASE      )
							model.to(SCREAMING_SNAKE_CASE      )
							model.eval()

							with torch.no_grad():
										SCREAMING_SNAKE_CASE_								=						model(**self._prepare_for_class(SCREAMING_SNAKE_CASE      ,     SCREAMING_SNAKE_CASE      )      )

							SCREAMING_SNAKE_CASE_								=						outputs.hidden_states

							SCREAMING_SNAKE_CASE_								=						getattr(
							    self.model_tester      ,     'expected_num_hidden_layers'      ,     self.model_tester.num_hidden_layers + 1      )
							self.assertEqual(len(SCREAMING_SNAKE_CASE      )      ,     SCREAMING_SNAKE_CASE      )

							# YOLOS has a different seq_length
							SCREAMING_SNAKE_CASE_								=						self.model_tester.expected_seq_len

							self.assertListEqual(
							    list(hidden_states[0].shape[-2:]      )      ,     [seq_length, self.model_tester.hidden_size]      ,     )

				SCREAMING_SNAKE_CASE_						,		SCREAMING_SNAKE_CASE_								=						self.model_tester.prepare_config_and_inputs_for_common()

				for model_class in self.all_model_classes:
							SCREAMING_SNAKE_CASE_								=						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"]
							SCREAMING_SNAKE_CASE_								=						True

							check_hidden_states_output(SCREAMING_SNAKE_CASE      ,     SCREAMING_SNAKE_CASE      ,     SCREAMING_SNAKE_CASE      )





	def 						A_(							self      )  ->					Optional[Any]:




				"""simple docstring"""



				SCREAMING_SNAKE_CASE_								=						self.model_tester.prepare_config_and_inputs()
				self.model_tester.create_and_check_for_object_detection(*SCREAMING_SNAKE_CASE      )





	@slow
	def 						A_(							self      )  ->					Optional[int]:




				"""simple docstring"""



				for model_name in YOLOS_PRETRAINED_MODEL_ARCHIVE_LIST[:1]:
							SCREAMING_SNAKE_CASE_								=						YolosModel.from_pretrained(SCREAMING_SNAKE_CASE      )
							self.assertIsNotNone(SCREAMING_SNAKE_CASE      )




def lowercase    (  )			->							Dict:


			'''simple docstring'''







			SCREAMING_SNAKE_CASE_								=						Image.open('./tests/fixtures/tests_samples/COCO/000000039769.png' )
			return image



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





	@cached_property
	def 						A_(							self      )  ->					str:




				"""simple docstring"""



				return AutoImageProcessor.from_pretrained('hustvl/yolos-small'      ) if is_vision_available() else None





	@slow
	def 						A_(							self      )  ->					Optional[int]:




				"""simple docstring"""



				SCREAMING_SNAKE_CASE_								=						YolosForObjectDetection.from_pretrained('hustvl/yolos-small'      ).to(SCREAMING_SNAKE_CASE      )

				SCREAMING_SNAKE_CASE_								=						self.default_image_processor
				SCREAMING_SNAKE_CASE_								=						prepare_img()
				SCREAMING_SNAKE_CASE_								=						image_processor(images=SCREAMING_SNAKE_CASE      ,     return_tensors='pt'      ).to(SCREAMING_SNAKE_CASE      )

				# forward pass
				with torch.no_grad():
							SCREAMING_SNAKE_CASE_								=						model(inputs.pixel_values      )

				# verify outputs
				SCREAMING_SNAKE_CASE_								=						torch.Size((1, 100, 92)      )
				self.assertEqual(outputs.logits.shape      ,     SCREAMING_SNAKE_CASE      )

				SCREAMING_SNAKE_CASE_								=						torch.tensor(
				    [[-2_4.0_2_4_8, -1_0.3_0_2_4, -1_4.8_2_9_0], [-4_2.0_3_9_2, -1_6.8_2_0_0, -2_7.4_3_3_4], [-2_7.2_7_4_3, -1_1.8_1_5_4, -1_8.7_1_4_8]]      ,     device=SCREAMING_SNAKE_CASE      ,     )
				SCREAMING_SNAKE_CASE_								=						torch.tensor(
				    [[0.2_5_5_9, 0.5_4_5_5, 0.4_7_0_6], [0.2_9_8_9, 0.7_2_7_9, 0.1_8_7_5], [0.7_7_3_2, 0.4_0_1_7, 0.4_4_6_2]]      ,     device=SCREAMING_SNAKE_CASE      )
				self.assertTrue(torch.allclose(outputs.logits[0, :3, :3]      ,     SCREAMING_SNAKE_CASE      ,     atol=1e-4      )      )
				self.assertTrue(torch.allclose(outputs.pred_boxes[0, :3, :3]      ,     SCREAMING_SNAKE_CASE      ,     atol=1e-4      )      )

				# verify postprocessing
				SCREAMING_SNAKE_CASE_								=						image_processor.post_process_object_detection(
				    SCREAMING_SNAKE_CASE      ,     threshold=0.3      ,     target_sizes=[image.size[::-1]]      )[0]
				SCREAMING_SNAKE_CASE_								=						torch.tensor([0.9_9_9_4, 0.9_7_9_0, 0.9_9_6_4, 0.9_9_7_2, 0.9_8_6_1]      ).to(SCREAMING_SNAKE_CASE      )
				SCREAMING_SNAKE_CASE_								=						[75, 75, 17, 63, 17]
				SCREAMING_SNAKE_CASE_								=						torch.tensor([3_3_5.0_6_0_9, 7_9.3_8_4_8, 3_7_5.4_2_1_6, 1_8_7.2_4_9_5]      ).to(SCREAMING_SNAKE_CASE      )

				self.assertEqual(len(results['scores']      )      ,     5      )
				self.assertTrue(torch.allclose(results['scores']      ,     SCREAMING_SNAKE_CASE      ,     atol=1e-4      )      )
				self.assertSequenceEqual(results['labels'].tolist()      ,     SCREAMING_SNAKE_CASE      )
				self.assertTrue(torch.allclose(results['boxes'][0, :]      ,     SCREAMING_SNAKE_CASE      )      )






import unittest

from diffusers import FlaxAutoencoderKL
from diffusers.utils import is_flax_available
from diffusers.utils.testing_utils import require_flax

from .test_modeling_common_flax import FlaxModelTesterMixin


if is_flax_available():
				import jax



@require_flax
class       a_       (     SCREAMING_SNAKE_CASE__  ,    unittest.TestCase     ):
	A    							= FlaxAutoencoderKL





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




				"""simple docstring"""



				SCREAMING_SNAKE_CASE_								=						4
				SCREAMING_SNAKE_CASE_								=						3
				SCREAMING_SNAKE_CASE_								=						(32, 32)

				SCREAMING_SNAKE_CASE_								=						jax.random.PRNGKey(0      )
				SCREAMING_SNAKE_CASE_								=						jax.random.uniform(SCREAMING_SNAKE_CASE      ,     ((batch_size, num_channels) + sizes)      )

				return {"sample": image, "prng_key": prng_key}





	def 						A_(							self      )  ->					Tuple:




				"""simple docstring"""



				SCREAMING_SNAKE_CASE_								=						{
				    'block_out_channels': [32, 64],
				    'in_channels': 3,
				    'out_channels': 3,
				    'down_block_types': ['DownEncoderBlock2D', 'DownEncoderBlock2D'],
				    'up_block_types': ['UpDecoderBlock2D', 'UpDecoderBlock2D'],
				    'latent_channels': 4,
				}
				SCREAMING_SNAKE_CASE_								=						self.dummy_input
				return init_dict, inputs_dict
