




'''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	:  List[str]							,      lowerCAmelCase_	:  Optional[Any]							,      lowerCAmelCase_	:  Any=13							,      lowerCAmelCase_	:  str=[30, 30]							,      lowerCAmelCase_	:  Dict=2							,      lowerCAmelCase_	:  Optional[Any]=3							,      lowerCAmelCase_	:  int=True							,      lowerCAmelCase_	:  List[Any]=True							,      lowerCAmelCase_	:  Union[str, Any]=32							,      lowerCAmelCase_	:  Dict=5							,      lowerCAmelCase_	:  List[str]=4							,      lowerCAmelCase_	:  int=37							,      lowerCAmelCase_	:  List[str]="gelu"							,      lowerCAmelCase_	:  Dict=0.1							,      lowerCAmelCase_	:  Union[str, Any]=0.1							,      lowerCAmelCase_	:  List[str]=10							,      lowerCAmelCase_	:  Union[str, Any]=0.0_2							,      lowerCAmelCase_	:  Union[str, Any]=3							,      lowerCAmelCase_	:  Any=None							,      lowerCAmelCase_	:  Optional[Any]=8							,      lowerCAmelCase_	:  Tuple=10							,      )      ->							Tuple:


														"""simple docstring"""


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







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


														"""simple docstring"""


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

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

														_a     					=    self.get_config()

														return config, pixel_values, labels







							def        __lowerCAmelCase      (  self	:  Any )      ->							List[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=_a							,      initializer_range=self.initializer_range							,      num_detection_tokens=self.num_detection_tokens							,      num_labels=self.num_labels							,      )







							def        __lowerCAmelCase      (  self	:  List[str]							,      lowerCAmelCase_	:  Optional[int]							,      lowerCAmelCase_	:  Any							,      lowerCAmelCase_	:  Dict )      ->							Optional[int]:


														"""simple docstring"""


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







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


														"""simple docstring"""


														_a     					=    YolosForObjectDetection(_a )
														model.to(_a )
														model.eval()

														_a     					=    model(pixel_values=_a )
														_a     					=    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     					=    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        __lowerCAmelCase      (  self	:  List[str] )      ->							Optional[int]:


														"""simple docstring"""


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



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

							lowercase_          =    False
							lowercase_          =    False
							lowercase_          =    False
							lowercase_          =    False







							def        __lowerCAmelCase      (  self	:  List[Any]							,      lowerCAmelCase_	:  Optional[int]							,      lowerCAmelCase_	:  Tuple							,      lowerCAmelCase_	:  List[str]=False )      ->							List[str]:


														"""simple docstring"""


														_a     					=    super()._prepare_for_class(_a							,      _a							,      return_labels=_a )

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

														return inputs_dict







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


														"""simple docstring"""


														_a     					=    YolosModelTester(self )
														_a     					=    ConfigTester(self							,      config_class=_a							,      has_text_modality=_a							,      hidden_size=37 )







							def        __lowerCAmelCase      (  self	:  Any )      ->							Tuple:


														"""simple docstring"""


														self.config_tester.run_common_tests()







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


														"""simple docstring"""


														pass







							def        __lowerCAmelCase      (  self	:  Any )      ->							Any:


														"""simple docstring"""


														_a     					=    self.model_tester.prepare_config_and_inputs_for_common()

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







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


														"""simple docstring"""


														_a     					=    self.model_tester.prepare_config_and_inputs_for_common()

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

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







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


														"""simple docstring"""


														_a     					=    self.model_tester.prepare_config_and_inputs()
														self.model_tester.create_and_check_model(*_a )







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


														"""simple docstring"""


														_a     					=    self.model_tester.prepare_config_and_inputs_for_common()
														_a     					=    True

														# in YOLOS, the seq_len is different
														_a     					=    self.model_tester.expected_seq_len
														for model_class in self.all_model_classes:
																					_a     					=    True
																					_a     					=    False
																					_a     					=    True
																					_a     					=    model_class(_a )
																					model.to(_a )
																					model.eval()
																					with torch.no_grad():
																												_a     					=    model(**self._prepare_for_class(_a							,      _a ) )
																					_a     					=    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     					=    True
																					_a     					=    model_class(_a )
																					model.to(_a )
																					model.eval()
																					with torch.no_grad():
																												_a     					=    model(**self._prepare_for_class(_a							,      _a ) )
																					_a     					=    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     					=    len(_a )

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

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

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


														"""simple docstring"""


														def check_hidden_states_output(lowerCAmelCase_	:  List[Any]							,      lowerCAmelCase_	:  Optional[int]							,      lowerCAmelCase_	:  int ):
																					_a     					=    model_class(_a )
																					model.to(_a )
																					model.eval()

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

																					_a     					=    outputs.hidden_states

																					_a     					=    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     					=    self.model_tester.expected_seq_len

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

														_a     					=    self.model_tester.prepare_config_and_inputs_for_common()

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

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

																					check_hidden_states_output(_a							,      _a							,      _a )







							def        __lowerCAmelCase      (  self	:  Tuple )      ->							str:


														"""simple docstring"""


														_a     					=    self.model_tester.prepare_config_and_inputs()
														self.model_tester.create_and_check_for_object_detection(*_a )







							@slow
							def        __lowerCAmelCase      (  self	:  Any )      ->							Tuple:


														"""simple docstring"""


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



def 		snake_case_   ():





							'''simple docstring'''


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

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







							@cached_property
							def        __lowerCAmelCase      (  self	:  int )      ->							Dict:


														"""simple docstring"""


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







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


														"""simple docstring"""


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

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

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

														# verify outputs
														_a     					=    torch.Size((1, 1_00, 92) )
														self.assertEqual(outputs.logits.shape							,      _a )

														_a     					=    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=_a							,      )
														_a     					=    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=_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     					=    image_processor.post_process_object_detection(
														    _a							,      threshold=0.3							,      target_sizes=[image.size[::-1]] )[0]
														_a     					=    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(_a )
														_a     					=    [75, 75, 17, 63, 17]
														_a     					=    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(_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'''


import argparse
from collections import defaultdict

import yaml


_snake_case				:				int       							=		'docs/source/en/_toctree.yml'
def 		snake_case_   (UpperCamelCase	:  Optional[int]				):





							'''simple docstring'''


							_a     					=    defaultdict(UpperCamelCase				)
							for doc in model_doc:
														counts[doc["local"]] += 1
							_a     					=    [key for key, value in counts.items() if value > 1]

							_a     					=    []
							for duplicate_key in duplicates:
														_a     					=    list({doc['''title'''] for doc in model_doc if doc['''local'''] == duplicate_key}				)
														if len(UpperCamelCase				) > 1:
																					raise ValueError(
																					    f'{duplicate_key} is present several times in the documentation table of content at '
																					    '''`docs/source/en/_toctree.yml` with different *Title* values. Choose one of those and remove the '''
																					    '''others.'''				)
														# Only add this once
														new_doc.append({'''local''': duplicate_key, '''title''': titles[0]}				)

							# Add none duplicate-keys
							new_doc.extend([doc for doc in model_doc if counts[doc['''local''']] == 1]				)

							# Sort
							return sorted(UpperCamelCase			,						key=lambda UpperCamelCase				: s["title"].lower()				)
def 		snake_case_   (UpperCamelCase	:  str=False				):





							'''simple docstring'''


							with open(UpperCamelCase			,						encoding='''utf-8'''				) as f:
														_a     					=    yaml.safe_load(f.read()				)

							# Get to the API doc
							_a     					=    0
							while content[api_idx]["title"] != "API":
														api_idx += 1
							_a     					=    content[api_idx]['''sections''']

							# Then to the model doc
							_a     					=    0
							while api_doc[model_idx]["title"] != "Models":
														model_idx += 1

							_a     					=    api_doc[model_idx]['''sections''']

							_a     					=    [(idx, section) for idx, section in enumerate(UpperCamelCase				) if '''sections''' in section]
							_a     					=    False
							for idx, modality_doc in modalities_docs:
														_a     					=    modality_doc['''sections''']
														_a     					=    clean_model_doc_toc(UpperCamelCase				)

														if old_modality_doc != new_modality_doc:
																					_a     					=    True
																					if overwrite:
																												_a     					=    new_modality_doc

							if diff:
														if overwrite:
																					_a     					=    model_doc
																					_a     					=    api_doc
																					with open(UpperCamelCase			,						'''w'''			,						encoding='''utf-8'''				) as f:
																												f.write(yaml.dump(UpperCamelCase			,						allow_unicode=UpperCamelCase				)				)
														else:
																					raise ValueError(
																					    '''The model doc part of the table of content is not properly sorted, run `make style` to fix this.'''				)


if __name__ == "__main__":
				_snake_case				:				List[str]       							=		argparse.ArgumentParser()
				parser.add_argument('--fix_and_overwrite', action='store_true', help='Whether to fix inconsistencies.')
				_snake_case				:				List[Any]       							=		parser.parse_args()

				check_model_doc(args.fix_and_overwrite)

