




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,	UpperCamelCase__,	UpperCamelCase__=13,	UpperCamelCase__=[30, 30],	UpperCamelCase__=2,	UpperCamelCase__=3,	UpperCamelCase__=True,	UpperCamelCase__=True,	UpperCamelCase__=32,	UpperCamelCase__=5,	UpperCamelCase__=4,	UpperCamelCase__=37,	UpperCamelCase__="gelu",	UpperCamelCase__=0.1,	UpperCamelCase__=0.1,	UpperCamelCase__=10,	UpperCamelCase__=0.02,	UpperCamelCase__=3,	UpperCamelCase__=None,	UpperCamelCase__=8,	UpperCamelCase__=10,	):







								"""simple docstring"""



								lowerCAmelCase_      			=  parent
								lowerCAmelCase_      			=  batch_size
								lowerCAmelCase_      			=  image_size
								lowerCAmelCase_      			=  patch_size
								lowerCAmelCase_      			=  num_channels
								lowerCAmelCase_      			=  is_training
								lowerCAmelCase_      			=  use_labels
								lowerCAmelCase_      			=  hidden_size
								lowerCAmelCase_      			=  num_hidden_layers
								lowerCAmelCase_      			=  num_attention_heads
								lowerCAmelCase_      			=  intermediate_size
								lowerCAmelCase_      			=  hidden_act
								lowerCAmelCase_      			=  hidden_dropout_prob
								lowerCAmelCase_      			=  attention_probs_dropout_prob
								lowerCAmelCase_      			=  type_sequence_label_size
								lowerCAmelCase_      			=  initializer_range
								lowerCAmelCase_      			=  num_labels
								lowerCAmelCase_      			=  scope
								lowerCAmelCase_      			=  n_targets
								lowerCAmelCase_      			=  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
								lowerCAmelCase_      			=  (image_size[1] // patch_size) * (image_size[0] // patch_size)
								lowerCAmelCase_      			=  num_patches + 1 + self.num_detection_tokens



		def        SCREAMING_SNAKE_CASE__			(     self   ):







								"""simple docstring"""



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

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

								lowerCAmelCase_      			=  self.get_config()

								return config, pixel_values, labels



		def        SCREAMING_SNAKE_CASE__			(     self   ):







								"""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=UpperCamelCase__,	initializer_range=self.initializer_range,	num_detection_tokens=self.num_detection_tokens,	num_labels=self.num_labels,	)



		def        SCREAMING_SNAKE_CASE__			(     self,	UpperCamelCase__,	UpperCamelCase__,	UpperCamelCase__   ):







								"""simple docstring"""



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



		def        SCREAMING_SNAKE_CASE__			(     self,	UpperCamelCase__,	UpperCamelCase__,	UpperCamelCase__   ):







								"""simple docstring"""



								lowerCAmelCase_      			=  YolosForObjectDetection(UpperCamelCase__   )
								model.to(UpperCamelCase__   )
								model.eval()

								lowerCAmelCase_      			=  model(pixel_values=UpperCamelCase__   )
								lowerCAmelCase_      			=  model(UpperCamelCase__   )

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

								lowerCAmelCase_      			=  model(pixel_values=UpperCamelCase__,	labels=UpperCamelCase__   )

								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        SCREAMING_SNAKE_CASE__			(     self   ):







								"""simple docstring"""



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







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

		__snake_case									=   False
		__snake_case									=   False
		__snake_case									=   False
		__snake_case									=   False



		def        SCREAMING_SNAKE_CASE__			(     self,	UpperCamelCase__,	UpperCamelCase__,	UpperCamelCase__=False   ):







								"""simple docstring"""



								lowerCAmelCase_      			=  super()._prepare_for_class(UpperCamelCase__,	UpperCamelCase__,	return_labels=UpperCamelCase__   )

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

								return inputs_dict



		def        SCREAMING_SNAKE_CASE__			(     self   ):







								"""simple docstring"""



								lowerCAmelCase_      			=  YolosModelTester(self   )
								lowerCAmelCase_      			=  ConfigTester(self,	config_class=UpperCamelCase__,	has_text_modality=UpperCamelCase__,	hidden_size=37   )



		def        SCREAMING_SNAKE_CASE__			(     self   ):







								"""simple docstring"""



								self.config_tester.run_common_tests()



		def        SCREAMING_SNAKE_CASE__			(     self   ):







								"""simple docstring"""



								pass



		def        SCREAMING_SNAKE_CASE__			(     self   ):







								"""simple docstring"""



								lowerCAmelCase_			,					lowerCAmelCase_      			=  self.model_tester.prepare_config_and_inputs_for_common()

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



		def        SCREAMING_SNAKE_CASE__			(     self   ):







								"""simple docstring"""



								lowerCAmelCase_			,					lowerCAmelCase_      			=  self.model_tester.prepare_config_and_inputs_for_common()

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

														lowerCAmelCase_      			=  ['''pixel_values''']
														self.assertListEqual(arg_names[:1],	UpperCamelCase__   )



		def        SCREAMING_SNAKE_CASE__			(     self   ):







								"""simple docstring"""



								lowerCAmelCase_      			=  self.model_tester.prepare_config_and_inputs()
								self.model_tester.create_and_check_model(*UpperCamelCase__   )



		def        SCREAMING_SNAKE_CASE__			(     self   ):







								"""simple docstring"""



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

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

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

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

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

														lowerCAmelCase_      			=  1
														self.assertEqual(out_len + added_hidden_states,	len(UpperCamelCase__   )   )

														lowerCAmelCase_      			=  outputs.attentions

														self.assertEqual(len(UpperCamelCase__   ),	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        SCREAMING_SNAKE_CASE__			(     self   ):







								"""simple docstring"""



								def check_hidden_states_output(UpperCamelCase__,	UpperCamelCase__,	UpperCamelCase__   ):
														lowerCAmelCase_      			=  model_class(UpperCamelCase__   )
														model.to(UpperCamelCase__   )
														model.eval()

														with torch.no_grad():
																				lowerCAmelCase_      			=  model(**self._prepare_for_class(UpperCamelCase__,	UpperCamelCase__   )   )

														lowerCAmelCase_      			=  outputs.hidden_states

														lowerCAmelCase_      			=  getattr(
														    self.model_tester,	'''expected_num_hidden_layers''',	self.model_tester.num_hidden_layers + 1   )
														self.assertEqual(len(UpperCamelCase__   ),	UpperCamelCase__   )

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

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

								lowerCAmelCase_			,					lowerCAmelCase_      			=  self.model_tester.prepare_config_and_inputs_for_common()

								for model_class in self.all_model_classes:
														lowerCAmelCase_      			=  True
														check_hidden_states_output(UpperCamelCase__,	UpperCamelCase__,	UpperCamelCase__   )

														# check that output_hidden_states also work using config
														del inputs_dict["output_hidden_states"]
														lowerCAmelCase_      			=  True

														check_hidden_states_output(UpperCamelCase__,	UpperCamelCase__,	UpperCamelCase__   )



		def        SCREAMING_SNAKE_CASE__			(     self   ):







								"""simple docstring"""



								lowerCAmelCase_      			=  self.model_tester.prepare_config_and_inputs()
								self.model_tester.create_and_check_for_object_detection(*UpperCamelCase__   )







		@slow
		def        SCREAMING_SNAKE_CASE__			(     self   ):







								"""simple docstring"""



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







def __UpperCamelCase			(       ):
						lowerCAmelCase_      			=  Image.open('''./tests/fixtures/tests_samples/COCO/000000039769.png'''  )
						return image






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



		@cached_property
		def        SCREAMING_SNAKE_CASE__			(     self   ):







								"""simple docstring"""



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







		@slow
		def        SCREAMING_SNAKE_CASE__			(     self   ):







								"""simple docstring"""



								lowerCAmelCase_      			=  YolosForObjectDetection.from_pretrained('''hustvl/yolos-small'''   ).to(UpperCamelCase__   )

								lowerCAmelCase_      			=  self.default_image_processor
								lowerCAmelCase_      			=  prepare_img()
								lowerCAmelCase_      			=  image_processor(images=UpperCamelCase__,	return_tensors='''pt'''   ).to(UpperCamelCase__   )

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

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

								lowerCAmelCase_      			=  torch.tensor(
								    [[-24.0_248, -10.3_024, -14.8_290], [-42.0_392, -16.8_200, -27.4_334], [-27.2_743, -11.8_154, -18.7_148]],	device=UpperCamelCase__,	)
								lowerCAmelCase_      			=  torch.tensor(
								    [[0.2_559, 0.5_455, 0.4_706], [0.2_989, 0.7_279, 0.1_875], [0.7_732, 0.4_017, 0.4_462]],	device=UpperCamelCase__   )
								self.assertTrue(torch.allclose(outputs.logits[0, :3, :3],	UpperCamelCase__,	atol=1E-4   )   )
								self.assertTrue(torch.allclose(outputs.pred_boxes[0, :3, :3],	UpperCamelCase__,	atol=1E-4   )   )

								# verify postprocessing
								lowerCAmelCase_      			=  image_processor.post_process_object_detection(
								    UpperCamelCase__,	threshold=0.3,	target_sizes=[image.size[::-1]]   )[0]
								lowerCAmelCase_      			=  torch.tensor([0.9_994, 0.9_790, 0.9_964, 0.9_972, 0.9_861]   ).to(UpperCamelCase__   )
								lowerCAmelCase_      			=  [75, 75, 17, 63, 17]
								lowerCAmelCase_      			=  torch.tensor([335.0_609, 79.3_848, 375.4_216, 187.2_495]   ).to(UpperCamelCase__   )

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










import unittest

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


if is_torch_available():
						import torch

						from transformers import AutoModelForImageClassification

if is_vision_available():
						from transformers import AutoImageProcessor


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



		@slow
		def        SCREAMING_SNAKE_CASE__			(     self   ):







								"""simple docstring"""



								lowerCAmelCase_      			=  AutoImageProcessor.from_pretrained('''microsoft/dit-base-finetuned-rvlcdip'''   )
								lowerCAmelCase_      			=  AutoModelForImageClassification.from_pretrained('''microsoft/dit-base-finetuned-rvlcdip'''   )
								model.to(UpperCamelCase__   )

								from datasets import load_dataset

								lowerCAmelCase_      			=  load_dataset('''nielsr/rvlcdip-demo'''   )

								lowerCAmelCase_      			=  dataset['''train'''][0]['''image'''].convert('''RGB'''   )

								lowerCAmelCase_      			=  image_processor(UpperCamelCase__,	return_tensors='''pt'''   ).to(UpperCamelCase__   )

								# forward pass
								with torch.no_grad():
														lowerCAmelCase_      			=  model(**UpperCamelCase__   )
														lowerCAmelCase_      			=  outputs.logits

								lowerCAmelCase_      			=  torch.Size((1, 16)   )
								self.assertEqual(logits.shape,	UpperCamelCase__   )

								lowerCAmelCase_      			=  torch.tensor(
								    [-0.4_158, -0.4_092, -0.4_347],	device=UpperCamelCase__,	dtype=torch.float,	)
								self.assertTrue(torch.allclose(logits[0, :3],	UpperCamelCase__,	atol=1E-4   )   )




