


'''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 							__UpperCamelCase    :




	def __init__(       self						,    __a						,    __a=13						,    __a=[30, 30]						,    __a=2						,    __a=3						,    __a=True						,    __a=True						,    __a=32						,    __a=5						,    __a=4						,    __a=37						,    __a="gelu"						,    __a=0.1						,    __a=0.1						,    __a=10						,    __a=0.02						,    __a=3						,    __a=None						,    __a=8						,    __a=10						,    ):

						'''simple docstring'''





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




	def 				__UpperCAmelCase							(       self							):

						'''simple docstring'''





						__a      :	Union[str, Any]    =  floats_tensor([self.batch_size, self.num_channels, self.image_size[0], self.image_size[1]]							)

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

						__a      :	str    =  self.get_config()

						return config, pixel_values, labels




	def 				__UpperCAmelCase							(       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=__a						,    initializer_range=self.initializer_range						,    num_detection_tokens=self.num_detection_tokens						,    num_labels=self.num_labels						,    )




	def 				__UpperCAmelCase							(       self						,    __a						,    __a						,    __a							):

						'''simple docstring'''





						__a      :	Union[str, Any]    =  YolosModel(config=__a							)
						model.to(__a							)
						model.eval()
						__a      :	List[str]    =  model(__a							)
						self.parent.assertEqual(
						    result.last_hidden_state.shape						,    (self.batch_size, self.expected_seq_len, self.hidden_size)							)




	def 				__UpperCAmelCase							(       self						,    __a						,    __a						,    __a							):

						'''simple docstring'''





						__a      :	str    =  YolosForObjectDetection(__a							)
						model.to(__a							)
						model.eval()

						__a      :	Optional[int]    =  model(pixel_values=__a							)
						__a      :	Any    =  model(__a							)

						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      :	Tuple    =  model(pixel_values=__a						,    labels=__a							)

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

						'''simple docstring'''





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





@require_torch
class 							__UpperCamelCase    (		lowerCAmelCase_		,				lowerCAmelCase_		,				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 				__UpperCAmelCase							(       self						,    __a						,    __a						,    __a=False							):

						'''simple docstring'''





						__a      :	Any    =  super()._prepare_for_class(__a						,    __a						,    return_labels=__a							)

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

						return inputs_dict




	def 				__UpperCAmelCase							(       self							):

						'''simple docstring'''





						__a      :	str    =  YolosModelTester(self							)
						__a      :	Optional[Any]    =  ConfigTester(self						,    config_class=__a						,    has_text_modality=__a						,    hidden_size=37							)




	def 				__UpperCAmelCase							(       self							):

						'''simple docstring'''





						self.config_tester.run_common_tests()




	def 				__UpperCAmelCase							(       self							):

						'''simple docstring'''





						pass




	def 				__UpperCAmelCase							(       self							):

						'''simple docstring'''





						__a   ,    __a      :	List[str]    =  self.model_tester.prepare_config_and_inputs_for_common()

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




	def 				__UpperCAmelCase							(       self							):

						'''simple docstring'''





						__a   ,    __a      :	Dict    =  self.model_tester.prepare_config_and_inputs_for_common()

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

											__a      :	List[Any]    =  ['pixel_values']
											self.assertListEqual(arg_names[:1]						,    __a							)




	def 				__UpperCAmelCase							(       self							):

						'''simple docstring'''





						__a      :	Dict    =  self.model_tester.prepare_config_and_inputs()
						self.model_tester.create_and_check_model(*__a							)




	def 				__UpperCAmelCase							(       self							):

						'''simple docstring'''





						__a   ,    __a      :	int    =  self.model_tester.prepare_config_and_inputs_for_common()
						__a      :	int    =  True

						# in YOLOS, the seq_len is different
						__a      :	Any    =  self.model_tester.expected_seq_len
						for model_class in self.all_model_classes:
											__a      :	Tuple    =  True
											__a      :	Tuple    =  False
											__a      :	Optional[Any]    =  True
											__a      :	int    =  model_class(__a							)
											model.to(__a							)
											model.eval()
											with torch.no_grad():
																__a      :	Optional[int]    =  model(**self._prepare_for_class(__a						,    __a							)							)
											__a      :	int    =  outputs.attentions
											self.assertEqual(len(__a							)						,    self.model_tester.num_hidden_layers							)

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

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

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

											__a      :	Optional[Any]    =  1
											self.assertEqual(out_len + added_hidden_states						,    len(__a							)							)

											__a      :	Any    =  outputs.attentions

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

						'''simple docstring'''





						def check_hidden_states_output(__a						,    __a						,    __a							):
											__a      :	Union[str, Any]    =  model_class(__a							)
											model.to(__a							)
											model.eval()

											with torch.no_grad():
																__a      :	Dict    =  model(**self._prepare_for_class(__a						,    __a							)							)

											__a      :	Tuple    =  outputs.hidden_states

											__a      :	List[Any]    =  getattr(
											    self.model_tester						,    'expected_num_hidden_layers'						,    self.model_tester.num_hidden_layers + 1							)
											self.assertEqual(len(__a							)						,    __a							)

											# YOLOS has a different seq_length
											__a      :	List[str]    =  self.model_tester.expected_seq_len

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

						__a   ,    __a      :	List[Any]    =  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(__a						,    __a						,    __a							)

											# check that output_hidden_states also work using config
											del inputs_dict["output_hidden_states"]
											__a      :	Union[str, Any]    =  True

											check_hidden_states_output(__a						,    __a						,    __a							)




	def 				__UpperCAmelCase							(       self							):

						'''simple docstring'''





						__a      :	Union[str, Any]    =  self.model_tester.prepare_config_and_inputs()
						self.model_tester.create_and_check_for_object_detection(*__a							)





	@slow
	def 				__UpperCAmelCase							(       self							):

						'''simple docstring'''





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






def   lowerCamelCase							():
					__a      :	Union[str, Any]    =  Image.open('./tests/fixtures/tests_samples/COCO/000000039769.png'       )
					return image





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




	@cached_property
	def 				__UpperCAmelCase							(       self							):

						'''simple docstring'''





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





	@slow
	def 				__UpperCAmelCase							(       self							):

						'''simple docstring'''





						__a      :	Optional[Any]    =  YolosForObjectDetection.from_pretrained('hustvl/yolos-small'							).to(__a							)

						__a      :	Union[str, Any]    =  self.default_image_processor
						__a      :	Dict    =  prepare_img()
						__a      :	Tuple    =  image_processor(images=__a						,    return_tensors='pt'							).to(__a							)

						# forward pass
						with torch.no_grad():
											__a      :	List[str]    =  model(inputs.pixel_values							)

						# verify outputs
						__a      :	Any    =  torch.Size((1, 100, 92)							)
						self.assertEqual(outputs.logits.shape						,    __a							)

						__a      :	Optional[int]    =  torch.tensor(
						    [[-24.0248, -10.3024, -14.8290], [-42.0392, -16.8200, -27.4334], [-27.2743, -11.8154, -18.7148]]						,    device=__a						,    )
						__a      :	Optional[Any]    =  torch.tensor(
						    [[0.2559, 0.5455, 0.4706], [0.2989, 0.7279, 0.1875], [0.7732, 0.4017, 0.4462]]						,    device=__a							)
						self.assertTrue(torch.allclose(outputs.logits[0, :3, :3]						,    __a						,    atol=1E-4							)							)
						self.assertTrue(torch.allclose(outputs.pred_boxes[0, :3, :3]						,    __a						,    atol=1E-4							)							)

						# verify postprocessing
						__a      :	int    =  image_processor.post_process_object_detection(
						    __a						,    threshold=0.3						,    target_sizes=[image.size[::-1]]							)[0]
						__a      :	str    =  torch.tensor([0.9994, 0.9790, 0.9964, 0.9972, 0.9861]							).to(__a							)
						__a      :	List[Any]    =  [75, 75, 17, 63, 17]
						__a      :	Optional[Any]    =  torch.tensor([335.0609, 79.3848, 375.4216, 187.2495]							).to(__a							)

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







'''simple docstring'''



from typing import TYPE_CHECKING

from ...utils import OptionalDependencyNotAvailable, _LazyModule, is_tokenizers_available, is_torch_available


__lowercase     :						Union[str, Any]	=     {
    'configuration_roc_bert': ['ROC_BERT_PRETRAINED_CONFIG_ARCHIVE_MAP', 'RoCBertConfig'],
    'tokenization_roc_bert': ['RoCBertTokenizer'],
}

try:
	if not is_tokenizers_available():
		raise OptionalDependencyNotAvailable()
except OptionalDependencyNotAvailable:
	pass
else:
	pass

try:
	if not is_torch_available():
		raise OptionalDependencyNotAvailable()
except OptionalDependencyNotAvailable:
	pass
else:
	__lowercase     :						List[str]	=     [
	    'ROC_BERT_PRETRAINED_MODEL_ARCHIVE_LIST',
	    'RoCBertForCausalLM',
	    'RoCBertForMaskedLM',
	    'RoCBertForMultipleChoice',
	    'RoCBertForPreTraining',
	    'RoCBertForQuestionAnswering',
	    'RoCBertForSequenceClassification',
	    'RoCBertForTokenClassification',
	    'RoCBertLayer',
	    'RoCBertModel',
	    'RoCBertPreTrainedModel',
	    'load_tf_weights_in_roc_bert',
	]

if TYPE_CHECKING:
	from .configuration_roc_bert import ROC_BERT_PRETRAINED_CONFIG_ARCHIVE_MAP, RoCBertConfig
	from .tokenization_roc_bert import RoCBertTokenizer

	try:
		if not is_tokenizers_available():
			raise OptionalDependencyNotAvailable()
	except OptionalDependencyNotAvailable:
		pass
	else:
		raise OptionalDependencyNotAvailable()

	try:
		if not is_torch_available():
			raise OptionalDependencyNotAvailable()
	except OptionalDependencyNotAvailable:
		pass
	else:
		from .modeling_roc_bert import (
		    ROC_BERT_PRETRAINED_MODEL_ARCHIVE_LIST,
		    RoCBertForCausalLM,
		    RoCBertForMaskedLM,
		    RoCBertForMultipleChoice,
		    RoCBertForPreTraining,
		    RoCBertForQuestionAnswering,
		    RoCBertForSequenceClassification,
		    RoCBertForTokenClassification,
		    RoCBertLayer,
		    RoCBertModel,
		    RoCBertPreTrainedModel,
		    load_tf_weights_in_roc_bert,
		)


else:
	import sys

	__lowercase     :						Any	=     _LazyModule(__name__, globals()['__file__'], _import_structure, module_spec=__spec__)



