




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






     def     _lowercase     (			self   )							->      Optional[int]:
          _snake_case							=				floats_tensor([self.batch_size, self.num_channels, self.image_size[0], self.image_size[1]]   )

          _snake_case							=				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							=				[]
               for i in range(self.batch_size   ):
                    _snake_case							=				{}
                    _snake_case							=				torch.randint(
                        high=self.num_labels ,size=(self.n_targets,) ,device=_SCREAMING_SNAKE_CASE   )
                    _snake_case							=				torch.rand(self.n_targets ,4 ,device=_SCREAMING_SNAKE_CASE   )
                    labels.append(_SCREAMING_SNAKE_CASE   )

          _snake_case							=				self.get_config()

          return config, pixel_values, labels






     def     _lowercase     (			self   )							->      Dict:
          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     _lowercase     (			self ,_SCREAMING_SNAKE_CASE ,_SCREAMING_SNAKE_CASE ,_SCREAMING_SNAKE_CASE   )							->      List[str]:
          _snake_case							=				YolosModel(config=_SCREAMING_SNAKE_CASE   )
          model.to(_SCREAMING_SNAKE_CASE   )
          model.eval()
          _snake_case							=				model(_SCREAMING_SNAKE_CASE   )
          self.parent.assertEqual(
              result.last_hidden_state.shape ,(self.batch_size, self.expected_seq_len, self.hidden_size)   )






     def     _lowercase     (			self ,_SCREAMING_SNAKE_CASE ,_SCREAMING_SNAKE_CASE ,_SCREAMING_SNAKE_CASE   )							->      Union[str, Any]:
          _snake_case							=				YolosForObjectDetection(_SCREAMING_SNAKE_CASE   )
          model.to(_SCREAMING_SNAKE_CASE   )
          model.eval()

          _snake_case							=				model(pixel_values=_SCREAMING_SNAKE_CASE   )
          _snake_case							=				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)   )

          _snake_case							=				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     _lowercase     (			self   )							->      Any:
          _snake_case							=				self.prepare_config_and_inputs()
          _snake_case							=				config_and_inputs
          _snake_case							=				{'''pixel_values''': pixel_values}
          return config, inputs_dict







@require_torch
class        _a    (						__lowerCAmelCase , __lowerCAmelCase , unittest.TestCase							):
     SCREAMING_SNAKE_CASE_							:   List[str]       =						(YolosModel, YolosForObjectDetection) if is_torch_available() else ()
     SCREAMING_SNAKE_CASE_							:   Union[str, Any]       =						(
         {"""feature-extraction""": YolosModel, """object-detection""": YolosForObjectDetection} if is_torch_available() else {}
     )

     SCREAMING_SNAKE_CASE_							:   List[str]       =						False
     SCREAMING_SNAKE_CASE_							:   str       =						False
     SCREAMING_SNAKE_CASE_							:   Any       =						False
     SCREAMING_SNAKE_CASE_							:   Dict       =						False






     def     _lowercase     (			self ,_SCREAMING_SNAKE_CASE ,_SCREAMING_SNAKE_CASE ,_SCREAMING_SNAKE_CASE=False   )							->      Any:
          _snake_case							=				super()._prepare_for_class(_SCREAMING_SNAKE_CASE ,_SCREAMING_SNAKE_CASE ,return_labels=_SCREAMING_SNAKE_CASE   )

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

          return inputs_dict






     def     _lowercase     (			self   )							->      int:
          _snake_case							=				YolosModelTester(self   )
          _snake_case							=				ConfigTester(self ,config_class=_SCREAMING_SNAKE_CASE ,has_text_modality=_SCREAMING_SNAKE_CASE ,hidden_size=37   )






     def     _lowercase     (			self   )							->      Optional[Any]:
          self.config_tester.run_common_tests()






     def     _lowercase     (			self   )							->      Tuple:
          pass






     def     _lowercase     (			self   )							->      Dict:
          _snake_case							=				self.model_tester.prepare_config_and_inputs_for_common()

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






     def     _lowercase     (			self   )							->      Optional[int]:
          _snake_case							=				self.model_tester.prepare_config_and_inputs_for_common()

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

               _snake_case							=				['''pixel_values''']
               self.assertListEqual(arg_names[:1] ,_SCREAMING_SNAKE_CASE   )






     def     _lowercase     (			self   )							->      List[Any]:
          _snake_case							=				self.model_tester.prepare_config_and_inputs()
          self.model_tester.create_and_check_model(*_SCREAMING_SNAKE_CASE   )






     def     _lowercase     (			self   )							->      Dict:
          _snake_case							=				self.model_tester.prepare_config_and_inputs_for_common()
          _snake_case							=				True

          # in YOLOS, the seq_len is different
          _snake_case							=				self.model_tester.expected_seq_len
          for model_class in self.all_model_classes:
               _snake_case							=				True
               _snake_case							=				False
               _snake_case							=				True
               _snake_case							=				model_class(_SCREAMING_SNAKE_CASE   )
               model.to(_SCREAMING_SNAKE_CASE   )
               model.eval()
               with torch.no_grad():
                    _snake_case							=				model(**self._prepare_for_class(_SCREAMING_SNAKE_CASE ,_SCREAMING_SNAKE_CASE   )   )
               _snake_case							=				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"]
               _snake_case							=				True
               _snake_case							=				model_class(_SCREAMING_SNAKE_CASE   )
               model.to(_SCREAMING_SNAKE_CASE   )
               model.eval()
               with torch.no_grad():
                    _snake_case							=				model(**self._prepare_for_class(_SCREAMING_SNAKE_CASE ,_SCREAMING_SNAKE_CASE   )   )
               _snake_case							=				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] ,)
               _snake_case							=				len(_SCREAMING_SNAKE_CASE   )

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

               _snake_case							=				1
               self.assertEqual(out_len + added_hidden_states ,len(_SCREAMING_SNAKE_CASE   )   )

               _snake_case							=				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     _lowercase     (			self   )							->      List[str]:





          def check_hidden_states_output(_SCREAMING_SNAKE_CASE ,_SCREAMING_SNAKE_CASE ,_SCREAMING_SNAKE_CASE   ):
               _snake_case							=				model_class(_SCREAMING_SNAKE_CASE   )
               model.to(_SCREAMING_SNAKE_CASE   )
               model.eval()

               with torch.no_grad():
                    _snake_case							=				model(**self._prepare_for_class(_SCREAMING_SNAKE_CASE ,_SCREAMING_SNAKE_CASE   )   )

               _snake_case							=				outputs.hidden_states

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

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

          _snake_case							=				self.model_tester.prepare_config_and_inputs_for_common()

          for model_class in self.all_model_classes:
               _snake_case							=				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"]
               _snake_case							=				True

               check_hidden_states_output(_SCREAMING_SNAKE_CASE ,_SCREAMING_SNAKE_CASE ,_SCREAMING_SNAKE_CASE   )






     def     _lowercase     (			self   )							->      Optional[int]:
          _snake_case							=				self.model_tester.prepare_config_and_inputs()
          self.model_tester.create_and_check_for_object_detection(*_SCREAMING_SNAKE_CASE   )






     @slow
     def     _lowercase     (			self   )							->      str:





          for model_name in YOLOS_PRETRAINED_MODEL_ARCHIVE_LIST[:1]:
               _snake_case							=				YolosModel.from_pretrained(_SCREAMING_SNAKE_CASE   )
               self.assertIsNotNone(_SCREAMING_SNAKE_CASE   )







def      __a     (       )						->			Optional[Any]:

     """simple docstring"""




     _snake_case							=				Image.open("./tests/fixtures/tests_samples/COCO/000000039769.png"   )
     return image





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






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






     @slow
     def     _lowercase     (			self   )							->      int:
          _snake_case							=				YolosForObjectDetection.from_pretrained("hustvl/yolos-small"   ).to(_SCREAMING_SNAKE_CASE   )

          _snake_case							=				self.default_image_processor
          _snake_case							=				prepare_img()
          _snake_case							=				image_processor(images=_SCREAMING_SNAKE_CASE ,return_tensors="pt"   ).to(_SCREAMING_SNAKE_CASE   )

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

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

          _snake_case							=				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=_SCREAMING_SNAKE_CASE ,)
          _snake_case							=				torch.tensor(
              [[0.2_5_5_9, 0.5_4_5_5, 0.4_7_0_6], [0.2_9_8_9, 0.7_2_7_9, 0.1_8_7_5], [0.7_7_3_2, 0.4_0_1_7, 0.4_4_6_2]] ,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
          _snake_case							=				image_processor.post_process_object_detection(
              _SCREAMING_SNAKE_CASE ,threshold=0.3 ,target_sizes=[image.size[::-1]]   )[0]
          _snake_case							=				torch.tensor([0.9_9_9_4, 0.9_7_9_0, 0.9_9_6_4, 0.9_9_7_2, 0.9_8_6_1]   ).to(_SCREAMING_SNAKE_CASE   )
          _snake_case							=				[75, 75, 17, 63, 17]
          _snake_case							=				torch.tensor([335.0_609, 79.3_848, 375.4_216, 187.2_495]   ).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   )   )








'''simple docstring'''





import functools
import operator

from ...configuration_utils import PretrainedConfig
from ...utils import logging


UpperCamelCase_						:      str       =						logging.get_logger(__name__)

UpperCamelCase_						:      Optional[Any]       =						{
    '''asapp/sew-tiny-100k''': '''https://huggingface.co/asapp/sew-tiny-100k/resolve/main/config.json''',
    # See all SEW models at https://huggingface.co/models?filter=sew
}

class        _a    (						__lowerCAmelCase							):
     SCREAMING_SNAKE_CASE_							:   Dict       =						"""sew"""






     def __init__(			self ,_SCREAMING_SNAKE_CASE=32 ,_SCREAMING_SNAKE_CASE=768 ,_SCREAMING_SNAKE_CASE=12 ,_SCREAMING_SNAKE_CASE=12 ,_SCREAMING_SNAKE_CASE=3_072 ,_SCREAMING_SNAKE_CASE=2 ,_SCREAMING_SNAKE_CASE="gelu" ,_SCREAMING_SNAKE_CASE=0.1 ,_SCREAMING_SNAKE_CASE=0.1 ,_SCREAMING_SNAKE_CASE=0.1 ,_SCREAMING_SNAKE_CASE=0.0 ,_SCREAMING_SNAKE_CASE=0.1 ,_SCREAMING_SNAKE_CASE=0.1 ,_SCREAMING_SNAKE_CASE=0.0_2 ,_SCREAMING_SNAKE_CASE=1e-5 ,_SCREAMING_SNAKE_CASE="group" ,_SCREAMING_SNAKE_CASE="gelu" ,_SCREAMING_SNAKE_CASE=(64, 128, 128, 128, 128, 256, 256, 256, 256, 512, 512, 512, 512) ,_SCREAMING_SNAKE_CASE=(5, 2, 1, 2, 1, 2, 1, 2, 1, 2, 1, 2, 1) ,_SCREAMING_SNAKE_CASE=(10, 3, 1, 3, 1, 3, 1, 3, 1, 2, 1, 2, 1) ,_SCREAMING_SNAKE_CASE=False ,_SCREAMING_SNAKE_CASE=128 ,_SCREAMING_SNAKE_CASE=16 ,_SCREAMING_SNAKE_CASE=True ,_SCREAMING_SNAKE_CASE=0.0_5 ,_SCREAMING_SNAKE_CASE=10 ,_SCREAMING_SNAKE_CASE=2 ,_SCREAMING_SNAKE_CASE=0.0 ,_SCREAMING_SNAKE_CASE=10 ,_SCREAMING_SNAKE_CASE=0 ,_SCREAMING_SNAKE_CASE="mean" ,_SCREAMING_SNAKE_CASE=False ,_SCREAMING_SNAKE_CASE=False ,_SCREAMING_SNAKE_CASE=256 ,_SCREAMING_SNAKE_CASE=0 ,_SCREAMING_SNAKE_CASE=1 ,_SCREAMING_SNAKE_CASE=2 ,**_SCREAMING_SNAKE_CASE ,)							->      str:
          super().__init__(**_SCREAMING_SNAKE_CASE ,pad_token_id=_SCREAMING_SNAKE_CASE ,bos_token_id=_SCREAMING_SNAKE_CASE ,eos_token_id=_SCREAMING_SNAKE_CASE   )
          _snake_case							=				hidden_size
          _snake_case							=				feat_extract_norm
          _snake_case							=				feat_extract_activation
          _snake_case							=				list(_SCREAMING_SNAKE_CASE   )
          _snake_case							=				list(_SCREAMING_SNAKE_CASE   )
          _snake_case							=				list(_SCREAMING_SNAKE_CASE   )
          _snake_case							=				conv_bias
          _snake_case							=				num_conv_pos_embeddings
          _snake_case							=				num_conv_pos_embedding_groups
          _snake_case							=				len(self.conv_dim   )
          _snake_case							=				num_hidden_layers
          _snake_case							=				intermediate_size
          _snake_case							=				squeeze_factor
          _snake_case							=				hidden_act
          _snake_case							=				num_attention_heads
          _snake_case							=				hidden_dropout
          _snake_case							=				attention_dropout
          _snake_case							=				activation_dropout
          _snake_case							=				feat_proj_dropout
          _snake_case							=				final_dropout
          _snake_case							=				layerdrop
          _snake_case							=				layer_norm_eps
          _snake_case							=				initializer_range
          _snake_case							=				vocab_size

          if (
              (len(self.conv_stride   ) != self.num_feat_extract_layers)
              or (len(self.conv_kernel   ) != self.num_feat_extract_layers)
              or (len(self.conv_dim   ) != self.num_feat_extract_layers)
          ):
               raise ValueError(
                   "Configuration for convolutional layers is incorrect."
                   "It is required that `len(config.conv_dim)` == `len(config.conv_stride)` == `len(config.conv_kernel)`,"
                   f"""but is `len(config.conv_dim) = {len(self.conv_dim   )}`, `len(config.conv_stride)"""
                   f"""= {len(self.conv_stride   )}`, `len(config.conv_kernel) = {len(self.conv_kernel   )}`."""   )

          # fine-tuning config parameters for SpecAugment: https://arxiv.org/abs/1904.08779
          _snake_case							=				apply_spec_augment
          _snake_case							=				mask_time_prob
          _snake_case							=				mask_time_length
          _snake_case							=				mask_time_min_masks
          _snake_case							=				mask_feature_prob
          _snake_case							=				mask_feature_length
          _snake_case							=				mask_feature_min_masks

          # ctc loss
          _snake_case							=				ctc_loss_reduction
          _snake_case							=				ctc_zero_infinity

          # sequence classification
          _snake_case							=				use_weighted_layer_sum
          _snake_case							=				classifier_proj_size






     @property
     def     _lowercase     (			self   )							->      Optional[Any]:
          return functools.reduce(operator.mul ,self.conv_stride ,1   )


