



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 				_snake_case			:




    def __init__(						self					:						List[Any],					__lowercase					:						List[Any],					__lowercase					:						Optional[Any]=13,					__lowercase					:						Dict=[30, 30],					__lowercase					:						int=2,					__lowercase					:						Optional[int]=3,					__lowercase					:						int=True,					__lowercase					:						List[str]=True,					__lowercase					:						Dict=32,					__lowercase					:						List[str]=5,					__lowercase					:						Union[str, Any]=4,					__lowercase					:						Union[str, Any]=37,					__lowercase					:						Any="gelu",					__lowercase					:						int=0.1,					__lowercase					:						List[str]=0.1,					__lowercase					:						int=10,					__lowercase					:						Tuple=0.02,					__lowercase					:						Dict=3,					__lowercase					:						Dict=None,					__lowercase					:						List[Any]=8,					__lowercase					:						Optional[Any]=10,					):
       lowercase__					  =				parent
       lowercase__					  =				batch_size
       lowercase__					  =				image_size
       lowercase__					  =				patch_size
       lowercase__					  =				num_channels
       lowercase__					  =				is_training
       lowercase__					  =				use_labels
       lowercase__					  =				hidden_size
       lowercase__					  =				num_hidden_layers
       lowercase__					  =				num_attention_heads
       lowercase__					  =				intermediate_size
       lowercase__					  =				hidden_act
       lowercase__					  =				hidden_dropout_prob
       lowercase__					  =				attention_probs_dropout_prob
       lowercase__					  =				type_sequence_label_size
       lowercase__					  =				initializer_range
       lowercase__					  =				num_labels
       lowercase__					  =				scope
       lowercase__					  =				n_targets
       lowercase__					  =				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
       lowercase__					  =				(image_size[1] // patch_size) * (image_size[0] // patch_size)
       lowercase__					  =				num_patches + 1 + self.num_detection_tokens




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

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

       lowercase__					  =				self.get_config()

       return config, pixel_values, labels




    def 							A__      (						self					:						List[str]						):
       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=__lowercase,					initializer_range=self.initializer_range,					num_detection_tokens=self.num_detection_tokens,					num_labels=self.num_labels,					)




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




    def 							A__      (						self					:						Any,					__lowercase					:						Tuple,					__lowercase					:						int,					__lowercase					:						List[str]						):
       lowercase__					  =				YolosForObjectDetection(__lowercase						)
       model.to(__lowercase						)
       model.eval()

       lowercase__					  =				model(pixel_values=__lowercase						)
       lowercase__					  =				model(__lowercase						)

       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)						)

       lowercase__					  =				model(pixel_values=__lowercase,					labels=__lowercase						)

       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 							A__      (						self					:						Optional[int]						):
       lowercase__					  =				self.prepare_config_and_inputs()
       lowercase__					  =				config_and_inputs
       lowercase__					  =				{'''pixel_values''': pixel_values}
       return config, inputs_dict
@require_torch
class 				_snake_case			(					UpperCamelCase_    ,	UpperCamelCase_    ,	unittest.TestCase):
    UpperCamelCase__				:					Any     		=(YolosModel, YolosForObjectDetection) if is_torch_available() else ()
    UpperCamelCase__				:					Tuple     		=(
        {"""feature-extraction""": YolosModel, """object-detection""": YolosForObjectDetection} if is_torch_available() else {}
    )

    UpperCamelCase__				:					Any     		=False
    UpperCamelCase__				:					Any     		=False
    UpperCamelCase__				:					Any     		=False
    UpperCamelCase__				:					int     		=False




    def 							A__      (						self					:						Tuple,					__lowercase					:						Dict,					__lowercase					:						Tuple,					__lowercase					:						Optional[Any]=False						):
       lowercase__					  =				super()._prepare_for_class(__lowercase,					__lowercase,					return_labels=__lowercase						)

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

       return inputs_dict




    def 							A__      (						self					:						str						):
       lowercase__					  =				YolosModelTester(self						)
       lowercase__					  =				ConfigTester(self,					config_class=__lowercase,					has_text_modality=__lowercase,					hidden_size=37						)




    def 							A__      (						self					:						Tuple						):
       self.config_tester.run_common_tests()




    def 							A__      (						self					:						Any						):
       # YOLOS does not use inputs_embeds
       pass




    def 							A__      (						self					:						Optional[Any]						):
       lowercase__					  =				self.model_tester.prepare_config_and_inputs_for_common()

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




    def 							A__      (						self					:						List[Any]						):
       lowercase__					  =				self.model_tester.prepare_config_and_inputs_for_common()

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

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




    def 							A__      (						self					:						Tuple						):
       lowercase__					  =				self.model_tester.prepare_config_and_inputs()
       self.model_tester.create_and_check_model(*__lowercase						)




    def 							A__      (						self					:						Optional[Any]						):
       lowercase__					  =				self.model_tester.prepare_config_and_inputs_for_common()
       lowercase__					  =				True

       # in YOLOS, the seq_len is different
       lowercase__					  =				self.model_tester.expected_seq_len
       for model_class in self.all_model_classes:
          lowercase__					  =				True
          lowercase__					  =				False
          lowercase__					  =				True
          lowercase__					  =				model_class(__lowercase						)
          model.to(__lowercase						)
          model.eval()
          with torch.no_grad():
             lowercase__					  =				model(**self._prepare_for_class(__lowercase,					__lowercase						)						)
          lowercase__					  =				outputs.attentions
          self.assertEqual(len(__lowercase						),					self.model_tester.num_hidden_layers						)

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

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

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

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

          lowercase__					  =				outputs.attentions

          self.assertEqual(len(__lowercase						),					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 							A__      (						self					:						Optional[Any]						):
       def check_hidden_states_output(__lowercase					:						List[Any],					__lowercase					:						List[str],					__lowercase					:						List[str]						):
          lowercase__					  =				model_class(__lowercase						)
          model.to(__lowercase						)
          model.eval()

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

          lowercase__					  =				outputs.hidden_states

          lowercase__					  =				getattr(
              self.model_tester,					"expected_num_hidden_layers",					self.model_tester.num_hidden_layers + 1						)
          self.assertEqual(len(__lowercase						),					__lowercase						)

          # YOLOS has a different seq_length
          lowercase__					  =				self.model_tester.expected_seq_len

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

       lowercase__					  =				self.model_tester.prepare_config_and_inputs_for_common()

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

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

          check_hidden_states_output(__lowercase,					__lowercase,					__lowercase						)




    def 							A__      (						self					:						List[Any]						):
       lowercase__					  =				self.model_tester.prepare_config_and_inputs()
       self.model_tester.create_and_check_for_object_detection(*__lowercase						)




    @slow
    def 							A__      (						self					:						Any						):
       for model_name in YOLOS_PRETRAINED_MODEL_ARCHIVE_LIST[:1]:
          lowercase__					  =				YolosModel.from_pretrained(__lowercase						)
          self.assertIsNotNone(__lowercase						)



def __lowerCAmelCase (     ):
   lowercase__					  =				Image.open("./tests/fixtures/tests_samples/COCO/000000039769.png"  )
   return image




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




    @cached_property
    def 							A__      (						self					:						List[str]						):
       return AutoImageProcessor.from_pretrained("hustvl/yolos-small"						) if is_vision_available() else None




    @slow
    def 							A__      (						self					:						int						):
       lowercase__					  =				YolosForObjectDetection.from_pretrained("hustvl/yolos-small"						).to(__lowercase						)

       lowercase__					  =				self.default_image_processor
       lowercase__					  =				prepare_img()
       lowercase__					  =				image_processor(images=__lowercase,					return_tensors="pt"						).to(__lowercase						)

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

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

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

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

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









# 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


lowercase_								=     {
    """configuration_xmod""": [
        """XMOD_PRETRAINED_CONFIG_ARCHIVE_MAP""",
        """XmodConfig""",
        """XmodOnnxConfig""",
    ],
}

try:
							if not is_torch_available():
														raise OptionalDependencyNotAvailable()
except OptionalDependencyNotAvailable:
							pass
else:
							lowercase_								=     [
							    """XMOD_PRETRAINED_MODEL_ARCHIVE_LIST""",
							    """XmodForCausalLM""",
							    """XmodForMaskedLM""",
							    """XmodForMultipleChoice""",
							    """XmodForQuestionAnswering""",
							    """XmodForSequenceClassification""",
							    """XmodForTokenClassification""",
							    """XmodModel""",
							    """XmodPreTrainedModel""",
							]

if TYPE_CHECKING:
							from .configuration_xmod import XMOD_PRETRAINED_CONFIG_ARCHIVE_MAP, XmodConfig, XmodOnnxConfig

							try:
														if not is_torch_available():
																					raise OptionalDependencyNotAvailable()
							except OptionalDependencyNotAvailable:
														pass
							else:
														from .modeling_xmod import (
														    XMOD_PRETRAINED_MODEL_ARCHIVE_LIST,
														    XmodForCausalLM,
														    XmodForMaskedLM,
														    XmodForMultipleChoice,
														    XmodForQuestionAnswering,
														    XmodForSequenceClassification,
														    XmodForTokenClassification,
														    XmodModel,
														    XmodPreTrainedModel,
														)

else:
							import sys

							lowercase_								=     _LazyModule(__name__, globals()["""__file__"""], _import_structure, module_spec=__spec__)




