



"""simple docstring"""




import copy
import inspect
import unittest

from transformers import AutoBackbone
from transformers.configuration_utils import PretrainedConfig
from transformers.testing_utils import require_timm, require_torch, torch_device
from transformers.utils.import_utils import is_torch_available

from ...test_backbone_common import BackboneTesterMixin
from ...test_configuration_common import ConfigTester
from ...test_modeling_common import ModelTesterMixin, floats_tensor


if is_torch_available():
 import torch

 from transformers import TimmBackbone, TimmBackboneConfig

from ...test_pipeline_mixin import PipelineTesterMixin






class      UpperCAmelCase_  :



      def __init__(					self					:     int					,     A					:     List[str]					,     A					:     Tuple=None					,     A					:     Dict=None					,     A					:     Union[str, Any]=None					,     A					:     Optional[int]="resnet50"					,     A					:     Dict=3					,     A					:     Union[str, Any]=3_2					,     A					:     int=3					,     A					:     List[Any]=True					,     A					:     List[str]=True					,     ):
           _UpperCAmelCase      :     Union[str, Any]        =   parent
           _UpperCAmelCase      :     Union[str, Any]        =   out_indices if out_indices is not None else [4]
           _UpperCAmelCase      :     Optional[Any]        =   stage_names
           _UpperCAmelCase      :     Any        =   out_features
           _UpperCAmelCase      :     int        =   backbone
           _UpperCAmelCase      :     List[str]        =   batch_size
           _UpperCAmelCase      :     Optional[int]        =   image_size
           _UpperCAmelCase      :     Union[str, Any]        =   num_channels
           _UpperCAmelCase      :     Optional[Any]        =   use_pretrained_backbone
           _UpperCAmelCase      :     Optional[Any]        =   is_training



      def 						snake_case_ (					self					:     Optional[Any]						):
           _UpperCAmelCase      :     Any        =   floats_tensor([self.batch_size, self.num_channels, self.image_size, self.image_size]						)
           _UpperCAmelCase      :     Any        =   self.get_config()

           return config, pixel_values



      def 						snake_case_ (					self					:     Dict						):
           return TimmBackboneConfig(
               image_size=self.image_size					,     num_channels=self.num_channels					,     out_features=self.out_features					,     out_indices=self.out_indices					,     stage_names=self.stage_names					,     use_pretrained_backbone=self.use_pretrained_backbone					,     backbone=self.backbone					,     )



      def 						snake_case_ (					self					:     List[Any]					,     A					:     Dict					,     A					:     Any						):
           _UpperCAmelCase      :     Union[str, Any]        =   TimmBackbone(config=A						)
           model.to(A						)
           model.eval()
           with torch.no_grad():
                _UpperCAmelCase      :     Any        =   model(A						)
           self.parent.assertEqual(
               result.feature_map[-1].shape					,     (self.batch_size, model.channels[-1], 1_4, 1_4)					,     )



      def 						snake_case_ (					self					:     Tuple						):
           _UpperCAmelCase      :     str        =   self.prepare_config_and_inputs()
           _UpperCAmelCase    ,	_UpperCAmelCase      :     str        =   config_and_inputs
           _UpperCAmelCase      :     Any        =   {"pixel_values": pixel_values}
           return config, inputs_dict







@require_torch
@require_timm
class      UpperCAmelCase_  (    _UpperCamelCase	,      _UpperCamelCase	,      _UpperCamelCase	,      unittest.TestCase						):
      __SCREAMING_SNAKE_CASE						:       Dict								=			(TimmBackbone,) if is_torch_available() else ()
      __SCREAMING_SNAKE_CASE						:       Optional[Any]								=			{'feature-extraction': TimmBackbone} if is_torch_available() else {}
      __SCREAMING_SNAKE_CASE						:       Optional[Any]								=			False
      __SCREAMING_SNAKE_CASE						:       Tuple								=			False
      __SCREAMING_SNAKE_CASE						:       List[str]								=			False
      __SCREAMING_SNAKE_CASE						:       Optional[Any]								=			False



      def 						snake_case_ (					self					:     Optional[int]						):
           _UpperCAmelCase      :     int        =   TimmBackboneModelTester(self						)
           _UpperCAmelCase      :     List[str]        =   ConfigTester(self					,     config_class=A					,     has_text_modality=A						)



      def 						snake_case_ (					self					:     str						):
           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 						snake_case_ (					self					:     Optional[int]						):
           _UpperCAmelCase      :     List[Any]        =   "resnet18"
           _UpperCAmelCase      :     Tuple        =   "microsoft/resnet-18"

           _UpperCAmelCase      :     Dict        =   AutoBackbone.from_pretrained(A					,     use_timm_backbone=A						)
           _UpperCAmelCase      :     int        =   AutoBackbone.from_pretrained(A						)

           self.assertEqual(len(timm_model.out_features						)					,     len(transformers_model.out_features						)						)
           self.assertEqual(len(timm_model.stage_names						)					,     len(transformers_model.stage_names						)						)
           self.assertEqual(timm_model.channels					,     transformers_model.channels						)
           # Out indices are set to the last layer by default. For timm models, we don't know
           # the number of layers in advance, so we set it to (-1,), whereas for transformers
           # models, we set it to [len(stage_names) - 1] (kept for backward compatibility).
           self.assertEqual(timm_model.out_indices					,     (-1,)						)
           self.assertEqual(transformers_model.out_indices					,     [len(timm_model.stage_names						) - 1]						)

           _UpperCAmelCase      :     Any        =   AutoBackbone.from_pretrained(A					,     use_timm_backbone=A					,     out_indices=[1, 2, 3]						)
           _UpperCAmelCase      :     Optional[int]        =   AutoBackbone.from_pretrained(A					,     out_indices=[1, 2, 3]						)

           self.assertEqual(timm_model.out_indices					,     transformers_model.out_indices						)
           self.assertEqual(len(timm_model.out_features						)					,     len(transformers_model.out_features						)						)
           self.assertEqual(timm_model.channels					,     transformers_model.channels						)



      @unittest.skip("TimmBackbone doesn't support feed forward chunking"						)
      def 						snake_case_ (					self					:     str						):
           pass



      @unittest.skip("TimmBackbone doesn't have num_hidden_layers attribute"						)
      def 						snake_case_ (					self					:     Optional[Any]						):
           pass



      @unittest.skip("TimmBackbone initialization is managed on the timm side"						)
      def 						snake_case_ (					self					:     Dict						):
           pass



      @unittest.skip("TimmBackbone models doesn't have inputs_embeds"						)
      def 						snake_case_ (					self					:     Optional[Any]						):
           pass



      @unittest.skip("TimmBackbone models doesn't have inputs_embeds"						)
      def 						snake_case_ (					self					:     Union[str, Any]						):
           pass



      @unittest.skip("TimmBackbone model cannot be created without specifying a backbone checkpoint"						)
      def 						snake_case_ (					self					:     Optional[int]						):
           pass



      @unittest.skip("Only checkpoints on timm can be loaded into TimmBackbone"						)
      def 						snake_case_ (					self					:     Tuple						):
           pass



      @unittest.skip("model weights aren't tied in TimmBackbone."						)
      def 						snake_case_ (					self					:     Tuple						):
           pass



      @unittest.skip("model weights aren't tied in TimmBackbone."						)
      def 						snake_case_ (					self					:     Union[str, Any]						):
           pass



      @unittest.skip("Only checkpoints on timm can be loaded into TimmBackbone"						)
      def 						snake_case_ (					self					:     List[Any]						):
           pass



      @unittest.skip("Only checkpoints on timm can be loaded into TimmBackbone"						)
      def 						snake_case_ (					self					:     Tuple						):
           pass



      @unittest.skip("TimmBackbone doesn't have hidden size info in its configuration."						)
      def 						snake_case_ (					self					:     Optional[int]						):
           pass



      @unittest.skip("TimmBackbone doesn't support output_attentions."						)
      def 						snake_case_ (					self					:     int						):
           pass



      @unittest.skip("Safetensors is not supported by timm."						)
      def 						snake_case_ (					self					:     Dict						):
           pass



      @unittest.skip("Will be fixed soon by reducing the size of the model used for common tests."						)
      def 						snake_case_ (					self					:     str						):
           pass



      def 						snake_case_ (					self					:     Union[str, Any]						):
           _UpperCAmelCase    ,	_UpperCAmelCase      :     int        =   self.model_tester.prepare_config_and_inputs_for_common()

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

                _UpperCAmelCase      :     Union[str, Any]        =   ["pixel_values"]
                self.assertListEqual(arg_names[:1]					,     A						)



      def 						snake_case_ (					self					:     List[str]						):
           _UpperCAmelCase    ,	_UpperCAmelCase      :     Any        =   self.model_tester.prepare_config_and_inputs_for_common()
           _UpperCAmelCase      :     Any        =   True
           _UpperCAmelCase      :     List[Any]        =   self.has_attentions

           # no need to test all models as different heads yield the same functionality
           _UpperCAmelCase      :     Optional[Any]        =   self.all_model_classes[0]
           _UpperCAmelCase      :     Optional[int]        =   model_class(A						)
           model.to(A						)

           _UpperCAmelCase      :     Any        =   self._prepare_for_class(A					,     A						)
           _UpperCAmelCase      :     int        =   model(**A						)
           _UpperCAmelCase      :     Dict        =   outputs[0][-1]

           # Encoder-/Decoder-only models
           _UpperCAmelCase      :     Union[str, Any]        =   outputs.hidden_states[0]
           hidden_states.retain_grad()

           if self.has_attentions:
                _UpperCAmelCase      :     List[str]        =   outputs.attentions[0]
                attentions.retain_grad()

           output.flatten()[0].backward(retain_graph=A						)

           self.assertIsNotNone(hidden_states.grad						)

           if self.has_attentions:
                self.assertIsNotNone(attentions.grad						)



      def 						snake_case_ (					self					:     int						):
           _UpperCAmelCase    ,	_UpperCAmelCase      :     List[Any]        =   self.model_tester.prepare_config_and_inputs_for_common()

           for model_class in self.all_model_classes:
                _UpperCAmelCase      :     List[Any]        =   model_class(A						)
                model.to(A						)
                model.eval()
                _UpperCAmelCase      :     Tuple        =   model(**A						)

                self.assertEqual(len(result.feature_maps						)					,     len(config.out_indices						)						)
                self.assertEqual(len(model.channels						)					,     len(config.out_indices						)						)

                # Check output of last stage is taken if out_features=None, out_indices=None
                _UpperCAmelCase      :     List[str]        =   copy.deepcopy(A						)
                _UpperCAmelCase      :     List[Any]        =   None
                _UpperCAmelCase      :     str        =   model_class(A						)
                model.to(A						)
                model.eval()
                _UpperCAmelCase      :     Union[str, Any]        =   model(**A						)

                self.assertEqual(len(result.feature_maps						)					,     1						)
                self.assertEqual(len(model.channels						)					,     1						)

                # Check backbone can be initialized with fresh weights
                _UpperCAmelCase      :     str        =   copy.deepcopy(A						)
                _UpperCAmelCase      :     Optional[Any]        =   False
                _UpperCAmelCase      :     str        =   model_class(A						)
                model.to(A						)
                model.eval()
                _UpperCAmelCase      :     Optional[Any]        =   model(**A						)





"""simple docstring"""




import importlib
import inspect
import os
import re


# 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
_lowerCAmelCase    : Dict							=							"src/transformers"


# This is to make sure the transformers module imported is the one in the repo.
_lowerCAmelCase    : List[Any]							=							importlib.util.spec_from_file_location(
    "transformers",
    os.path.join(PATH_TO_TRANSFORMERS, "__init__.py"),
    submodule_search_locations=[PATH_TO_TRANSFORMERS],
)
_lowerCAmelCase    : Tuple							=							spec.loader.load_module()

_lowerCAmelCase    : Tuple							=							transformers.models.auto.configuration_auto.CONFIG_MAPPING

# Regex pattern used to find the checkpoint mentioned in the docstring of `config_class`.
# For example, `[bert-base-uncased](https://huggingface.co/bert-base-uncased)`
_lowerCAmelCase    : Optional[int]							=							re.compile("\[(.+?)\]\((https://huggingface\.co/.+?)\)")


_lowerCAmelCase    : Optional[int]							=							{
    "CLIPConfigMixin",
    "DecisionTransformerConfigMixin",
    "EncoderDecoderConfigMixin",
    "RagConfigMixin",
    "SpeechEncoderDecoderConfigMixin",
    "VisionEncoderDecoderConfigMixin",
    "VisionTextDualEncoderConfigMixin",
}

def 						__snake_case						(				)  ->       Dict:





     '''simple docstring'''

     _UpperCAmelCase      :     List[str]        =   []

     for config_class in list(CONFIG_MAPPING.values()    ):
          _UpperCAmelCase      :     Union[str, Any]        =   False

          # source code of `config_class`
          _UpperCAmelCase      :     Optional[int]        =   inspect.getsource(SCREAMING_SNAKE_CASE__    )
          _UpperCAmelCase      :     List[Any]        =   _re_checkpoint.findall(SCREAMING_SNAKE_CASE__    )

          for checkpoint in checkpoints:
               # Each `checkpoint` is a tuple of a checkpoint name and a checkpoint link.
               # For example, `('bert-base-uncased', 'https://huggingface.co/bert-base-uncased')`
               _UpperCAmelCase    ,	_UpperCAmelCase      :     List[Any]        =   checkpoint

               # verify the checkpoint name corresponds to the checkpoint link
               _UpperCAmelCase      :     Optional[Any]        =   f'https://huggingface.co/{ckpt_name}'
               if ckpt_link == ckpt_link_from_name:
                    _UpperCAmelCase      :     Optional[Any]        =   True
                    break

          _UpperCAmelCase      :     int        =   config_class.__name__
          if not checkpoint_found and name not in CONFIG_CLASSES_TO_IGNORE_FOR_DOCSTRING_CHECKPOINT_CHECK:
               configs_without_checkpoint.append(SCREAMING_SNAKE_CASE__    )

     if len(SCREAMING_SNAKE_CASE__    ) > 0:
          _UpperCAmelCase      :     List[str]        =   "\n".join(sorted(SCREAMING_SNAKE_CASE__    )    )
          raise ValueError(f'The following configurations don\'t contain any valid checkpoint:\n{message}'    )


if __name__ == "__main__":
 check_config_docstrings_have_checkpoints()
