





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_=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'''




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





      def 	__UpperCamelCase(			self       ):
       '''simple docstring'''




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

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

       UpperCamelCase     : Any	     =       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'''




       UpperCamelCase     : Union[str, Any]	     =       YolosModel(config=A_       )
       model.to(A_       )
       model.eval()
       UpperCamelCase     : Dict	     =       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'''




       UpperCamelCase     : int	     =       YolosForObjectDetection(A_       )
       model.to(A_       )
       model.eval()

       UpperCamelCase     : Optional[int]	     =       model(pixel_values=A_       )
       UpperCamelCase     : List[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)       )

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




       UpperCamelCase     : Tuple	     =       self.prepare_config_and_inputs()
       UpperCamelCase     ,   UpperCamelCase     ,   UpperCamelCase     : Tuple	     =       config_and_inputs
       UpperCamelCase     : str	     =       {"pixel_values": pixel_values}
       return config, inputs_dict



@require_torch
class  A__       (	__snake_case	,       __snake_case	,       unittest.TestCase      ):
      _UpperCAmelCase     :Optional[Any]						   =       (YolosModel, YolosForObjectDetection) if is_torch_available() else ()
      _UpperCAmelCase     :Any						   =       (
          {'feature-extraction': YolosModel, 'object-detection': YolosForObjectDetection} if is_torch_available() else {}
      )

      _UpperCAmelCase     :Tuple						   =       False
      _UpperCAmelCase     :int						   =       False
      _UpperCAmelCase     :int						   =       False
      _UpperCAmelCase     :Optional[int]						   =       False





      def 	__UpperCamelCase(			self	,							A_	,							A_	,							A_=False       ):
       '''simple docstring'''




       UpperCamelCase     : Optional[int]	     =       super()._prepare_for_class(A_	,							A_	,							return_labels=A_       )

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

       return inputs_dict





      def 	__UpperCamelCase(			self       ):
       '''simple docstring'''




       UpperCamelCase     : Dict	     =       YolosModelTester(self       )
       UpperCamelCase     : 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'''




       UpperCamelCase     ,   UpperCamelCase     : Union[str, Any]	     =       self.model_tester.prepare_config_and_inputs_for_common()

       for model_class in self.all_model_classes:
        UpperCamelCase     : int	     =       model_class(A_       )
        self.assertIsInstance(model.get_input_embeddings()	,							(nn.Module)       )
        UpperCamelCase     : Optional[int]	     =       model.get_output_embeddings()
        self.assertTrue(x is None or isinstance(A_	,							nn.Linear       )       )





      def 	__UpperCamelCase(			self       ):
       '''simple docstring'''




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

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

        UpperCamelCase     : List[str]	     =       ["pixel_values"]
        self.assertListEqual(arg_names[:1]	,							A_       )





      def 	__UpperCamelCase(			self       ):
       '''simple docstring'''




       UpperCamelCase     : Optional[Any]	     =       self.model_tester.prepare_config_and_inputs()
       self.model_tester.create_and_check_model(*A_       )





      def 	__UpperCamelCase(			self       ):
       '''simple docstring'''




       UpperCamelCase     ,   UpperCamelCase     : Any	     =       self.model_tester.prepare_config_and_inputs_for_common()
       UpperCamelCase     : str	     =       True

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

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

        UpperCamelCase     : int	     =       1
        self.assertEqual(out_len + added_hidden_states	,							len(A_       )       )

        UpperCamelCase     : Dict	     =       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_       ):
        UpperCamelCase     : Union[str, Any]	     =       model_class(A_       )
        model.to(A_       )
        model.eval()

        with torch.no_grad():
         UpperCamelCase     : Optional[Any]	     =       model(**self._prepare_for_class(A_	,							A_       )       )

        UpperCamelCase     : int	     =       outputs.hidden_states

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

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

       UpperCamelCase     ,   UpperCamelCase     : Optional[Any]	     =       self.model_tester.prepare_config_and_inputs_for_common()

       for model_class in self.all_model_classes:
        UpperCamelCase     : int	     =       True
        check_hidden_states_output(A_	,							A_	,							A_       )

        # check that output_hidden_states also work using config
        del inputs_dict["output_hidden_states"]
        UpperCamelCase     : Optional[int]	     =       True

        check_hidden_states_output(A_	,							A_	,							A_       )





      def 	__UpperCamelCase(			self       ):
       '''simple docstring'''




       UpperCamelCase     : int	     =       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]:
        UpperCamelCase     : Optional[int]	     =       YolosModel.from_pretrained(A_       )
        self.assertIsNotNone(A_       )



def 		A_    (					)						->			Dict:
 UpperCamelCase     : str	     =       Image.open("./tests/fixtures/tests_samples/COCO/000000039769.png"					)
 return image



@require_torch
@require_vision
class  A__       (	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'''




       UpperCamelCase     : Any	     =       YolosForObjectDetection.from_pretrained("hustvl/yolos-small"       ).to(A_       )

       UpperCamelCase     : Dict	     =       self.default_image_processor
       UpperCamelCase     : List[str]	     =       prepare_img()
       UpperCamelCase     : str	     =       image_processor(images=A_	,							return_tensors="pt"       ).to(A_       )

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

       # verify outputs
       UpperCamelCase     : Dict	     =       torch.Size((1, 100, 92)       )
       self.assertEqual(outputs.logits.shape	,							A_       )

       UpperCamelCase     : int	     =       torch.tensor(
           [[-24.02_48, -10.30_24, -14.82_90], [-42.03_92, -16.82_00, -27.43_34], [-27.27_43, -11.81_54, -18.71_48]]	,							device=A_	,							)
       UpperCamelCase     : List[Any]	     =       torch.tensor(
           [[0.25_59, 0.54_55, 0.47_06], [0.29_89, 0.72_79, 0.18_75], [0.77_32, 0.40_17, 0.44_62]]	,							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
       UpperCamelCase     : Optional[Any]	     =       image_processor.post_process_object_detection(
           A_	,							threshold=0.3	,							target_sizes=[image.size[::-1]]       )[0]
       UpperCamelCase     : List[Any]	     =       torch.tensor([0.99_94, 0.97_90, 0.99_64, 0.99_72, 0.98_61]       ).to(A_       )
       UpperCamelCase     : int	     =       [75, 75, 17, 63, 17]
       UpperCamelCase     : Optional[int]	     =       torch.tensor([3_35.06_09, 79.38_48, 3_75.42_16, 1_87.24_95]       ).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_       )       )







from typing import TYPE_CHECKING

from ...utils import (
    OptionalDependencyNotAvailable,
    _LazyModule,
    is_flax_available,
    is_tf_available,
    is_torch_available,
)


__lowerCamelCase	:					str			  =					{"""configuration_encoder_decoder""": ["""EncoderDecoderConfig"""]}

try:
    if not is_torch_available():
        raise OptionalDependencyNotAvailable()
except OptionalDependencyNotAvailable:
    pass
else:
    __lowerCamelCase	:					Optional[Any]			  =					["""EncoderDecoderModel"""]

try:
    if not is_tf_available():
        raise OptionalDependencyNotAvailable()
except OptionalDependencyNotAvailable:
    pass
else:
    __lowerCamelCase	:					Optional[Any]			  =					["""TFEncoderDecoderModel"""]

try:
    if not is_flax_available():
        raise OptionalDependencyNotAvailable()
except OptionalDependencyNotAvailable:
    pass
else:
    __lowerCamelCase	:					Union[str, Any]			  =					["""FlaxEncoderDecoderModel"""]

if TYPE_CHECKING:
    from .configuration_encoder_decoder import EncoderDecoderConfig

    try:
        if not is_torch_available():
            raise OptionalDependencyNotAvailable()
    except OptionalDependencyNotAvailable:
        pass
    else:
        from .modeling_encoder_decoder import EncoderDecoderModel

    try:
        if not is_tf_available():
            raise OptionalDependencyNotAvailable()
    except OptionalDependencyNotAvailable:
        pass
    else:
        from .modeling_tf_encoder_decoder import TFEncoderDecoderModel

    try:
        if not is_flax_available():
            raise OptionalDependencyNotAvailable()
    except OptionalDependencyNotAvailable:
        pass
    else:
        from .modeling_flax_encoder_decoder import FlaxEncoderDecoderModel

else:
    import sys

    __lowerCamelCase	:					Dict			  =					_LazyModule(__name__, globals()["""__file__"""], _import_structure, module_spec=__spec__)
