


"""simple docstring"""







import inspect
import unittest

from transformers import MobileNetVaConfig
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, ids_tensor
from ...test_pipeline_mixin import PipelineTesterMixin


if is_torch_available():
 import torch

 from transformers import MobileNetVaForImageClassification, MobileNetVaModel
 from transformers.models.mobilenet_va.modeling_mobilenet_va import MOBILENET_V1_PRETRAINED_MODEL_ARCHIVE_LIST


if is_vision_available():
 from PIL import Image

 from transformers import MobileNetVaImageProcessor






class 						_A  (  _a  ):







    """simple docstring"""




    def      __snake_case							( self    :   Union[str, Any]):
      a						:		int											=      self.config_class(**self.inputs_dict)
      self.parent.assertTrue(hasattr(__UpperCAmelCase    ,			"tf_padding"))
      self.parent.assertTrue(hasattr(__UpperCAmelCase    ,			"depth_multiplier"))






class 						_A  :







    """simple docstring"""




    def __init__( self    :   int    ,			__UpperCAmelCase    :   Optional[int]    ,			__UpperCAmelCase    :   List[Any]=13    ,			__UpperCAmelCase    :   str=3    ,			__UpperCAmelCase    :   Optional[int]=32    ,			__UpperCAmelCase    :   Dict=0.25    ,			__UpperCAmelCase    :   int=8    ,			__UpperCAmelCase    :   int=True    ,			__UpperCAmelCase    :   Optional[int]=1024    ,			__UpperCAmelCase    :   Dict=32    ,			__UpperCAmelCase    :   Union[str, Any]="relu6"    ,			__UpperCAmelCase    :   Any=0.1    ,			__UpperCAmelCase    :   Union[str, Any]=0.02    ,			__UpperCAmelCase    :   List[str]=True    ,			__UpperCAmelCase    :   Union[str, Any]=True    ,			__UpperCAmelCase    :   str=10    ,			__UpperCAmelCase    :   List[Any]=None    ,			):
      a						:		Any											=      parent
      a						:		int											=      batch_size
      a						:		Any											=      num_channels
      a						:		Optional[Any]											=      image_size
      a						:		int											=      depth_multiplier
      a						:		Tuple											=      min_depth
      a						:		Any											=      tf_padding
      a						:		Union[str, Any]											=      int(last_hidden_size * depth_multiplier)
      a						:		Optional[int]											=      output_stride
      a						:		int											=      hidden_act
      a						:		Dict											=      classifier_dropout_prob
      a						:		str											=      use_labels
      a						:		List[Any]											=      is_training
      a						:		str											=      num_labels
      a						:		Optional[int]											=      initializer_range
      a						:		Tuple											=      scope






    def      __snake_case							( self    :   int):
      a						:		Optional[int]											=      floats_tensor([self.batch_size, self.num_channels, self.image_size, self.image_size])

      a						:		Any											=      None
      a						:		Tuple											=      None
      if self.use_labels:
        a						:		List[Any]											=      ids_tensor([self.batch_size]    ,			self.num_labels)
        a						:		Dict											=      ids_tensor([self.batch_size, self.image_size, self.image_size]    ,			self.num_labels)

      a						:		Union[str, Any]											=      self.get_config()

      return config, pixel_values, labels, pixel_labels






    def      __snake_case							( self    :   Any):
      return MobileNetVaConfig(
          num_channels=self.num_channels    ,			image_size=self.image_size    ,			depth_multiplier=self.depth_multiplier    ,			min_depth=self.min_depth    ,			tf_padding=self.tf_padding    ,			hidden_act=self.hidden_act    ,			classifier_dropout_prob=self.classifier_dropout_prob    ,			initializer_range=self.initializer_range    ,			)






    def      __snake_case							( self    :   int    ,			__UpperCAmelCase    :   Optional[Any]    ,			__UpperCAmelCase    :   Dict    ,			__UpperCAmelCase    :   Dict    ,			__UpperCAmelCase    :   Dict):
      a						:		List[Any]											=      MobileNetVaModel(config=__UpperCAmelCase)
      model.to(__UpperCAmelCase)
      model.eval()
      a						:		Dict											=      model(__UpperCAmelCase)
      self.parent.assertEqual(
          result.last_hidden_state.shape    ,			(
              self.batch_size,
              self.last_hidden_size,
              self.image_size // self.output_stride,
              self.image_size // self.output_stride,
          )    ,			)






    def      __snake_case							( self    :   Optional[Any]    ,			__UpperCAmelCase    :   Dict    ,			__UpperCAmelCase    :   str    ,			__UpperCAmelCase    :   List[str]    ,			__UpperCAmelCase    :   Tuple):
      a						:		Any											=      self.num_labels
      a						:		Union[str, Any]											=      MobileNetVaForImageClassification(__UpperCAmelCase)
      model.to(__UpperCAmelCase)
      model.eval()
      a						:		List[str]											=      model(__UpperCAmelCase    ,			labels=__UpperCAmelCase)
      self.parent.assertEqual(result.logits.shape    ,			(self.batch_size, self.num_labels))






    def      __snake_case							( self    :   Union[str, Any]):
      a						:		List[Any]											=      self.prepare_config_and_inputs()
      a							,		a							,		a							,		a						:		Tuple											=      config_and_inputs
      a						:		Union[str, Any]											=      {"pixel_values": pixel_values}
      return config, inputs_dict






@require_torch
class 						_A  (  _a   ,_a   ,unittest.TestCase  ):







    """simple docstring"""




    UpperCAmelCase	:							List[str]     =	(MobileNetVaModel, MobileNetVaForImageClassification) if is_torch_available() else ()
    UpperCAmelCase	:							int     =	(
        {"""feature-extraction""": MobileNetVaModel, """image-classification""": MobileNetVaForImageClassification}
        if is_torch_available()
        else {}
    )

    UpperCAmelCase	:							Dict     =	False
    UpperCAmelCase	:							Dict     =	False
    UpperCAmelCase	:							Tuple     =	False
    UpperCAmelCase	:							Optional[int]     =	False






    def      __snake_case							( self    :   Any):
      a						:		int											=      MobileNetVaModelTester(self)
      a						:		List[str]											=      MobileNetVaConfigTester(self    ,			config_class=__UpperCAmelCase    ,			has_text_modality=__UpperCAmelCase)






    def      __snake_case							( self    :   List[Any]):
      self.config_tester.run_common_tests()






    @unittest.skip(reason="MobileNetV1 does not use inputs_embeds")
    def      __snake_case							( self    :   Optional[int]):
      pass






    @unittest.skip(reason="MobileNetV1 does not support input and output embeddings")
    def      __snake_case							( self    :   str):
      pass






    @unittest.skip(reason="MobileNetV1 does not output attentions")
    def      __snake_case							( self    :   Union[str, Any]):
      pass






    def      __snake_case							( self    :   int):
      a							,		a						:		Optional[Any]											=      self.model_tester.prepare_config_and_inputs_for_common()

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

        a						:		Optional[Any]											=      ["pixel_values"]
        self.assertListEqual(arg_names[:1]    ,			__UpperCAmelCase)






    def      __snake_case							( self    :   Union[str, Any]):
      a						:		int											=      self.model_tester.prepare_config_and_inputs()
      self.model_tester.create_and_check_model(*__UpperCAmelCase)






    def      __snake_case							( self    :   int):
      def check_hidden_states_output(__UpperCAmelCase    :   Dict    ,			__UpperCAmelCase    :   str    ,			__UpperCAmelCase    :   Optional[Any]):
        a						:		List[str]											=      model_class(__UpperCAmelCase)
        model.to(__UpperCAmelCase)
        model.eval()

        with torch.no_grad():
          a						:		Any											=      model(**self._prepare_for_class(__UpperCAmelCase    ,			__UpperCAmelCase))

        a						:		Optional[int]											=      outputs.hidden_states

        a						:		Any											=      26
        self.assertEqual(len(__UpperCAmelCase)    ,			__UpperCAmelCase)

      a							,		a						:		Optional[int]											=      self.model_tester.prepare_config_and_inputs_for_common()

      for model_class in self.all_model_classes:
        a						:		str											=      True
        check_hidden_states_output(__UpperCAmelCase    ,			__UpperCAmelCase    ,			__UpperCAmelCase)

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

        check_hidden_states_output(__UpperCAmelCase    ,			__UpperCAmelCase    ,			__UpperCAmelCase)






    def      __snake_case							( self    :   int):
      a						:		List[Any]											=      self.model_tester.prepare_config_and_inputs()
      self.model_tester.create_and_check_for_image_classification(*__UpperCAmelCase)






    @slow
    def      __snake_case							( self    :   Optional[Any]):
      for model_name in MOBILENET_V1_PRETRAINED_MODEL_ARCHIVE_LIST[:1]:
        a						:		Tuple											=      MobileNetVaModel.from_pretrained(__UpperCAmelCase)
        self.assertIsNotNone(__UpperCAmelCase)






def 					lowercase      (    )->				Tuple:
  '''simple docstring'''







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







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







    """simple docstring"""




    @cached_property
    def      __snake_case							( self    :   int):
      return (
          MobileNetVaImageProcessor.from_pretrained("google/mobilenet_v1_1.0_224") if is_vision_available() else None
      )






    @slow
    def      __snake_case							( self    :   Dict):
      a						:		Any											=      MobileNetVaForImageClassification.from_pretrained("google/mobilenet_v1_1.0_224").to(__UpperCAmelCase)

      a						:		Union[str, Any]											=      self.default_image_processor
      a						:		Optional[int]											=      prepare_img()
      a						:		List[Any]											=      image_processor(images=__UpperCAmelCase    ,			return_tensors="pt").to(__UpperCAmelCase)

      # forward pass
      with torch.no_grad():
        a						:		Union[str, Any]											=      model(**__UpperCAmelCase)

      # verify the logits
      a						:		Tuple											=      torch.Size((1, 1001))
      self.assertEqual(outputs.logits.shape    ,			__UpperCAmelCase)

      a						:		List[str]											=      torch.tensor([-4.1_739, -1.1_233, 3.1_205]).to(__UpperCAmelCase)

      self.assertTrue(torch.allclose(outputs.logits[0, :3]    ,			__UpperCAmelCase    ,			atol=1e-4))










"""simple docstring"""







import inspect
import os
import re

from transformers.configuration_utils import PretrainedConfig
from transformers.utils import direct_transformers_import


# All paths are set with the intent you should run this script from the root of the repo with the command
# python utils/check_config_docstrings.py
__lowercase    =				"""src/transformers"""


# This is to make sure the transformers module imported is the one in the repo.
__lowercase    =				direct_transformers_import(PATH_TO_TRANSFORMERS)

__lowercase    =				transformers.models.auto.configuration_auto.CONFIG_MAPPING

__lowercase    =				{
    # used to compute the property `self.chunk_length`
    """EncodecConfig""": ["""overlap"""],
    # used as `self.bert_model = BertModel(config, ...)`
    """DPRConfig""": True,
    # not used in modeling files, but it's an important information
    """FSMTConfig""": ["""langs"""],
    # used internally in the configuration class file
    """GPTNeoConfig""": ["""attention_types"""],
    # used internally in the configuration class file
    """EsmConfig""": ["""is_folding_model"""],
    # used during training (despite we don't have training script for these models yet)
    """Mask2FormerConfig""": ["""ignore_value"""],
    # `ignore_value` used during training (despite we don't have training script for these models yet)
    # `norm` used in conversion script (despite not using in the modeling file)
    """OneFormerConfig""": ["""ignore_value""", """norm"""],
    # used during preprocessing and collation, see `collating_graphormer.py`
    """GraphormerConfig""": ["""spatial_pos_max"""],
    # used internally in the configuration class file
    """T5Config""": ["""feed_forward_proj"""],
    # used internally in the configuration class file
    # `tokenizer_class` get default value `T5Tokenizer` intentionally
    """MT5Config""": ["""feed_forward_proj""", """tokenizer_class"""],
    """UMT5Config""": ["""feed_forward_proj""", """tokenizer_class"""],
    # used internally in the configuration class file
    """LongT5Config""": ["""feed_forward_proj"""],
    # used internally in the configuration class file
    """SwitchTransformersConfig""": ["""feed_forward_proj"""],
    # having default values other than `1e-5` - we can't fix them without breaking
    """BioGptConfig""": ["""layer_norm_eps"""],
    # having default values other than `1e-5` - we can't fix them without breaking
    """GLPNConfig""": ["""layer_norm_eps"""],
    # having default values other than `1e-5` - we can't fix them without breaking
    """SegformerConfig""": ["""layer_norm_eps"""],
    # having default values other than `1e-5` - we can't fix them without breaking
    """CvtConfig""": ["""layer_norm_eps"""],
    # having default values other than `1e-5` - we can't fix them without breaking
    """PerceiverConfig""": ["""layer_norm_eps"""],
    # used internally to calculate the feature size
    """InformerConfig""": ["""num_static_real_features""", """num_time_features"""],
    # used internally to calculate the feature size
    """TimeSeriesTransformerConfig""": ["""num_static_real_features""", """num_time_features"""],
    # used internally to calculate the feature size
    """AutoformerConfig""": ["""num_static_real_features""", """num_time_features"""],
    # used internally to calculate `mlp_dim`
    """SamVisionConfig""": ["""mlp_ratio"""],
    # For (head) training, but so far not implemented
    """ClapAudioConfig""": ["""num_classes"""],
    # Not used, but providing useful information to users
    """SpeechT5HifiGanConfig""": ["""sampling_rate"""],
}


# TODO (ydshieh): Check the failing cases, try to fix them or move some cases to the above block once we are sure
SPECIAL_CASES_TO_ALLOW.update(
    {
        """CLIPSegConfig""": True,
        """DeformableDetrConfig""": True,
        """DetaConfig""": True,
        """DinatConfig""": True,
        """DonutSwinConfig""": True,
        """EfficientFormerConfig""": True,
        """FSMTConfig""": True,
        """JukeboxConfig""": True,
        """LayoutLMv2Config""": True,
        """MaskFormerSwinConfig""": True,
        """MT5Config""": True,
        """NatConfig""": True,
        """OneFormerConfig""": True,
        """PerceiverConfig""": True,
        """RagConfig""": True,
        """SpeechT5Config""": True,
        """SwinConfig""": True,
        """Swin2SRConfig""": True,
        """Swinv2Config""": True,
        """SwitchTransformersConfig""": True,
        """TableTransformerConfig""": True,
        """TapasConfig""": True,
        """TransfoXLConfig""": True,
        """UniSpeechConfig""": True,
        """UniSpeechSatConfig""": True,
        """WavLMConfig""": True,
        """WhisperConfig""": True,
        # TODO: @Arthur (for `alignment_head` and `alignment_layer`)
        """JukeboxPriorConfig""": True,
        # TODO: @Younes (for `is_decoder`)
        """Pix2StructTextConfig""": True,
    }
)


def 					lowercase      (    A_  ,       A_  ,       A_  ,       A_	)->				Optional[Any]:
  '''simple docstring'''







  a						:		List[str]											=      False
  for attribute in attributes:
    for modeling_source in source_strings:
      # check if we can find `config.xxx`, `getattr(config, "xxx", ...)` or `getattr(self.config, "xxx", ...)`
      if (
          F'''config.{attribute}''' in modeling_source
          or F'''getattr(config, "{attribute}"''' in modeling_source
          or F'''getattr(self.config, "{attribute}"''' in modeling_source
      ):
        a						:		str											=      True
      # Deal with multi-line cases
      elif (
          re.search(
              RF'''getattr[ \t\v\n\r\f]*\([ \t\v\n\r\f]*(self\.)?config,[ \t\v\n\r\f]*"{attribute}"'''  ,       A_  ,       )
          is not None
      ):
        a						:		List[Any]											=      True
      # `SequenceSummary` is called with `SequenceSummary(config)`
      elif attribute in [
          "summary_type",
          "summary_use_proj",
          "summary_activation",
          "summary_last_dropout",
          "summary_proj_to_labels",
          "summary_first_dropout",
      ]:
        if "SequenceSummary" in modeling_source:
          a						:		str											=      True
      if attribute_used:
        break
    if attribute_used:
      break

    # common and important attributes, even if they do not always appear in the modeling files
  a						:		Tuple											=      [
      "bos_index",
      "eos_index",
      "pad_index",
      "unk_index",
      "mask_index",
      "image_size",
      "use_cache",
      "out_features",
      "out_indices",
  ]
  a						:		str											=      ["encoder_no_repeat_ngram_size"]

  # Special cases to be allowed
  a						:		int											=      True
  if not attribute_used:
    a						:		Dict											=      False
    for attribute in attributes:
      # Allow if the default value in the configuration class is different from the one in `PretrainedConfig`
      if attribute in ["is_encoder_decoder"] and default_value is True:
        a						:		Optional[int]											=      True
      elif attribute in ["tie_word_embeddings"] and default_value is False:
        a						:		List[Any]											=      True

      # Allow cases without checking the default value in the configuration class
      elif attribute in attributes_to_allow + attributes_used_in_generation:
        a						:		str											=      True
      elif attribute.endswith("_token_id"	):
        a						:		str											=      True

      # configuration class specific cases
      if not case_allowed:
        a						:		Union[str, Any]											=      SPECIAL_CASES_TO_ALLOW.get(config_class.__name__  ,       []	)
        a						:		Optional[Any]											=      allowed_cases is True or attribute in allowed_cases

  return attribute_used or case_allowed


def 					lowercase      (    A_	)->				Tuple:
  '''simple docstring'''







  a						:		Optional[int]											=      dict(inspect.signature(config_class.__init__	).parameters	)
  a						:		Any											=      [x for x in list(signature.keys()	) if x not in ["self", "kwargs"]]
  a						:		str											=      [signature[param].default for param in parameter_names]

  # If `attribute_map` exists, an attribute can have different names to be used in the modeling files, and as long
  # as one variant is used, the test should pass
  a						:		Dict											=      {}
  if len(config_class.attribute_map	) > 0:
    a						:		int											=      {v: k for k, v in config_class.attribute_map.items()}

  # Get the path to modeling source files
  a						:		int											=      inspect.getsourcefile(A_	)
  a						:		Union[str, Any]											=      os.path.dirname(A_	)
  # Let's check against all frameworks: as long as one framework uses an attribute, we are good.
  a						:		Optional[Any]											=      [os.path.join(A_  ,       A_	) for fn in os.listdir(A_	) if fn.startswith("modeling_"	)]

  # Get the source code strings
  a						:		Tuple											=      []
  for path in modeling_paths:
    if os.path.isfile(A_	):
      with open(A_	) as fp:
        modeling_sources.append(fp.read()	)

  a						:		Optional[Any]											=      []
  for config_param, default_value in zip(A_  ,       A_	):
    # `attributes` here is all the variant names for `config_param`
    a						:		str											=      [config_param]
    # some configuration classes have non-empty `attribute_map`, and both names could be used in the
    # corresponding modeling files. As long as one of them appears, it is fine.
    if config_param in reversed_attribute_map:
      attributes.append(reversed_attribute_map[config_param]	)

    if not check_attribute_being_used(A_  ,       A_  ,       A_  ,       A_	):
      unused_attributes.append(attributes[0]	)

  return sorted(A_	)


def 					lowercase      (    )->				str:
  '''simple docstring'''







  a						:		List[Any]											=      {}
  for _config_class in list(CONFIG_MAPPING.values()	):
    # Skip deprecated models
    if "models.deprecated" in _config_class.__module__:
      continue
    # Some config classes are not in `CONFIG_MAPPING` (e.g. `CLIPVisionConfig`, `Blip2VisionConfig`, etc.)
    a						:		str											=      [
        cls
        for name, cls in inspect.getmembers(
            inspect.getmodule(_config_class	)  ,       lambda A_	: inspect.isclass(A_	)
            and issubclass(A_  ,       A_	)
            and inspect.getmodule(A_	) == inspect.getmodule(_config_class	)  ,       )
    ]
    for config_class in config_classes_in_module:
      a						:		Union[str, Any]											=      check_config_attributes_being_used(A_	)
      if len(A_	) > 0:
        a						:		Dict											=      unused_attributes

  if len(A_	) > 0:
    a						:		Union[str, Any]											=      "The following configuration classes contain unused attributes in the corresponding modeling files:\n"
    for name, attributes in configs_with_unused_attributes.items():
      error += F'''{name}: {attributes}\n'''

    raise ValueError(A_	)


if __name__ == "__main__":
 check_config_attributes()






