


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






       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			,     )->      int:
            _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   UpperCamelCase						( self   )->      Tuple:
            _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=_UpperCamelCase   )
                      _A				=							torch.rand(self.n_targets			,     4			,     device=_UpperCamelCase   )
                      labels.append(_UpperCamelCase   )

            _A				=							self.get_config()

            return config, pixel_values, labels






       def   UpperCamelCase						( self   )->      Any:
            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   UpperCamelCase						( self			,     _UpperCamelCase			,     _UpperCamelCase			,     _UpperCamelCase   )->      Optional[int]:
            _A				=							YolosModel(config=_UpperCamelCase   )
            model.to(_UpperCamelCase   )
            model.eval()
            _A				=							model(_UpperCamelCase   )
            self.parent.assertEqual(
                result.last_hidden_state.shape			,     (self.batch_size, self.expected_seq_len, self.hidden_size)   )






       def   UpperCamelCase						( self			,     _UpperCamelCase			,     _UpperCamelCase			,     _UpperCamelCase   )->      Union[str, Any]:
            _A				=							YolosForObjectDetection(_UpperCamelCase   )
            model.to(_UpperCamelCase   )
            model.eval()

            _A				=							model(pixel_values=_UpperCamelCase   )
            _A				=							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)   )

            _A				=							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   UpperCamelCase						( self   )->      List[str]:
            _A				=							self.prepare_config_and_inputs()
            _A		,				_A		,				_A				=							config_and_inputs
            _A				=							{'pixel_values': pixel_values}
            return config, inputs_dict






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

       __UpperCAmelCase					=False
       __UpperCAmelCase					=False
       __UpperCAmelCase					=False
       __UpperCAmelCase					=False






       def   UpperCamelCase						( self			,     _UpperCamelCase			,     _UpperCamelCase			,     _UpperCamelCase=False   )->      Optional[int]:
            _A				=							super()._prepare_for_class(_UpperCamelCase			,     _UpperCamelCase			,     return_labels=_UpperCamelCase   )

            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=_UpperCamelCase			,     dtype=torch.long   )
                           _A				=							torch.ones(
                               self.model_tester.n_targets			,     4			,     device=_UpperCamelCase			,     dtype=torch.float   )
                           labels.append(_UpperCamelCase   )
                      _A				=							labels

            return inputs_dict






       def   UpperCamelCase						( self   )->      Optional[int]:
            _A				=							YolosModelTester(self   )
            _A				=							ConfigTester(self			,     config_class=_UpperCamelCase			,     has_text_modality=_UpperCamelCase			,     hidden_size=37   )






       def   UpperCamelCase						( self   )->      Dict:
            self.config_tester.run_common_tests()






       def   UpperCamelCase						( self   )->      int:
            # YOLOS does not use inputs_embeds
            pass






       def   UpperCamelCase						( self   )->      Optional[int]:
            _A		,				_A				=							self.model_tester.prepare_config_and_inputs_for_common()

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






       def   UpperCamelCase						( self   )->      Dict:
            _A		,				_A				=							self.model_tester.prepare_config_and_inputs_for_common()

            for model_class in self.all_model_classes:
                 _A				=							model_class(_UpperCamelCase   )
                 _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]			,     _UpperCamelCase   )






       def   UpperCamelCase						( self   )->      int:
            _A				=							self.model_tester.prepare_config_and_inputs()
            self.model_tester.create_and_check_model(*_UpperCamelCase   )






       def   UpperCamelCase						( self   )->      Any:
            _A		,				_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(_UpperCamelCase   )
                 model.to(_UpperCamelCase   )
                 model.eval()
                 with torch.no_grad():
                      _A				=							model(**self._prepare_for_class(_UpperCamelCase			,     _UpperCamelCase   )   )
                 _A				=							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"]
                 _A				=							True
                 _A				=							model_class(_UpperCamelCase   )
                 model.to(_UpperCamelCase   )
                 model.eval()
                 with torch.no_grad():
                      _A				=							model(**self._prepare_for_class(_UpperCamelCase			,     _UpperCamelCase   )   )
                 _A				=							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]			,     )
                 _A				=							len(_UpperCamelCase   )

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

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

                 _A				=							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   UpperCamelCase						( self   )->      str:
            def check_hidden_states_output(_UpperCamelCase			,     _UpperCamelCase			,     _UpperCamelCase   ):
                 _A				=							model_class(_UpperCamelCase   )
                 model.to(_UpperCamelCase   )
                 model.eval()

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

                 _A				=							outputs.hidden_states

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

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

            _A		,				_A				=							self.model_tester.prepare_config_and_inputs_for_common()

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

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

                 check_hidden_states_output(_UpperCamelCase			,     _UpperCamelCase			,     _UpperCamelCase   )






       def   UpperCamelCase						( self   )->      Dict:
            _A				=							self.model_tester.prepare_config_and_inputs()
            self.model_tester.create_and_check_for_object_detection(*_UpperCamelCase   )






       @slow
       def   UpperCamelCase						( self   )->      Any:
            for model_name in YOLOS_PRETRAINED_MODEL_ARCHIVE_LIST[:1]:
                 _A				=							YolosModel.from_pretrained(_UpperCamelCase   )
                 self.assertIsNotNone(_UpperCamelCase   )






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







     """simple docstring"""
     _A				=							Image.open('./tests/fixtures/tests_samples/COCO/000000039769.png'		)
     return image






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






       @cached_property
       def   UpperCamelCase						( self   )->      List[Any]:
            return AutoImageProcessor.from_pretrained('hustvl/yolos-small'   ) if is_vision_available() else None






       @slow
       def   UpperCamelCase						( self   )->      Optional[int]:
            _A				=							YolosForObjectDetection.from_pretrained('hustvl/yolos-small'   ).to(_UpperCamelCase   )

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

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

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

            _A				=							torch.tensor(
                [[-24.0248, -10.3024, -14.8290], [-42.0392, -16.8200, -27.4334], [-27.2743, -11.8154, -18.7148]]			,     device=_UpperCamelCase			,     )
            _A				=							torch.tensor(
                [[0.2559, 0.5455, 0.4706], [0.2989, 0.7279, 0.1875], [0.7732, 0.4017, 0.4462]]			,     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
            _A				=							image_processor.post_process_object_detection(
                _UpperCamelCase			,     threshold=0.3			,     target_sizes=[image.size[::-1]]   )[0]
            _A				=							torch.tensor([0.9994, 0.9790, 0.9964, 0.9972, 0.9861]   ).to(_UpperCamelCase   )
            _A				=							[75, 75, 17, 63, 17]
            _A				=							torch.tensor([335.0609, 79.3848, 375.4216, 187.2495]   ).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   )   )









'''simple docstring'''
# tests directory-specific settings - this file is run automatically
# by pytest before any tests are run

import doctest
import sys
import warnings
from os.path import abspath, dirname, join

import _pytest

from transformers.testing_utils import HfDoctestModule, HfDocTestParser


# allow having multiple repository checkouts and not needing to remember to rerun
# 'pip install -e .[dev]' when switching between checkouts and running tests.
lowerCAmelCase						=					abspath(join(dirname(__file__), """src"""))
sys.path.insert(1, git_repo_path)

# silence FutureWarning warnings in tests since often we can't act on them until
# they become normal warnings - i.e. the tests still need to test the current functionality
warnings.simplefilter(action="""ignore""", category=FutureWarning)

def 					lowerCamelCase_ ( __UpperCamelCase					:       Optional[Any]		)					->	str:







     """simple docstring"""
     config.addinivalue_line(
         'markers'							,    'is_pt_tf_cross_test: mark test to run only when PT and TF interactions are tested'		)
     config.addinivalue_line(
         'markers'							,    'is_pt_flax_cross_test: mark test to run only when PT and FLAX interactions are tested'		)
     config.addinivalue_line('markers'							,    'is_pipeline_test: mark test to run only when pipelines are tested'		)
     config.addinivalue_line('markers'							,    'is_staging_test: mark test to run only in the staging environment'		)
     config.addinivalue_line('markers'							,    'accelerate_tests: mark test that require accelerate'		)
     config.addinivalue_line('markers'							,    'tool_tests: mark the tool tests that are run on their specific schedule'		)

def 					lowerCamelCase_ ( __UpperCamelCase					:       Tuple		)					->	List[str]:







     """simple docstring"""
     from transformers.testing_utils import pytest_addoption_shared

     pytest_addoption_shared(__UpperCamelCase		)

def 					lowerCamelCase_ ( __UpperCamelCase					:       Union[str, Any]		)					->	str:







     """simple docstring"""
     from transformers.testing_utils import pytest_terminal_summary_main

     _A				=							terminalreporter.config.getoption('--make-reports'		)
     if make_reports:
          pytest_terminal_summary_main(__UpperCamelCase							,    id=__UpperCamelCase		)

def 					lowerCamelCase_ ( __UpperCamelCase					:       str							,    __UpperCamelCase					:       List[str]		)					->	Optional[int]:







     """simple docstring"""
     # If no tests are collected, pytest exists with code 5, which makes the CI fail.
     if exitstatus == 5:
          _A				=							0


# Doctest custom flag to ignore output.
lowerCAmelCase						=					doctest.register_optionflag("""IGNORE_RESULT""")

lowerCAmelCase						=					doctest.OutputChecker






class        lowerCAmelCase_  (     UpperCAmelCase	):






       def   UpperCamelCase						( self			,     _UpperCamelCase			,     _UpperCamelCase			,     _UpperCamelCase   )->      Tuple:
            if IGNORE_RESULT & optionflags:
                 return True
            return OutputChecker.check_output(self			,     _UpperCamelCase			,     _UpperCamelCase			,     _UpperCamelCase   )






lowerCAmelCase						=					CustomOutputChecker
lowerCAmelCase						=					HfDoctestModule
lowerCAmelCase						=					HfDocTestParser





