






'''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					,   __a					,   __a=1_3					,   __a=[3_0, 3_0]					,   __a=2					,   __a=3					,   __a=True					,   __a=True					,   __a=3_2					,   __a=5					,   __a=4					,   __a=3_7					,   __a="gelu"					,   __a=0.1					,   __a=0.1					,   __a=1_0					,   __a=0.02					,   __a=3					,   __a=None					,   __a=8					,   __a=1_0					,   )			->      int:
      """simple docstring"""






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







   def     SCREAMING_SNAKE_CASE__					(self)			->      List[str]:
      """simple docstring"""






      __snake_case				:      Optional[Any]     							= floats_tensor([self.batch_size, self.num_channels, self.image_size[0], self.image_size[1]])

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

      __snake_case				:      Union[str, Any]     							= self.get_config()

      return config, pixel_values, labels







   def     SCREAMING_SNAKE_CASE__					(self)			->      Optional[int]:
      """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     SCREAMING_SNAKE_CASE__					(self					,   __a					,   __a					,   __a)			->      Union[str, Any]:
      """simple docstring"""






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







   def     SCREAMING_SNAKE_CASE__					(self					,   __a					,   __a					,   __a)			->      Optional[Any]:
      """simple docstring"""






      __snake_case				:      Any     							= YolosForObjectDetection(__a)
      model.to(__a)
      model.eval()

      __snake_case				:      Union[str, Any]     							= model(pixel_values=__a)
      __snake_case				:      Dict     							= 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))

      __snake_case				:      List[Any]     							= 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     SCREAMING_SNAKE_CASE__					(self)			->      Optional[Any]:
      """simple docstring"""






      __snake_case				:      Tuple     							= self.prepare_config_and_inputs()
      __snake_case							,__snake_case							,__snake_case				:      Dict     							= config_and_inputs
      __snake_case				:      Any     							= {'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					,   __a					,   __a					,   __a=False)			->      str:
      """simple docstring"""






      __snake_case				:      Dict     							= super()._prepare_for_class(__a					,   __a					,   return_labels=__a)

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

      return inputs_dict







   def     SCREAMING_SNAKE_CASE__					(self)			->      Optional[int]:
      """simple docstring"""






      __snake_case				:      Tuple     							= YolosModelTester(self)
      __snake_case				:      List[str]     							= ConfigTester(self					,   config_class=__a					,   has_text_modality=__a					,   hidden_size=3_7)







   def     SCREAMING_SNAKE_CASE__					(self)			->      Dict:
      """simple docstring"""






      self.config_tester.run_common_tests()







   def     SCREAMING_SNAKE_CASE__					(self)			->      Tuple:
      """simple docstring"""






      pass







   def     SCREAMING_SNAKE_CASE__					(self)			->      Dict:
      """simple docstring"""






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

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







   def     SCREAMING_SNAKE_CASE__					(self)			->      Dict:
      """simple docstring"""






      __snake_case							,__snake_case				:      Any     							= self.model_tester.prepare_config_and_inputs_for_common()

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

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







   def     SCREAMING_SNAKE_CASE__					(self)			->      Dict:
      """simple docstring"""






      __snake_case				:      Tuple     							= self.model_tester.prepare_config_and_inputs()
      self.model_tester.create_and_check_model(*__a)







   def     SCREAMING_SNAKE_CASE__					(self)			->      Optional[int]:
      """simple docstring"""






      __snake_case							,__snake_case				:      Tuple     							= self.model_tester.prepare_config_and_inputs_for_common()
      __snake_case				:      str     							= True

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

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

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

         __snake_case				:      Optional[int]     							= 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     SCREAMING_SNAKE_CASE__					(self)			->      int:
      """simple docstring"""






      def check_hidden_states_output(__a					,   __a					,   __a):
         __snake_case				:      Optional[int]     							= model_class(__a)
         model.to(__a)
         model.eval()

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

         __snake_case				:      Optional[int]     							= outputs.hidden_states

         __snake_case				:      List[str]     							= 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
         __snake_case				:      Optional[Any]     							= self.model_tester.expected_seq_len

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

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

      for model_class in self.all_model_classes:
         __snake_case				:      Tuple     							= True
         check_hidden_states_output(__a					,   __a					,   __a)

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

         check_hidden_states_output(__a					,   __a					,   __a)







   def     SCREAMING_SNAKE_CASE__					(self)			->      str:
      """simple docstring"""






      __snake_case				:      Dict     							= self.model_tester.prepare_config_and_inputs()
      self.model_tester.create_and_check_for_object_detection(*__a)







   @slow
   def     SCREAMING_SNAKE_CASE__					(self)			->      int:
      """simple docstring"""






      for model_name in YOLOS_PRETRAINED_MODEL_ARCHIVE_LIST[:1]:
         __snake_case				:      List[str]     							= YolosModel.from_pretrained(__a)
         self.assertIsNotNone(__a)




def        _SCREAMING_SNAKE_CASE  (				)    -> int:







   """simple docstring"""
   __snake_case				:      Dict     							= 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)			->      Optional[Any]:
      """simple docstring"""






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







   @slow
   def     SCREAMING_SNAKE_CASE__					(self)			->      Optional[int]:
      """simple docstring"""






      __snake_case				:      int     							= YolosForObjectDetection.from_pretrained('hustvl/yolos-small').to(__a)

      __snake_case				:      Optional[Any]     							= self.default_image_processor
      __snake_case				:      List[Any]     							= prepare_img()
      __snake_case				:      Optional[Any]     							= image_processor(images=__a					,   return_tensors='pt').to(__a)

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

      # verify outputs
      __snake_case				:      Optional[Any]     							= torch.Size((1, 1_0_0, 9_2))
      self.assertEqual(outputs.logits.shape					,   __a)

      __snake_case				:      Optional[int]     							= 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=__a					,   )
      __snake_case				:      int     							= 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=__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
      __snake_case				:      Optional[int]     							= image_processor.post_process_object_detection(
          __a					,   threshold=0.3					,   target_sizes=[image.size[::-1]])[0]
      __snake_case				:      List[str]     							= torch.tensor([0.9_994, 0.9_790, 0.9_964, 0.9_972, 0.9_861]).to(__a)
      __snake_case				:      Tuple     							= [7_5, 7_5, 1_7, 6_3, 1_7]
      __snake_case				:      Any     							= torch.tensor([335.0_609, 79.3_848, 375.4_216, 187.2_495]).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'''






# Copyright 2023 The HuggingFace Team. All rights reserved.
#
# Licensed under the Apache License, Version 2.0 (the "License");
# you may not use this file except in compliance with the License.
# You may obtain a copy of the License at
#
#     http://www.apache.org/licenses/LICENSE-2.0
#
# Unless required by applicable law or agreed to in writing, software
# distributed under the License is distributed on an "AS IS" BASIS,
# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
# See the License for the specific language governing permissions and
# limitations under the License.
from typing import TYPE_CHECKING

from ...utils import OptionalDependencyNotAvailable, _LazyModule, is_torch_available


__A    	=   {'''configuration_timm_backbone''': ['''TimmBackboneConfig''']}


try:
      if not is_torch_available():
            raise OptionalDependencyNotAvailable()
except OptionalDependencyNotAvailable:
      pass
else:
      __A    	=   ['''TimmBackbone''']


if TYPE_CHECKING:
      from .configuration_timm_backbone import TimmBackboneConfig

      try:
            if not is_torch_available():
                  raise OptionalDependencyNotAvailable()
      except OptionalDependencyNotAvailable:
            pass
      else:
            from .modeling_timm_backbone import TimmBackbone

else:
      import sys

      __A    	=   _LazyModule(__name__, globals()['''__file__'''], _import_structure, module_spec=__spec__)