
import inspect
import unittest
from typing import List

import numpy as np

from transformers import EfficientFormerConfig
from transformers.testing_utils import require_tf, require_vision, slow
from transformers.utils import cached_property, is_tf_available, is_vision_available

from ...test_configuration_common import ConfigTester
from ...test_modeling_tf_common import TFModelTesterMixin, floats_tensor, ids_tensor
from ...test_pipeline_mixin import PipelineTesterMixin


if is_tf_available():
    import tensorflow as tf

    from transformers import (
        TFEfficientFormerForImageClassification,
        TFEfficientFormerForImageClassificationWithTeacher,
        TFEfficientFormerModel,
    )
    from transformers.models.efficientformer.modeling_tf_efficientformer import (
        TF_EFFICIENTFORMER_PRETRAINED_MODEL_ARCHIVE_LIST,
    )


if is_vision_available():
    from PIL import Image

    from transformers import EfficientFormerImageProcessor






class      _UpperCAmelCase				:
    def __init__(    self						,    snake_case_						,    snake_case_ = 13						,    snake_case_ = 64						,    snake_case_ = 2						,    snake_case_ = 3						,    snake_case_ = 3						,    snake_case_ = True						,    snake_case_ = True						,    snake_case_ = 1_28						,    snake_case_=[16, 32, 64, 1_28]						,    snake_case_ = 7						,    snake_case_ = 4						,    snake_case_ = 37						,    snake_case_ = "gelu"						,    snake_case_ = 0.1						,    snake_case_ = 0.1						,    snake_case_ = 10						,    snake_case_ = 0.02						,    snake_case_ = 2						,    snake_case_ = 1						,    snake_case_ = 1_28						,    snake_case_ = [2, 2, 2, 2]						,    snake_case_ = 2						,    snake_case_ = 2						,    ):
      _snake_case     :						str						=   parent
      _snake_case     :						List[Any]						=   batch_size
      _snake_case     :						Dict						=   image_size
      _snake_case     :						Dict						=   patch_size
      _snake_case     :						Optional[int]						=   num_channels
      _snake_case     :						List[str]						=   is_training
      _snake_case     :						int						=   use_labels
      _snake_case     :						Tuple						=   hidden_size
      _snake_case     :						str						=   num_hidden_layers
      _snake_case     :						Tuple						=   num_attention_heads
      _snake_case     :						List[str]						=   intermediate_size
      _snake_case     :						Optional[Any]						=   hidden_act
      _snake_case     :						Tuple						=   hidden_dropout_prob
      _snake_case     :						List[Any]						=   attention_probs_dropout_prob
      _snake_case     :						List[str]						=   type_sequence_label_size
      _snake_case     :						int						=   initializer_range
      _snake_case     :						List[Any]						=   encoder_stride
      _snake_case     :						Optional[int]						=   num_attention_outputs
      _snake_case     :						Optional[Any]						=   embed_dim
      _snake_case     :						Union[str, Any]						=   embed_dim + 1
      _snake_case     :						Union[str, Any]						=   resolution
      _snake_case     :						Tuple						=   depths
      _snake_case     :						Any						=   hidden_sizes
      _snake_case     :						int						=   dim
      _snake_case     :						str						=   mlp_expansion_ratio
    def 					lowerCamelCase__	(    self     ):
      _snake_case     :						List[str]						=   floats_tensor([self.batch_size, self.num_channels, self.image_size, self.image_size]     )

      _snake_case     :						int						=   None
      if self.use_labels:
        _snake_case     :						int						=   ids_tensor([self.batch_size]						,    self.type_sequence_label_size     )

      _snake_case     :						str						=   self.get_config()

      return config, pixel_values, labels
    def 					lowerCamelCase__	(    self     ):
      return EfficientFormerConfig(
          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=snake_case_						,    initializer_range=self.initializer_range						,    encoder_stride=self.encoder_stride						,    resolution=self.resolution						,    depths=self.depths						,    hidden_sizes=self.hidden_sizes						,    dim=self.dim						,    mlp_expansion_ratio=self.mlp_expansion_ratio						,    )
    def 					lowerCamelCase__	(    self						,    snake_case_						,    snake_case_						,    snake_case_     ):
      _snake_case     :						Any						=   TFEfficientFormerModel(config=snake_case_     )
      _snake_case     :						Tuple						=   model(snake_case_						,    training=snake_case_     )
      self.parent.assertEqual(result.last_hidden_state.shape						,    (self.batch_size, self.seq_length, self.hidden_size)     )
    def 					lowerCamelCase__	(    self						,    snake_case_						,    snake_case_						,    snake_case_     ):
      _snake_case     :						List[Any]						=   self.type_sequence_label_size
      _snake_case     :						Any						=   TFEfficientFormerForImageClassification(snake_case_     )
      _snake_case     :						Tuple						=   model(snake_case_						,    labels=snake_case_						,    training=snake_case_     )
      self.parent.assertEqual(result.logits.shape						,    (self.batch_size, self.type_sequence_label_size)     )

      # test greyscale images
      _snake_case     :						Tuple						=   1
      _snake_case     :						Optional[Any]						=   TFEfficientFormerForImageClassification(snake_case_     )

      _snake_case     :						Tuple						=   floats_tensor([self.batch_size, 1, self.image_size, self.image_size]     )
      _snake_case     :						Tuple						=   model(snake_case_						,    labels=snake_case_     )
      self.parent.assertEqual(result.logits.shape						,    (self.batch_size, self.type_sequence_label_size)     )


    def 					lowerCamelCase__	(    self     ):
      _snake_case     :						str						=   self.prepare_config_and_inputs()
      _snake_case     :						Optional[Any]						=   config_and_inputs
      _snake_case     :						Any						=   {"pixel_values": pixel_values}
      return config, inputs_dict






@require_tf
class      _UpperCAmelCase				(					_snake_case		,					_snake_case		,					unittest.TestCase):
    __lowercase							: Tuple  =					(
        (
            TFEfficientFormerModel,
            TFEfficientFormerForImageClassificationWithTeacher,
            TFEfficientFormerForImageClassification,
        )
        if is_tf_available()
        else ()
    )
    __lowercase							: Optional[Any]  =					(
        {
            """feature-extraction""": TFEfficientFormerModel,
            """image-classification""": (
                TFEfficientFormerForImageClassification,
                TFEfficientFormerForImageClassificationWithTeacher,
            ),
        }
        if is_tf_available()
        else {}
    )

    __lowercase							: str  =					False

    __lowercase							: str  =					False
    __lowercase							: str  =					False
    __lowercase							: str  =					False
    __lowercase							: Optional[int]  =					False
    def 					lowerCamelCase__	(    self     ):
      _snake_case     :						List[Any]						=   TFEfficientFormerModelTester(self     )
      _snake_case     :						Optional[int]						=   ConfigTester(
          self						,    config_class=snake_case_						,    has_text_modality=snake_case_						,    hidden_size=37     )
    def 					lowerCamelCase__	(    self     ):
      self.config_tester.run_common_tests()
    @unittest.skip(reason="EfficientFormer does not use inputs_embeds"     )
    def 					lowerCamelCase__	(    self     ):
      pass
    @unittest.skip(reason="EfficientFormer does not support input and output embeddings"     )
    def 					lowerCamelCase__	(    self     ):
      pass
    def 					lowerCamelCase__	(    self     ):
      _snake_case     :						List[str]						=   self.model_tester.prepare_config_and_inputs_for_common()

      for model_class in self.all_model_classes:
        _snake_case     :						List[str]						=   model_class(snake_case_     )
        _snake_case     :						Union[str, Any]						=   inspect.signature(model.call     )
        # signature.parameters is an OrderedDict => so arg_names order is deterministic
        _snake_case     :						Optional[Any]						=   [*signature.parameters.keys()]

        _snake_case     :						Optional[Any]						=   ["pixel_values"]
        self.assertListEqual(arg_names[:1]						,    snake_case_     )
    def 					lowerCamelCase__	(    self     ):
      def check_hidden_states_output(snake_case_						,    snake_case_						,    snake_case_     ):
        _snake_case     :						str						=   model_class(snake_case_     )

        _snake_case     :						Dict						=   model(**self._prepare_for_class(snake_case_						,    snake_case_     )						,    training=snake_case_     )
        _snake_case     :						Tuple						=   outputs.encoder_hidden_states if config.is_encoder_decoder else outputs.hidden_states

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

        if hasattr(self.model_tester						,    "encoder_seq_length"     ):
          _snake_case     :						List[Any]						=   self.model_tester.encoder_seq_length
          if hasattr(self.model_tester						,    "chunk_length"     ) and self.model_tester.chunk_length > 1:
            _snake_case     :						List[Any]						=   seq_length * self.model_tester.chunk_length
        else:
          _snake_case     :						List[str]						=   self.model_tester.seq_length

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

        if config.is_encoder_decoder:
          _snake_case     :						List[str]						=   outputs.decoder_hidden_states

          self.asseretIsInstance(snake_case_						,    (list, tuple)     )
          self.assertEqual(len(snake_case_     )						,    snake_case_     )
          _snake_case     :						List[Any]						=   getattr(self.model_tester						,    "seq_length"						,    snake_case_     )
          _snake_case     :						List[Any]						=   getattr(self.model_tester						,    "decoder_seq_length"						,    snake_case_     )

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

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

      for model_class in self.all_model_classes:
        _snake_case     :						str						=   True
        check_hidden_states_output(snake_case_						,    snake_case_						,    snake_case_     )

        # check that output_hidden_states also work using config
        del inputs_dict["output_hidden_states"]
        _snake_case     :						List[str]						=   True

        check_hidden_states_output(snake_case_						,    snake_case_						,    snake_case_     )
    def 					lowerCamelCase__	(    self						,    snake_case_						,    snake_case_						,    snake_case_=False     ):
      _snake_case     :						List[str]						=   super()._prepare_for_class(snake_case_						,    snake_case_						,    return_labels=snake_case_     )

      if return_labels:
        if model_class.__name__ == "TFEfficientFormerForImageClassificationWithTeacher":
          del inputs_dict["labels"]

      return inputs_dict
    def 					lowerCamelCase__	(    self     ):
      _snake_case     :						Dict						=   self.model_tester.prepare_config_and_inputs()
      self.model_tester.create_and_check_model(*snake_case_     )
    @unittest.skip(reason="EfficientFormer does not implement masked image modeling yet"     )
    def 					lowerCamelCase__	(    self     ):
      _snake_case     :						List[str]						=   self.model_tester.prepare_config_and_inputs()
      self.model_tester.create_and_check_for_masked_image_modeling(*snake_case_     )
    def 					lowerCamelCase__	(    self     ):
      _snake_case     :						Dict						=   self.model_tester.prepare_config_and_inputs()
      self.model_tester.create_and_check_for_image_classification(*snake_case_     )
    @slow
    def 					lowerCamelCase__	(    self     ):
      for model_name in TF_EFFICIENTFORMER_PRETRAINED_MODEL_ARCHIVE_LIST[:1]:
        _snake_case     :						Optional[int]						=   TFEfficientFormerModel.from_pretrained(snake_case_     )
        self.assertIsNotNone(snake_case_     )
    def 					lowerCamelCase__	(    self     ):
      _snake_case     :						Any						=   self.model_tester.prepare_config_and_inputs_for_common()
      _snake_case     :						Optional[int]						=   True

      _snake_case     :						str						=   getattr(self.model_tester						,    "seq_length"						,    snake_case_     )
      _snake_case     :						Optional[int]						=   getattr(self.model_tester						,    "encoder_seq_length"						,    snake_case_     )
      _snake_case     :						Dict						=   getattr(self.model_tester						,    "key_length"						,    snake_case_     )
      _snake_case     :						Optional[int]						=   getattr(self.model_tester						,    "chunk_length"						,    snake_case_     )

      if chunk_length is not None and hasattr(self.model_tester						,    "num_hashes"     ):
        _snake_case     :						List[Any]						=   encoder_seq_length * self.model_tester.num_hashes

      for model_class in self.all_model_classes:
        _snake_case     :						List[str]						=   True
        _snake_case     :						Dict						=   False
        _snake_case     :						Tuple						=   True
        _snake_case     :						Optional[Any]						=   model_class(snake_case_     )

        _snake_case     :						Optional[int]						=   model(**self._prepare_for_class(snake_case_						,    snake_case_     )						,    training=snake_case_     )
        _snake_case     :						List[str]						=   outputs.encoder_attentions if config.is_encoder_decoder else outputs.attentions
        self.assertEqual(len(snake_case_     )						,    self.model_tester.num_attention_outputs     )

        # check that output_attentions also work using config
        del inputs_dict["output_attentions"]
        _snake_case     :						Optional[Any]						=   True
        _snake_case     :						Union[str, Any]						=   model_class(snake_case_     )
        _snake_case     :						List[Any]						=   model(**self._prepare_for_class(snake_case_						,    snake_case_     )						,    training=snake_case_     )

        _snake_case     :						Optional[Any]						=   outputs.encoder_attentions if config.is_encoder_decoder else outputs.attentions
        self.assertEqual(len(snake_case_     )						,    self.model_tester.num_attention_outputs     )

        if chunk_length is not None:
          self.assertListEqual(
              list(attentions[0].shape[-4:]     )						,    [self.model_tester.num_attention_heads, encoder_seq_length, chunk_length, encoder_key_length]						,    )
        else:
          self.assertListEqual(
              list(attentions[0].shape[-3:]     )						,    [self.model_tester.num_attention_heads, encoder_seq_length, encoder_key_length]						,    )


    def 					lowerCamelCase__	(    self     ):
      # We use a simplified version of this test for EfficientFormer because it requires training=False
      # and Keras refuses to let us force that during functional construction
      _snake_case     :						List[Any]						=   self.model_tester.prepare_config_and_inputs_for_common()

      for model_class in self.all_model_classes:
        # Prepare our model
        _snake_case     :						Tuple						=   model_class(snake_case_     )
        # These are maximally general inputs for the model, with multiple None dimensions
        # Hopefully this will catch any conditionals that fail for flexible shapes
        _snake_case     :						str						=   {
            key: tf.keras.Input(shape=val.shape[1:]						,    dtype=val.dtype						,    name=snake_case_     )
            for key, val in model.input_signature.items()
            if key in model.dummy_inputs
        }
        _snake_case     :						str						=   model(snake_case_     )
        self.assertTrue(outputs_dict is not None     )


def 				a__   (   ):

  """simple docstring"""







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






@require_tf
@require_vision
class      _UpperCAmelCase				(					unittest.TestCase):
    @cached_property
    def 					lowerCamelCase__	(    self     ):
      return (
          EfficientFormerImageProcessor.from_pretrained("snap-research/efficientformer-l1-300"     )
          if is_vision_available()
          else None
      )
    @slow
    def 					lowerCamelCase__	(    self     ):
      _snake_case     :						List[str]						=   TFEfficientFormerForImageClassification.from_pretrained("snap-research/efficientformer-l1-300"     )
      _snake_case     :						Any						=   self.default_image_processor
      _snake_case     :						Optional[Any]						=   prepare_img()
      _snake_case     :						str						=   image_processor(images=snake_case_						,    return_tensors="tf"     )
      # forward pass
      _snake_case     :						List[str]						=   model(**snake_case_						,    training=snake_case_     )
      # verify the logits
      _snake_case     :						Tuple						=   tf.TensorShape((1, 10_00)     )
      self.assertEqual(outputs.logits.shape						,    snake_case_     )
      _snake_case     :						Optional[Any]						=   tf.constant([-0.0555, 0.4825, -0.0852]     )
      self.assertTrue(np.allclose(outputs.logits[0, :3]						,    snake_case_						,    atol=1E-4     )     )


    @slow
    def 					lowerCamelCase__	(    self     ):
      _snake_case     :						Optional[Any]						=   TFEfficientFormerForImageClassificationWithTeacher.from_pretrained(
          "snap-research/efficientformer-l1-300"     )
      _snake_case     :						str						=   self.default_image_processor
      _snake_case     :						List[Any]						=   prepare_img()
      _snake_case     :						str						=   image_processor(images=snake_case_						,    return_tensors="tf"     )
      # forward pass
      _snake_case     :						Dict						=   model(**snake_case_						,    training=snake_case_     )
      # verify the logits
      _snake_case     :						Any						=   tf.TensorShape((1, 10_00)     )
      self.assertEqual(outputs.logits.shape						,    snake_case_     )
      _snake_case     :						List[str]						=   tf.constant([-0.1312, 0.4353, -1.0499]     )
      self.assertTrue(np.allclose(outputs.logits[0, :3]						,    snake_case_						,    atol=1E-4     )     )



"""simple docstring"""
from typing import TYPE_CHECKING

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


_a      :			str					=							{"""configuration_yolos""": ["""YOLOS_PRETRAINED_CONFIG_ARCHIVE_MAP""", """YolosConfig""", """YolosOnnxConfig"""]}

try:
    if not is_vision_available():
        raise OptionalDependencyNotAvailable()
except OptionalDependencyNotAvailable:
    pass
else:
    _a      :			Optional[Any]					=							["""YolosFeatureExtractor"""]
    _a      :			List[Any]					=							["""YolosImageProcessor"""]

try:
    if not is_torch_available():
        raise OptionalDependencyNotAvailable()
except OptionalDependencyNotAvailable:
    pass
else:
    _a      :			Union[str, Any]					=							[
        """YOLOS_PRETRAINED_MODEL_ARCHIVE_LIST""",
        """YolosForObjectDetection""",
        """YolosModel""",
        """YolosPreTrainedModel""",
    ]


if TYPE_CHECKING:
    from .configuration_yolos import YOLOS_PRETRAINED_CONFIG_ARCHIVE_MAP, YolosConfig, YolosOnnxConfig

    try:
        if not is_vision_available():
            raise OptionalDependencyNotAvailable()
    except OptionalDependencyNotAvailable:
        pass
    else:
        from .feature_extraction_yolos import YolosFeatureExtractor
        from .image_processing_yolos import YolosImageProcessor

    try:
        if not is_torch_available():
            raise OptionalDependencyNotAvailable()
    except OptionalDependencyNotAvailable:
        pass
    else:
        from .modeling_yolos import (
            YOLOS_PRETRAINED_MODEL_ARCHIVE_LIST,
            YolosForObjectDetection,
            YolosModel,
            YolosPreTrainedModel,
        )


else:
    import sys

    _a      :			Union[str, Any]					=							_LazyModule(__name__, globals()["""__file__"""], _import_structure, module_spec=__spec__)

