


from typing import TYPE_CHECKING

from ...utils import OptionalDependencyNotAvailable, _LazyModule, is_tokenizers_available, is_torch_available


_A		:				Optional[int]									=       {
    '''configuration_canine''': ['''CANINE_PRETRAINED_CONFIG_ARCHIVE_MAP''', '''CanineConfig'''],
    '''tokenization_canine''': ['''CanineTokenizer'''],
}

try:
   if not is_torch_available():
      raise OptionalDependencyNotAvailable()
except OptionalDependencyNotAvailable:
   pass
else:
   _A		:				Optional[Any]									=       [
       '''CANINE_PRETRAINED_MODEL_ARCHIVE_LIST''',
       '''CanineForMultipleChoice''',
       '''CanineForQuestionAnswering''',
       '''CanineForSequenceClassification''',
       '''CanineForTokenClassification''',
       '''CanineLayer''',
       '''CanineModel''',
       '''CaninePreTrainedModel''',
       '''load_tf_weights_in_canine''',
   ]


if TYPE_CHECKING:
   from .configuration_canine import CANINE_PRETRAINED_CONFIG_ARCHIVE_MAP, CanineConfig
   from .tokenization_canine import CanineTokenizer

   try:
      if not is_torch_available():
         raise OptionalDependencyNotAvailable()
   except OptionalDependencyNotAvailable:
      pass
   else:
      from .modeling_canine import (
          CANINE_PRETRAINED_MODEL_ARCHIVE_LIST,
          CanineForMultipleChoice,
          CanineForQuestionAnswering,
          CanineForSequenceClassification,
          CanineForTokenClassification,
          CanineLayer,
          CanineModel,
          CaninePreTrainedModel,
          load_tf_weights_in_canine,
      )


else:
   import sys

   _A		:				int									=       _LazyModule(__name__, globals()['''__file__'''], _import_structure, module_spec=__spec__)






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





     def  SCREAMING_SNAKE_CASE__       (    self					:				Optional[Any]							):
        __lowerCamelCase:				List[str]     =	floats_tensor([self.batch_size, self.num_channels, self.image_size[0], self.image_size[1]]							)

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

        __lowerCamelCase:				int     =	self.get_config()

        return config, pixel_values, labels





     def  SCREAMING_SNAKE_CASE__       (    self					:				Union[str, 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=SCREAMING_SNAKE_CASE_    ,	initializer_range=self.initializer_range    ,	num_detection_tokens=self.num_detection_tokens    ,	num_labels=self.num_labels    ,	)





     def  SCREAMING_SNAKE_CASE__       (    self					:				int    ,	SCREAMING_SNAKE_CASE_					:				str    ,	SCREAMING_SNAKE_CASE_					:				List[Any]    ,	SCREAMING_SNAKE_CASE_					:				Dict							):
        __lowerCamelCase:				List[Any]     =	YolosModel(config=SCREAMING_SNAKE_CASE_							)
        model.to(SCREAMING_SNAKE_CASE_							)
        model.eval()
        __lowerCamelCase:				Optional[int]     =	model(SCREAMING_SNAKE_CASE_							)
        self.parent.assertEqual(
            result.last_hidden_state.shape    ,	(self.batch_size, self.expected_seq_len, self.hidden_size)							)





     def  SCREAMING_SNAKE_CASE__       (    self					:				Optional[int]    ,	SCREAMING_SNAKE_CASE_					:				Optional[Any]    ,	SCREAMING_SNAKE_CASE_					:				List[Any]    ,	SCREAMING_SNAKE_CASE_					:				str							):
        __lowerCamelCase:				int     =	YolosForObjectDetection(SCREAMING_SNAKE_CASE_							)
        model.to(SCREAMING_SNAKE_CASE_							)
        model.eval()

        __lowerCamelCase:				List[Any]     =	model(pixel_values=SCREAMING_SNAKE_CASE_							)
        __lowerCamelCase:				str     =	model(SCREAMING_SNAKE_CASE_							)

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

        __lowerCamelCase:				Any     =	model(pixel_values=SCREAMING_SNAKE_CASE_    ,	labels=SCREAMING_SNAKE_CASE_							)

        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					:				List[Any]							):
        __lowerCamelCase:				Union[str, Any]     =	self.prepare_config_and_inputs()
        __lowerCamelCase   ,     __lowerCamelCase   ,     __lowerCamelCase:				Optional[int]     =	config_and_inputs
        __lowerCamelCase:				Optional[Any]     =	{"""pixel_values""": pixel_values}
        return config, inputs_dict



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

     UpperCAmelCase__ :  Dict						      =	False
     UpperCAmelCase__ :  Tuple						      =	False
     UpperCAmelCase__ :  str						      =	False
     UpperCAmelCase__ :  List[str]						      =	False





     def  SCREAMING_SNAKE_CASE__       (    self					:				Optional[Any]    ,	SCREAMING_SNAKE_CASE_					:				Optional[int]    ,	SCREAMING_SNAKE_CASE_					:				Any    ,	SCREAMING_SNAKE_CASE_					:				List[str]=False							):
        __lowerCamelCase:				Any     =	super()._prepare_for_class(SCREAMING_SNAKE_CASE_    ,	SCREAMING_SNAKE_CASE_    ,	return_labels=SCREAMING_SNAKE_CASE_							)

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

        return inputs_dict





     def  SCREAMING_SNAKE_CASE__       (    self					:				Dict							):
        __lowerCamelCase:				Dict     =	YolosModelTester(self							)
        __lowerCamelCase:				str     =	ConfigTester(self    ,	config_class=SCREAMING_SNAKE_CASE_    ,	has_text_modality=SCREAMING_SNAKE_CASE_    ,	hidden_size=37							)





     def  SCREAMING_SNAKE_CASE__       (    self					:				Optional[Any]							):
        self.config_tester.run_common_tests()





     def  SCREAMING_SNAKE_CASE__       (    self					:				Union[str, Any]							):
        # YOLOS does not use inputs_embeds
        pass





     def  SCREAMING_SNAKE_CASE__       (    self					:				int							):
        __lowerCamelCase   ,     __lowerCamelCase:				Optional[int]     =	self.model_tester.prepare_config_and_inputs_for_common()

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





     def  SCREAMING_SNAKE_CASE__       (    self					:				Any							):
        __lowerCamelCase   ,     __lowerCamelCase:				int     =	self.model_tester.prepare_config_and_inputs_for_common()

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

           __lowerCamelCase:				Optional[int]     =	["""pixel_values"""]
           self.assertListEqual(arg_names[:1]    ,	SCREAMING_SNAKE_CASE_							)





     def  SCREAMING_SNAKE_CASE__       (    self					:				Any							):
        __lowerCamelCase:				str     =	self.model_tester.prepare_config_and_inputs()
        self.model_tester.create_and_check_model(*SCREAMING_SNAKE_CASE_							)





     def  SCREAMING_SNAKE_CASE__       (    self					:				Any							):
        __lowerCamelCase   ,     __lowerCamelCase:				Any     =	self.model_tester.prepare_config_and_inputs_for_common()
        __lowerCamelCase:				str     =	True

        # in YOLOS, the seq_len is different
        __lowerCamelCase:				List[Any]     =	self.model_tester.expected_seq_len
        for model_class in self.all_model_classes:
           __lowerCamelCase:				Dict     =	True
           __lowerCamelCase:				Union[str, Any]     =	False
           __lowerCamelCase:				Any     =	True
           __lowerCamelCase:				str     =	model_class(SCREAMING_SNAKE_CASE_							)
           model.to(SCREAMING_SNAKE_CASE_							)
           model.eval()
           with torch.no_grad():
              __lowerCamelCase:				Tuple     =	model(**self._prepare_for_class(SCREAMING_SNAKE_CASE_    ,	SCREAMING_SNAKE_CASE_							)							)
           __lowerCamelCase:				str     =	outputs.attentions
           self.assertEqual(len(SCREAMING_SNAKE_CASE_							)    ,	self.model_tester.num_hidden_layers							)

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

           self.assertListEqual(
               list(attentions[0].shape[-3:]							)    ,	[self.model_tester.num_attention_heads, seq_len, seq_len]    ,	)
           __lowerCamelCase:				List[str]     =	len(SCREAMING_SNAKE_CASE_							)

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

           __lowerCamelCase:				Tuple     =	1
           self.assertEqual(out_len + added_hidden_states    ,	len(SCREAMING_SNAKE_CASE_							)							)

           __lowerCamelCase:				Any     =	outputs.attentions

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

           with torch.no_grad():
              __lowerCamelCase:				str     =	model(**self._prepare_for_class(SCREAMING_SNAKE_CASE_    ,	SCREAMING_SNAKE_CASE_							)							)

           __lowerCamelCase:				Any     =	outputs.hidden_states

           __lowerCamelCase:				int     =	getattr(
               self.model_tester    ,	"""expected_num_hidden_layers"""    ,	self.model_tester.num_hidden_layers + 1							)
           self.assertEqual(len(SCREAMING_SNAKE_CASE_							)    ,	SCREAMING_SNAKE_CASE_							)

           # YOLOS has a different seq_length
           __lowerCamelCase:				Optional[int]     =	self.model_tester.expected_seq_len

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

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

        for model_class in self.all_model_classes:
           __lowerCamelCase:				Any     =	True
           check_hidden_states_output(SCREAMING_SNAKE_CASE_    ,	SCREAMING_SNAKE_CASE_    ,	SCREAMING_SNAKE_CASE_							)

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

           check_hidden_states_output(SCREAMING_SNAKE_CASE_    ,	SCREAMING_SNAKE_CASE_    ,	SCREAMING_SNAKE_CASE_							)





     def  SCREAMING_SNAKE_CASE__       (    self					:				List[str]							):
        __lowerCamelCase:				int     =	self.model_tester.prepare_config_and_inputs()
        self.model_tester.create_and_check_for_object_detection(*SCREAMING_SNAKE_CASE_							)







     @slow
     def  SCREAMING_SNAKE_CASE__       (    self					:				Any							):
        for model_name in YOLOS_PRETRAINED_MODEL_ARCHIVE_LIST[:1]:
           __lowerCamelCase:				str     =	YolosModel.from_pretrained(SCREAMING_SNAKE_CASE_							)
           self.assertIsNotNone(SCREAMING_SNAKE_CASE_							)



def     __lowerCAmelCase						(							)       ->							Optional[Any]:
   __lowerCamelCase:				Optional[int]     =	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					:				str							):
        return AutoImageProcessor.from_pretrained("""hustvl/yolos-small"""							) if is_vision_available() else None







     @slow
     def  SCREAMING_SNAKE_CASE__       (    self					:				List[Any]							):
        __lowerCamelCase:				int     =	YolosForObjectDetection.from_pretrained("""hustvl/yolos-small"""							).to(SCREAMING_SNAKE_CASE_							)

        __lowerCamelCase:				List[Any]     =	self.default_image_processor
        __lowerCamelCase:				Optional[int]     =	prepare_img()
        __lowerCamelCase:				Optional[Any]     =	image_processor(images=SCREAMING_SNAKE_CASE_    ,	return_tensors="""pt"""							).to(SCREAMING_SNAKE_CASE_							)

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

        # verify outputs
        __lowerCamelCase:				Optional[int]     =	torch.Size((1, 100, 92)							)
        self.assertEqual(outputs.logits.shape    ,	SCREAMING_SNAKE_CASE_							)

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

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

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


