






"""simple docstring"""


import inspect
import unittest

from transformers import RegNetConfig
from transformers.file_utils import cached_property, is_torch_available, is_vision_available
from transformers.testing_utils import require_torch, require_vision, slow, torch_device

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 torch import nn

 from transformers import RegNetForImageClassification, RegNetModel
 from transformers.models.regnet.modeling_regnet import REGNET_PRETRAINED_MODEL_ARCHIVE_LIST


if is_vision_available():
 from PIL import Image

 from transformers import AutoImageProcessor






class 						snake_case  :





    def __init__(							self     : Dict    ,		A     : str    ,		A     : List[Any]=3    ,		A     : Optional[int]=3_2    ,		A     : List[Any]=3    ,		A     : Optional[int]=1_0    ,		A     : List[Any]=[1_0, 2_0, 3_0, 4_0]    ,		A     : Tuple=[1, 1, 2, 1]    ,		A     : Dict=True    ,		A     : Optional[Any]=True    ,		A     : Union[str, Any]="relu"    ,		A     : List[Any]=3    ,		A     : str=None    ,		):


      '''simple docstring'''




      a					:      Any    =       parent
      a					:      int    =       batch_size
      a					:      Dict    =       image_size
      a					:      List[str]    =       num_channels
      a					:      Dict    =       embeddings_size
      a					:      Union[str, Any]    =       hidden_sizes
      a					:      Dict    =       depths
      a					:      Union[str, Any]    =       is_training
      a					:      Optional[int]    =       use_labels
      a					:      Dict    =       hidden_act
      a					:      Dict    =       num_labels
      a					:      str    =       scope
      a					:      Union[str, Any]    =       len(A      )





    def     lowerCamelCase__				(							self     : Optional[int]      ):


      '''simple docstring'''




      a					:      Union[str, Any]    =       floats_tensor([self.batch_size, self.num_channels, self.image_size, self.image_size]      )

      a					:      str    =       None
      if self.use_labels:
        a					:      Optional[int]    =       ids_tensor([self.batch_size]    ,		self.num_labels      )

      a					:      Optional[Any]    =       self.get_config()

      return config, pixel_values, labels





    def     lowerCamelCase__				(							self     : Dict      ):


      '''simple docstring'''




      return RegNetConfig(
          num_channels=self.num_channels    ,		embeddings_size=self.embeddings_size    ,		hidden_sizes=self.hidden_sizes    ,		depths=self.depths    ,		hidden_act=self.hidden_act    ,		num_labels=self.num_labels    ,		)





    def     lowerCamelCase__				(							self     : Union[str, Any]    ,		A     : Any    ,		A     : Union[str, Any]    ,		A     : Tuple      ):


      '''simple docstring'''




      a					:      Union[str, Any]    =       RegNetModel(config=A      )
      model.to(A      )
      model.eval()
      a					:      Tuple    =       model(A      )
      # expected last hidden states: B, C, H // 32, W // 32
      self.parent.assertEqual(
          result.last_hidden_state.shape    ,		(self.batch_size, self.hidden_sizes[-1], self.image_size // 3_2, self.image_size // 3_2)    ,		)





    def     lowerCamelCase__				(							self     : Union[str, Any]    ,		A     : Optional[int]    ,		A     : str    ,		A     : Union[str, Any]      ):


      '''simple docstring'''




      a					:      Tuple    =       self.num_labels
      a					:      int    =       RegNetForImageClassification(A      )
      model.to(A      )
      model.eval()
      a					:      str    =       model(A    ,		labels=A      )
      self.parent.assertEqual(result.logits.shape    ,		(self.batch_size, self.num_labels)      )





    def     lowerCamelCase__				(							self     : List[str]      ):


      '''simple docstring'''




      a					:      List[str]    =       self.prepare_config_and_inputs()
      a					:      Optional[int]    =       config_and_inputs
      a					:      Any    =       {'pixel_values': pixel_values}
      return config, inputs_dict






@require_torch
class 						snake_case  (  UpperCAmelCase       ,			UpperCAmelCase       ,			unittest.TestCase	):
    __magic_name__   					=					(RegNetModel, RegNetForImageClassification) if is_torch_available() else ()
    __magic_name__   					=					(
        {'''feature-extraction''': RegNetModel, '''image-classification''': RegNetForImageClassification}
        if is_torch_available()
        else {}
    )

    __magic_name__   					=					False
    __magic_name__   					=					False
    __magic_name__   					=					False
    __magic_name__   					=					False





    def     lowerCamelCase__				(							self     : Dict      ):


      '''simple docstring'''




      a					:      Any    =       RegNetModelTester(self      )
      a					:      str    =       ConfigTester(self    ,		config_class=A    ,		has_text_modality=A      )





    def     lowerCamelCase__				(							self     : List[str]      ):


      '''simple docstring'''




      self.create_and_test_config_common_properties()
      self.config_tester.create_and_test_config_to_json_string()
      self.config_tester.create_and_test_config_to_json_file()
      self.config_tester.create_and_test_config_from_and_save_pretrained()
      self.config_tester.create_and_test_config_with_num_labels()
      self.config_tester.check_config_can_be_init_without_params()
      self.config_tester.check_config_arguments_init()





    def     lowerCamelCase__				(							self     : Union[str, Any]      ):


      '''simple docstring'''




      return





    @unittest.skip(reason='RegNet does not use inputs_embeds'      )
    def     lowerCamelCase__				(							self     : List[Any]      ):


      '''simple docstring'''




      pass





    @unittest.skip(reason='RegNet does not support input and output embeddings'      )
    def     lowerCamelCase__				(							self     : Tuple      ):


      '''simple docstring'''




      pass





    def     lowerCamelCase__				(							self     : List[str]      ):


      '''simple docstring'''




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

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

        a					:      Any    =       ['pixel_values']
        self.assertListEqual(arg_names[:1]    ,		A      )





    def     lowerCamelCase__				(							self     : Union[str, Any]      ):


      '''simple docstring'''




      a					:      List[str]    =       self.model_tester.prepare_config_and_inputs()
      self.model_tester.create_and_check_model(*A      )





    def     lowerCamelCase__				(							self     : Union[str, Any]      ):


      '''simple docstring'''




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

      for model_class in self.all_model_classes:
        a					:      List[Any]    =       model_class(config=A      )
        for name, module in model.named_modules():
          if isinstance(A    ,		(nn.BatchNormad, nn.GroupNorm)      ):
            self.assertTrue(
                torch.all(module.weight == 1      )    ,		msg=F'''Parameter {name} of model {model_class} seems not properly initialized'''    ,		)
            self.assertTrue(
                torch.all(module.bias == 0      )    ,		msg=F'''Parameter {name} of model {model_class} seems not properly initialized'''    ,		)





    def     lowerCamelCase__				(							self     : Tuple      ):


      '''simple docstring'''




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

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

        a					:      List[str]    =       outputs.encoder_hidden_states if config.is_encoder_decoder else outputs.hidden_states

        a					:      int    =       self.model_tester.num_stages
        self.assertEqual(len(A      )    ,		expected_num_stages + 1      )

        # RegNet's feature maps are of shape (batch_size, num_channels, height, width)
        self.assertListEqual(
            list(hidden_states[0].shape[-2:]      )    ,		[self.model_tester.image_size // 2, self.model_tester.image_size // 2]    ,		)

      a					:      Union[str, Any]    =       self.model_tester.prepare_config_and_inputs_for_common()
      a					:      Union[str, Any]    =       ['basic', 'bottleneck']
      for model_class in self.all_model_classes:
        for layer_type in layers_type:
          a					:      Tuple    =       layer_type
          a					:      List[Any]    =       True
          check_hidden_states_output(A    ,		A    ,		A      )

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

          check_hidden_states_output(A    ,		A    ,		A      )





    def     lowerCamelCase__				(							self     : int      ):


      '''simple docstring'''




      a					:      Tuple    =       self.model_tester.prepare_config_and_inputs()
      self.model_tester.create_and_check_for_image_classification(*A      )





    @slow
    def     lowerCamelCase__				(							self     : Tuple      ):


      '''simple docstring'''




      for model_name in REGNET_PRETRAINED_MODEL_ARCHIVE_LIST[:1]:
        a					:      Dict    =       RegNetModel.from_pretrained(A      )
        self.assertIsNotNone(A      )




def       snake_case  ():







  '''simple docstring'''

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






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





    @cached_property
    def     lowerCamelCase__				(							self     : List[str]      ):


      '''simple docstring'''




      return (
          AutoImageProcessor.from_pretrained(REGNET_PRETRAINED_MODEL_ARCHIVE_LIST[0]      )
          if is_vision_available()
          else None
      )





    @slow
    def     lowerCamelCase__				(							self     : Optional[Any]      ):


      '''simple docstring'''




      a					:      int    =       RegNetForImageClassification.from_pretrained(REGNET_PRETRAINED_MODEL_ARCHIVE_LIST[0]      ).to(A      )

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

      # forward pass
      with torch.no_grad():
        a					:      str    =       model(**A      )

      # verify the logits
      a					:      str    =       torch.Size((1, 1_0_0_0)      )
      self.assertEqual(outputs.logits.shape    ,		A      )

      a					:      List[str]    =       torch.tensor([-0.41_80, -1.50_51, -3.48_36]      ).to(A      )

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












"""simple docstring"""


import argparse
from collections import defaultdict

import yaml


_UpperCamelCase    :   int   			=						'docs/source/en/_toctree.yml'




def       snake_case  (A_				:Optional[Any]				):







  '''simple docstring'''

  a					:      List[Any]    =       defaultdict(A_				)
  for doc in model_doc:
    counts[doc["local"]] += 1
  a					:      Optional[Any]    =       [key for key, value in counts.items() if value > 1]

  a					:      List[str]    =       []
  for duplicate_key in duplicates:
    a					:      int    =       list({doc['title'] for doc in model_doc if doc['local'] == duplicate_key}				)
    if len(A_				) > 1:
      raise ValueError(
          f'''{duplicate_key} is present several times in the documentation table of content at '''
          '`docs/source/en/_toctree.yml` with different *Title* values. Choose one of those and remove the '
          'others.'				)
    # Only add this once
    new_doc.append({'local': duplicate_key, 'title': titles[0]}				)

  # Add none duplicate-keys
  new_doc.extend([doc for doc in model_doc if counts[doc['local']] == 1]				)

  # Sort
  return sorted(A_     ,      key=lambda A_				: s["title"].lower()				)




def       snake_case  (A_				:List[str]=False				):







  '''simple docstring'''

  with open(A_     ,      encoding='utf-8'				) as f:
    a					:      Dict    =       yaml.safe_load(f.read()				)

  # Get to the API doc
  a					:      Optional[Any]    =       0
  while content[api_idx]["title"] != "API":
    api_idx += 1
  a					:      List[str]    =       content[api_idx]['sections']

  # Then to the model doc
  a					:      Optional[int]    =       0
  while api_doc[model_idx]["title"] != "Models":
    model_idx += 1

  a					:      Optional[Any]    =       api_doc[model_idx]['sections']

  a					:      Dict    =       [(idx, section) for idx, section in enumerate(A_				) if 'sections' in section]
  a					:      List[str]    =       False
  for idx, modality_doc in modalities_docs:
    a					:      str    =       modality_doc['sections']
    a					:      str    =       clean_model_doc_toc(A_				)

    if old_modality_doc != new_modality_doc:
      a					:      str    =       True
      if overwrite:
        a					:      Any    =       new_modality_doc

  if diff:
    if overwrite:
      a					:      Any    =       model_doc
      a					:      str    =       api_doc
      with open(A_     ,      'w'     ,      encoding='utf-8'				) as f:
        f.write(yaml.dump(A_     ,      allow_unicode=A_				)				)
    else:
      raise ValueError(
          'The model doc part of the table of content is not properly sorted, run `make style` to fix this.'				)


if __name__ == "__main__":
   _UpperCamelCase    :   Optional[int]   			=						argparse.ArgumentParser()
   parser.add_argument('--fix_and_overwrite', action='store_true', help='Whether to fix inconsistencies.')
   _UpperCamelCase    :   Any   			=						parser.parse_args()

   check_model_doc(args.fix_and_overwrite)




