






'''simple docstring'''





import itertools
import random
import unittest

import numpy as np

from transformers import is_speech_available
from transformers.testing_utils import require_torch, require_torchaudio

from ...test_sequence_feature_extraction_common import SequenceFeatureExtractionTestMixin


if is_speech_available():
							from transformers import SpeechaTextFeatureExtractor

a_  			=			random.Random()



def       __UpperCAmelCase					(lowercase__						,lowercase__=1.0						,lowercase__=None						,lowercase__=None					)		->					List[str]:

						'''simple docstring'''


						if rng is None:
												a_					  = global_rng

						a_					  = []
						for batch_idx in range(shape[0]					):
												values.append([]					)
												for _ in range(shape[1]					):
																		values[-1].append(rng.random() * scale					)

						return values





@require_torch
@require_torchaudio
class 		SCREAMING_SNAKE_CASE__ (  unittest.TestCase     ):



		def __init__(     self:     List[str]					, a:     Dict					, a:     Dict=7					, a:     List[str]=4_00					, a:     Any=20_00					, a:     Tuple=24					, a:     Optional[int]=24					, a:     Optional[Any]=0.0					, a:     int=1_60_00					, a:     Optional[int]=True					, a:     int=True					, )	->Optional[int]:






								'''simple docstring'''


								a_					  = parent
								a_					  = batch_size
								a_					  = min_seq_length
								a_					  = max_seq_length
								a_					  = (self.max_seq_length - self.min_seq_length) // (self.batch_size - 1)
								a_					  = feature_size
								a_					  = num_mel_bins
								a_					  = padding_value
								a_					  = sampling_rate
								a_					  = return_attention_mask
								a_					  = do_normalize



		def _lowerCAmelCase  (     self:     Optional[Any])	->Tuple:






								'''simple docstring'''


								return {
								    "feature_size": self.feature_size,
								    "num_mel_bins": self.num_mel_bins,
								    "padding_value": self.padding_value,
								    "sampling_rate": self.sampling_rate,
								    "return_attention_mask": self.return_attention_mask,
								    "do_normalize": self.do_normalize,
								}




		def _lowerCAmelCase  (     self:     Optional[int]					, a:     Optional[int]=False					, a:     List[str]=False)	->Tuple:






								'''simple docstring'''


								def _flatten(a:     List[Any]):
														return list(itertools.chain(*a))

								if equal_length:
														a_					  = [floats_list((self.max_seq_length, self.feature_size)) for _ in range(self.batch_size)]
								else:
														# make sure that inputs increase in size
														a_					  = [
														    floats_list((x, self.feature_size))
														    for x in range(self.min_seq_length					, self.max_seq_length					, self.seq_length_diff)
														]
								if numpify:
														a_					  = [np.asarray(a) for x in speech_inputs]
								return speech_inputs





@require_torch
@require_torchaudio
class 		SCREAMING_SNAKE_CASE__ (  __snake_case		,		unittest.TestCase     ):
		_UpperCAmelCase								=SpeechaTextFeatureExtractor if is_speech_available() else None



		def _lowerCAmelCase  (     self:     Tuple)	->int:






								'''simple docstring'''


								a_					  = SpeechaTextFeatureExtractionTester(self)



		def _lowerCAmelCase  (     self:     Optional[Any]					, a:     Optional[int])	->Tuple:






								'''simple docstring'''


								self.assertTrue(np.all(np.mean(a					, axis=0) < 1e-3))
								self.assertTrue(np.all(np.abs(np.var(a					, axis=0) - 1) < 1e-3))



		def _lowerCAmelCase  (     self:     Optional[int])	->Optional[Any]:






								'''simple docstring'''


								a_					  = self.feature_extraction_class(**self.feat_extract_tester.prepare_feat_extract_dict())
								# create three inputs of length 800, 1000, and 1200
								a_					  = [floats_list((1, x))[0] for x in range(8_00					, 14_00					, 2_00)]
								a_					  = [np.asarray(a) for speech_input in speech_inputs]

								# Test feature size
								a_					  = feature_extractor(a					, padding=a					, return_tensors="np").input_features
								self.assertTrue(input_features.ndim == 3)
								self.assertTrue(input_features.shape[-1] == feature_extractor.feature_size)

								# Test not batched input
								a_					  = feature_extractor(speech_inputs[0]					, return_tensors="np").input_features
								a_					  = feature_extractor(np_speech_inputs[0]					, return_tensors="np").input_features
								self.assertTrue(np.allclose(a					, a					, atol=1e-3))

								# Test batched
								a_					  = feature_extractor(a					, return_tensors="np").input_features
								a_					  = feature_extractor(a					, return_tensors="np").input_features
								for enc_seq_a, enc_seq_a in zip(a					, a):
														self.assertTrue(np.allclose(a					, a					, atol=1e-3))

								# Test 2-D numpy arrays are batched.
								a_					  = [floats_list((1, x))[0] for x in (8_00, 8_00, 8_00)]
								a_					  = np.asarray(a)
								a_					  = feature_extractor(a					, return_tensors="np").input_features
								a_					  = feature_extractor(a					, return_tensors="np").input_features
								for enc_seq_a, enc_seq_a in zip(a					, a):
														self.assertTrue(np.allclose(a					, a					, atol=1e-3))



		def _lowerCAmelCase  (     self:     Dict)	->Optional[Any]:






								'''simple docstring'''


								a_					  = self.feature_extraction_class(**self.feat_extract_tester.prepare_feat_extract_dict())
								a_					  = [floats_list((1, x))[0] for x in range(8_00					, 14_00					, 2_00)]

								a_					  = ['''longest''', '''max_length''', '''do_not_pad''']
								a_					  = [None, 16, None]
								for max_length, padding in zip(a					, a):
														a_					  = feature_extractor(
														    a					, padding=a					, max_length=a					, return_attention_mask=a)
														a_					  = inputs.input_features
														a_					  = inputs.attention_mask
														a_					  = [np.sum(a) for x in attention_mask]

														self._check_zero_mean_unit_variance(input_features[0][: fbank_feat_lengths[0]])
														self._check_zero_mean_unit_variance(input_features[1][: fbank_feat_lengths[1]])
														self._check_zero_mean_unit_variance(input_features[2][: fbank_feat_lengths[2]])



		def _lowerCAmelCase  (     self:     int)	->List[Any]:






								'''simple docstring'''


								a_					  = self.feature_extraction_class(**self.feat_extract_tester.prepare_feat_extract_dict())
								a_					  = [floats_list((1, x))[0] for x in range(8_00					, 14_00					, 2_00)]

								a_					  = ['''longest''', '''max_length''', '''do_not_pad''']
								a_					  = [None, 16, None]
								for max_length, padding in zip(a					, a):
														a_					  = feature_extractor(
														    a					, max_length=a					, padding=a					, return_tensors="np"					, return_attention_mask=a)
														a_					  = inputs.input_features
														a_					  = inputs.attention_mask
														a_					  = [np.sum(a) for x in attention_mask]

														self._check_zero_mean_unit_variance(input_features[0][: fbank_feat_lengths[0]])
														self.assertTrue(input_features[0][fbank_feat_lengths[0] :].sum() < 1e-6)
														self._check_zero_mean_unit_variance(input_features[1][: fbank_feat_lengths[1]])
														self.assertTrue(input_features[0][fbank_feat_lengths[1] :].sum() < 1e-6)
														self._check_zero_mean_unit_variance(input_features[2][: fbank_feat_lengths[2]])



		def _lowerCAmelCase  (     self:     Tuple)	->List[str]:






								'''simple docstring'''


								a_					  = self.feature_extraction_class(**self.feat_extract_tester.prepare_feat_extract_dict())
								a_					  = [floats_list((1, x))[0] for x in range(8_00					, 14_00					, 2_00)]
								a_					  = feature_extractor(
								    a					, padding="max_length"					, max_length=4					, truncation=a					, return_tensors="np"					, return_attention_mask=a					, )
								a_					  = inputs.input_features
								a_					  = inputs.attention_mask
								a_					  = np.sum(attention_mask == 1					, axis=1)

								self._check_zero_mean_unit_variance(input_features[0, : fbank_feat_lengths[0]])
								self._check_zero_mean_unit_variance(input_features[1])
								self._check_zero_mean_unit_variance(input_features[2])



		def _lowerCAmelCase  (     self:     List[Any])	->Dict:






								'''simple docstring'''


								a_					  = self.feature_extraction_class(**self.feat_extract_tester.prepare_feat_extract_dict())
								a_					  = [floats_list((1, x))[0] for x in range(8_00					, 14_00					, 2_00)]
								a_					  = feature_extractor(
								    a					, padding="longest"					, max_length=4					, truncation=a					, return_tensors="np"					, return_attention_mask=a					, )
								a_					  = inputs.input_features
								a_					  = inputs.attention_mask
								a_					  = np.sum(attention_mask == 1					, axis=1)

								self._check_zero_mean_unit_variance(input_features[0, : fbank_feat_lengths[0]])
								self._check_zero_mean_unit_variance(input_features[1, : fbank_feat_lengths[1]])
								self._check_zero_mean_unit_variance(input_features[2])

								# make sure that if max_length < longest -> then pad to max_length
								self.assertEqual(input_features.shape					, (3, 4, 24))

								a_					  = [floats_list((1, x))[0] for x in range(8_00					, 14_00					, 2_00)]
								a_					  = feature_extractor(
								    a					, padding="longest"					, max_length=16					, truncation=a					, return_tensors="np"					, return_attention_mask=a					, )
								a_					  = inputs.input_features
								a_					  = inputs.attention_mask
								a_					  = np.sum(attention_mask == 1					, axis=1)

								self._check_zero_mean_unit_variance(input_features[0, : fbank_feat_lengths[0]])
								self._check_zero_mean_unit_variance(input_features[1, : fbank_feat_lengths[1]])
								self._check_zero_mean_unit_variance(input_features[2])

								# make sure that if max_length < longest -> then pad to max_length
								self.assertEqual(input_features.shape					, (3, 6, 24))



		def _lowerCAmelCase  (     self:     Optional[Any])	->Dict:






								'''simple docstring'''


								import torch

								a_					  = self.feature_extraction_class(**self.feat_extract_tester.prepare_feat_extract_dict())
								a_					  = np.random.rand(1_00					, 32).astype(np.floataa)
								a_					  = np_speech_inputs.tolist()

								for inputs in [py_speech_inputs, np_speech_inputs]:
														a_					  = feature_extractor.pad([{"input_features": inputs}]					, return_tensors="np")
														self.assertTrue(np_processed.input_features.dtype == np.floataa)
														a_					  = feature_extractor.pad([{"input_features": inputs}]					, return_tensors="pt")
														self.assertTrue(pt_processed.input_features.dtype == torch.floataa)



		def _lowerCAmelCase  (     self:     List[Any]					, a:     Dict)	->List[str]:






								'''simple docstring'''


								from datasets import load_dataset

								a_					  = load_dataset("hf-internal-testing/librispeech_asr_dummy"					, "clean"					, split="validation")
								# automatic decoding with librispeech
								a_					  = ds.sort("id").select(range(a))[:num_samples]['''audio''']

								return [x["array"] for x in speech_samples]




		def _lowerCAmelCase  (     self:     Dict)	->List[str]:






								'''simple docstring'''


								a_					  = np.array([
								    -1.5745, -1.7713, -1.7020, -1.6069, -1.2250, -1.1105, -0.9072, -0.8241,
								    -1.2310, -0.8098, -0.3320, -0.4101, -0.7985, -0.4996, -0.8213, -0.9128,
								    -1.0420, -1.1286, -1.0440, -0.7999, -0.8405, -1.2275, -1.5443, -1.4625,
								])
								# fmt: on

								a_					  = self._load_datasamples(1)
								a_					  = self.feature_extraction_class(**self.feat_extract_tester.prepare_feat_extract_dict())
								a_					  = feature_extractor(a					, return_tensors="pt").input_features
								self.assertEquals(input_features.shape					, (1, 5_84, 24))
								self.assertTrue(np.allclose(input_features[0, 0, :30]					, a					, atol=1e-4))





'''simple docstring'''




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.02		,     SCREAMING_SNAKE_CASE=3		,     SCREAMING_SNAKE_CASE=None		,     SCREAMING_SNAKE_CASE=8		,     SCREAMING_SNAKE_CASE=10		,     )					->							Dict:






         """simple docstring"""






         A			:  List[Any]   =		parent
         A			:  Optional[Any]   =		batch_size
         A			:  int   =		image_size
         A			:  Optional[Any]   =		patch_size
         A			:  Union[str, Any]   =		num_channels
         A			:  Optional[int]   =		is_training
         A			:  List[str]   =		use_labels
         A			:  Any   =		hidden_size
         A			:  Dict   =		num_hidden_layers
         A			:  List[str]   =		num_attention_heads
         A			:  List[Any]   =		intermediate_size
         A			:  List[Any]   =		hidden_act
         A			:  Union[str, Any]   =		hidden_dropout_prob
         A			:  Union[str, Any]   =		attention_probs_dropout_prob
         A			:  Optional[Any]   =		type_sequence_label_size
         A			:  Optional[Any]   =		initializer_range
         A			:  Optional[Any]   =		num_labels
         A			:  Union[str, Any]   =		scope
         A			:  Optional[Any]   =		n_targets
         A			:  str   =		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
         A			:  Dict   =		(image_size[1] // patch_size) * (image_size[0] // patch_size)
         A			:  str   =		num_patches + 1 + self.num_detection_tokens





     def 							__lowerCAmelCase				(				self      )					->							int:






         """simple docstring"""






         A			:  Tuple   =		floats_tensor([self.batch_size, self.num_channels, self.image_size[0], self.image_size[1]]      )

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

         A			:  Any   =		self.get_config()

         return config, pixel_values, labels





     def 							__lowerCAmelCase				(				self      )					->							str:






         """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 							__lowerCAmelCase				(				self		,     SCREAMING_SNAKE_CASE		,     SCREAMING_SNAKE_CASE		,     SCREAMING_SNAKE_CASE      )					->							str:






         """simple docstring"""






         A			:  int   =		YolosModel(config=SCREAMING_SNAKE_CASE      )
         model.to(SCREAMING_SNAKE_CASE      )
         model.eval()
         A			:  Optional[int]   =		model(SCREAMING_SNAKE_CASE      )
         self.parent.assertEqual(
             result.last_hidden_state.shape		,     (self.batch_size, self.expected_seq_len, self.hidden_size)      )





     def 							__lowerCAmelCase				(				self		,     SCREAMING_SNAKE_CASE		,     SCREAMING_SNAKE_CASE		,     SCREAMING_SNAKE_CASE      )					->							str:






         """simple docstring"""






         A			:  int   =		YolosForObjectDetection(SCREAMING_SNAKE_CASE      )
         model.to(SCREAMING_SNAKE_CASE      )
         model.eval()

         A			:  Any   =		model(pixel_values=SCREAMING_SNAKE_CASE      )
         A			:  Tuple   =		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)      )

         A			:  List[str]   =		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 							__lowerCAmelCase				(				self      )					->							int:






         """simple docstring"""






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





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

     __magic_name__          =						False
     __magic_name__          =						False
     __magic_name__          =						False
     __magic_name__          =						False





     def 							__lowerCAmelCase				(				self		,     SCREAMING_SNAKE_CASE		,     SCREAMING_SNAKE_CASE		,     SCREAMING_SNAKE_CASE=False      )					->							Union[str, Any]:






         """simple docstring"""






         A			:  Union[str, Any]   =		super()._prepare_for_class(SCREAMING_SNAKE_CASE		,     SCREAMING_SNAKE_CASE		,     return_labels=SCREAMING_SNAKE_CASE      )

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

         return inputs_dict





     def 							__lowerCAmelCase				(				self      )					->							Optional[int]:






         """simple docstring"""






         A			:  Tuple   =		YolosModelTester(self      )
         A			:  Any   =		ConfigTester(self		,     config_class=SCREAMING_SNAKE_CASE		,     has_text_modality=SCREAMING_SNAKE_CASE		,     hidden_size=37      )





     def 							__lowerCAmelCase				(				self      )					->							int:






         """simple docstring"""






         self.config_tester.run_common_tests()





     def 							__lowerCAmelCase				(				self      )					->							Any:






         """simple docstring"""






         pass





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






         """simple docstring"""






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

         for model_class in self.all_model_classes:
             A			:  Dict   =		model_class(SCREAMING_SNAKE_CASE      )
             self.assertIsInstance(model.get_input_embeddings()		,     (nn.Module)      )
             A			:  List[Any]   =		model.get_output_embeddings()
             self.assertTrue(x is None or isinstance(SCREAMING_SNAKE_CASE		,     nn.Linear      )      )





     def 							__lowerCAmelCase				(				self      )					->							int:






         """simple docstring"""






         A,    A			:  int   =		self.model_tester.prepare_config_and_inputs_for_common()

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

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





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






         """simple docstring"""






         A			:  Optional[int]   =		self.model_tester.prepare_config_and_inputs()
         self.model_tester.create_and_check_model(*SCREAMING_SNAKE_CASE      )





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






         """simple docstring"""






         A,    A			:  Any   =		self.model_tester.prepare_config_and_inputs_for_common()
         A			:  List[Any]   =		True

         # in YOLOS, the seq_len is different
         A			:  Optional[int]   =		self.model_tester.expected_seq_len
         for model_class in self.all_model_classes:
             A			:  Optional[int]   =		True
             A			:  int   =		False
             A			:  List[str]   =		True
             A			:  str   =		model_class(SCREAMING_SNAKE_CASE      )
             model.to(SCREAMING_SNAKE_CASE      )
             model.eval()
             with torch.no_grad():
                 A			:  Optional[Any]   =		model(**self._prepare_for_class(SCREAMING_SNAKE_CASE		,     SCREAMING_SNAKE_CASE      )      )
             A			:  int   =		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"]
             A			:  int   =		True
             A			:  Optional[int]   =		model_class(SCREAMING_SNAKE_CASE      )
             model.to(SCREAMING_SNAKE_CASE      )
             model.eval()
             with torch.no_grad():
                 A			:  List[str]   =		model(**self._prepare_for_class(SCREAMING_SNAKE_CASE		,     SCREAMING_SNAKE_CASE      )      )
             A			:  List[Any]   =		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]		,     )
             A			:  Any   =		len(SCREAMING_SNAKE_CASE      )

             # Check attention is always last and order is fine
             A			:  Optional[Any]   =		True
             A			:  Union[str, Any]   =		True
             A			:  Optional[int]   =		model_class(SCREAMING_SNAKE_CASE      )
             model.to(SCREAMING_SNAKE_CASE      )
             model.eval()
             with torch.no_grad():
                 A			:  Tuple   =		model(**self._prepare_for_class(SCREAMING_SNAKE_CASE		,     SCREAMING_SNAKE_CASE      )      )

             A			:  Optional[int]   =		1
             self.assertEqual(out_len + added_hidden_states		,     len(SCREAMING_SNAKE_CASE      )      )

             A			:  List[str]   =		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 							__lowerCAmelCase				(				self      )					->							Tuple:






         """simple docstring"""






         def check_hidden_states_output(SCREAMING_SNAKE_CASE		,     SCREAMING_SNAKE_CASE		,     SCREAMING_SNAKE_CASE      ):
             A			:  List[Any]   =		model_class(SCREAMING_SNAKE_CASE      )
             model.to(SCREAMING_SNAKE_CASE      )
             model.eval()

             with torch.no_grad():
                 A			:  List[Any]   =		model(**self._prepare_for_class(SCREAMING_SNAKE_CASE		,     SCREAMING_SNAKE_CASE      )      )

             A			:  Dict   =		outputs.hidden_states

             A			:  List[Any]   =		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
             A			:  int   =		self.model_tester.expected_seq_len

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

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

         for model_class in self.all_model_classes:
             A			:  List[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"]
             A			:  Optional[Any]   =		True

             check_hidden_states_output(SCREAMING_SNAKE_CASE		,     SCREAMING_SNAKE_CASE		,     SCREAMING_SNAKE_CASE      )





     def 							__lowerCAmelCase				(				self      )					->							List[Any]:






         """simple docstring"""






         A			:  Dict   =		self.model_tester.prepare_config_and_inputs()
         self.model_tester.create_and_check_for_object_detection(*SCREAMING_SNAKE_CASE      )





     @slow
     def 							__lowerCAmelCase				(				self      )					->							Tuple:






         """simple docstring"""






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







def 						lowerCAmelCase_							(  ):




    '''simple docstring'''



    A			:  List[str]   =		Image.open('''./tests/fixtures/tests_samples/COCO/000000039769.png'''		)
    return image







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





     @cached_property
     def 							__lowerCAmelCase				(				self      )					->							Dict:






         """simple docstring"""






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





     @slow
     def 							__lowerCAmelCase				(				self      )					->							str:






         """simple docstring"""






         A			:  Union[str, Any]   =		YolosForObjectDetection.from_pretrained('''hustvl/yolos-small'''      ).to(SCREAMING_SNAKE_CASE      )

         A			:  str   =		self.default_image_processor
         A			:  Any   =		prepare_img()
         A			:  Any   =		image_processor(images=SCREAMING_SNAKE_CASE		,     return_tensors='''pt'''      ).to(SCREAMING_SNAKE_CASE      )

         # forward pass
         with torch.no_grad():
             A			:  Optional[Any]   =		model(inputs.pixel_values      )

         # verify outputs
         A			:  List[Any]   =		torch.Size((1, 100, 92)      )
         self.assertEqual(outputs.logits.shape		,     SCREAMING_SNAKE_CASE      )

         A			:  Optional[Any]   =		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=SCREAMING_SNAKE_CASE		,     )
         A			:  str   =		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=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
         A			:  int   =		image_processor.post_process_object_detection(
             SCREAMING_SNAKE_CASE		,     threshold=0.3		,     target_sizes=[image.size[::-1]]      )[0]
         A			:  str   =		torch.tensor([0.9_994, 0.9_790, 0.9_964, 0.9_972, 0.9_861]      ).to(SCREAMING_SNAKE_CASE      )
         A			:  Optional[Any]   =		[75, 75, 17, 63, 17]
         A			:  Union[str, Any]   =		torch.tensor([335.0_609, 79.3_848, 375.4_216, 187.2_495]      ).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      )      )




