





import dataclasses
import json
import sys
import types
from argparse import ArgumentDefaultsHelpFormatter, ArgumentParser, ArgumentTypeError
from copy import copy
from enum import Enum
from inspect import isclass
from pathlib import Path
from typing import Any, Callable, Dict, Iterable, List, Literal, NewType, Optional, Tuple, Union, get_type_hints

import yaml


snake_case_				=			NewType('DataClass', Any)
snake_case_				=			NewType('DataClassType', Any)






def lowerCamelCase__    (							snake_case_	:  str       )      ->				Optional[int]:
   if isinstance(snake_case_       ,      snake_case_       ):
      return v
   if v.lower() in ("yes", "true", "t", "y", "1"):
      return True
   elif v.lower() in ("no", "false", "f", "n", "0"):
      return False
   else:
      raise ArgumentTypeError(
          f"""Truthy value expected: got {v} but expected one of yes/no, true/false, t/f, y/n, 1/0 (case insensitive)."""       )






def lowerCamelCase__    (							snake_case_	:  list       )      ->				Callable[[str], Any]:
   __snake_case							       =   {str(snake_case_       ): choice for choice in choices}
   return lambda snake_case_       : str_to_choice.get(snake_case_       ,      snake_case_       )






def lowerCamelCase__    (							*,
    snake_case_	:  Union[str, List[str]] = None       ,      snake_case_	:  str = None       ,      snake_case_	:  Any = dataclasses.MISSING       ,      snake_case_	:  Callable[[], Any] = dataclasses.MISSING       ,      snake_case_	:  dict = None       ,      **snake_case_	:  int       ,      )      ->				dataclasses.Field:
   if metadata is None:
      # Important, don't use as default param in function signature because dict is mutable and shared across function calls
      __snake_case							       =   {}
   if aliases is not None:
      __snake_case							       =   aliases
   if help is not None:
      __snake_case							       =   help

   return dataclasses.field(metadata=snake_case_       ,      default=snake_case_       ,      default_factory=snake_case_       ,      **snake_case_       )







class 		SCREAMING_SNAKE_CASE__				(       _UpperCAmelCase  ):
      A_						:				Iterable[DataClassType]


      def __init__(self       :      Tuple				,			a__       :      Union[DataClassType, Iterable[DataClassType]]				,			**a__       :      Optional[Any]      ):





         """simple docstring"""



         if "formatter_class" not in kwargs:
            __snake_case							       =   ArgumentDefaultsHelpFormatter
         super().__init__(**a__      )
         if dataclasses.is_dataclass(a__      ):
            __snake_case							       =   [dataclass_types]
         __snake_case							       =   list(a__      )
         for dtype in self.dataclass_types:
            self._add_dataclass_arguments(a__      )


      @staticmethod
      def    a (a__       :      ArgumentParser				,			a__       :      dataclasses.Field      ):





         """simple docstring"""



         __snake_case							       =   f"""--{field.name}"""
         __snake_case							       =   field.metadata.copy()
         # field.metadata is not used at all by Data Classes,
         # it is provided as a third-party extension mechanism.
         if isinstance(field.type				,			a__      ):
            raise RuntimeError(
                '''Unresolved type detected, which should have been done with the help of '''
                '''`typing.get_type_hints` method by default'''      )

         __snake_case							       =   kwargs.pop('''aliases'''				,			[]      )
         if isinstance(a__				,			a__      ):
            __snake_case							       =   [aliases]

         __snake_case							       =   getattr(field.type				,			'''__origin__'''				,			field.type      )
         if origin_type is Union or (hasattr(a__				,			'''UnionType'''      ) and isinstance(a__				,			types.UnionType      )):
            if str not in field.type.__args__ and (
                len(field.type.__args__      ) != 2 or type(a__      ) not in field.type.__args__
            ):
               raise ValueError(
                   '''Only `Union[X, NoneType]` (i.e., `Optional[X]`) is allowed for `Union` because'''
                   ''' the argument parser only supports one type per argument.'''
                   f""" Problem encountered in field '{field.name}'."""      )
            if type(a__      ) not in field.type.__args__:
               # filter `str` in Union
               __snake_case							       =   field.type.__args__[0] if field.type.__args__[1] == str else field.type.__args__[1]
               __snake_case							       =   getattr(field.type				,			'''__origin__'''				,			field.type      )
            elif bool not in field.type.__args__:
               # filter `NoneType` in Union (except for `Union[bool, NoneType]`)
               __snake_case							       =   (
                   field.type.__args__[0] if isinstance(a__				,			field.type.__args__[1]      ) else field.type.__args__[1]
               )
               __snake_case							       =   getattr(field.type				,			'''__origin__'''				,			field.type      )

        # A variable to store kwargs for a boolean field, if needed
        # so that we can init a `no_*` complement argument (see below)
         __snake_case							       =   {}
         if origin_type is Literal or (isinstance(field.type				,			a__      ) and issubclass(field.type				,			a__      )):
            if origin_type is Literal:
               __snake_case							       =   field.type.__args__
            else:
               __snake_case							       =   [x.value for x in field.type]

            __snake_case							       =   make_choice_type_function(kwargs['''choices''']      )

            if field.default is not dataclasses.MISSING:
               __snake_case							       =   field.default
            else:
               __snake_case							       =   True
         elif field.type is bool or field.type == Optional[bool]:
            # Copy the currect kwargs to use to instantiate a `no_*` complement argument below.
            # We do not initialize it here because the `no_*` alternative must be instantiated after the real argument
            __snake_case							       =   copy(a__      )

            # Hack because type=bool in argparse does not behave as we want.
            __snake_case							       =   string_to_bool
            if field.type is bool or (field.default is not None and field.default is not dataclasses.MISSING):
               # Default value is False if we have no default when of type bool.
               __snake_case							       =   False if field.default is dataclasses.MISSING else field.default
               # This is the value that will get picked if we don't include --field_name in any way
               __snake_case							       =   default
               # This tells argparse we accept 0 or 1 value after --field_name
               __snake_case							       =   '''?'''
               # This is the value that will get picked if we do --field_name (without value)
               __snake_case							       =   True
         elif isclass(a__      ) and issubclass(a__				,			a__      ):
            __snake_case							       =   field.type.__args__[0]
            __snake_case							       =   '''+'''
            if field.default_factory is not dataclasses.MISSING:
               __snake_case							       =   field.default_factory()
            elif field.default is dataclasses.MISSING:
               __snake_case							       =   True
         else:
            __snake_case							       =   field.type
            if field.default is not dataclasses.MISSING:
               __snake_case							       =   field.default
            elif field.default_factory is not dataclasses.MISSING:
               __snake_case							       =   field.default_factory()
            else:
               __snake_case							       =   True
         parser.add_argument(a__				,			*a__				,			**a__      )

         # Add a complement `no_*` argument for a boolean field AFTER the initial field has already been added.
         # Order is important for arguments with the same destination!
         # We use a copy of earlier kwargs because the original kwargs have changed a lot before reaching down
         # here and we do not need those changes/additional keys.
         if field.default is True and (field.type is bool or field.type == Optional[bool]):
            __snake_case							       =   False
            parser.add_argument(f"""--no_{field.name}"""				,			action='''store_false'''				,			dest=field.name				,			**a__      )


      def    a (self       :      int				,			a__       :      DataClassType      ):





         """simple docstring"""



         if hasattr(a__				,			'''_argument_group_name'''      ):
            __snake_case							       =   self.add_argument_group(dtype._argument_group_name      )
         else:
            __snake_case							       =   self

         try:
            __snake_case							       =   get_type_hints(a__      )
         except NameError:
            raise RuntimeError(
                f"""Type resolution failed for {dtype}. Try declaring the class in global scope or """
                '''removing line of `from __future__ import annotations` which opts in Postponed '''
                '''Evaluation of Annotations (PEP 563)'''      )
         except TypeError as ex:
            # Remove this block when we drop Python 3.9 support
            if sys.version_info[:2] < (3, 10) and "unsupported operand type(s) for |" in str(a__      ):
               __snake_case							       =   '''.'''.join(map(a__				,			sys.version_info[:3]      )      )
               raise RuntimeError(
                   f"""Type resolution failed for {dtype} on Python {python_version}. Try removing """
                   '''line of `from __future__ import annotations` which opts in union types as '''
                   '''`X | Y` (PEP 604) via Postponed Evaluation of Annotations (PEP 563). To '''
                   '''support Python versions that lower than 3.10, you need to use '''
                   '''`typing.Union[X, Y]` instead of `X | Y` and `typing.Optional[X]` instead of '''
                   '''`X | None`.'''      ) from ex
            raise

         for field in dataclasses.fields(a__      ):
            if not field.init:
               continue
            __snake_case							       =   type_hints[field.name]
            self._parse_dataclass_field(a__				,			a__      )


      def    a (self       :      Union[str, Any]				,			a__       :      List[Any]=None				,			a__       :      List[Any]=False				,			a__       :      str=True				,			a__       :      List[Any]=None				,			a__       :      Tuple=None				,			):





         """simple docstring"""



         if args_file_flag or args_filename or (look_for_args_file and len(sys.argv      )):
            __snake_case							       =   []

            if args_filename:
               args_files.append(Path(a__      )      )
            elif look_for_args_file and len(sys.argv      ):
               args_files.append(Path(sys.argv[0]      ).with_suffix('''.args'''      )      )

            # args files specified via command line flag should overwrite default args files so we add them last
            if args_file_flag:
               # Create special parser just to extract the args_file_flag values
               __snake_case							       =   ArgumentParser()
               args_file_parser.add_argument(a__				,			type=a__				,			action='''append'''      )

               # Use only remaining args for further parsing (remove the args_file_flag)
               __snake_case       ,	__snake_case							       =   args_file_parser.parse_known_args(args=a__      )
               __snake_case							       =   vars(a__      ).get(args_file_flag.lstrip('''-'''      )				,			a__      )

               if cmd_args_file_paths:
                  args_files.extend([Path(a__      ) for p in cmd_args_file_paths]      )

            __snake_case							       =   []
            for args_file in args_files:
               if args_file.exists():
                  file_args += args_file.read_text().split()

            # in case of duplicate arguments the last one has precedence
            # args specified via the command line should overwrite args from files, so we add them last
            __snake_case							       =   file_args + args if args is not None else file_args + sys.argv[1:]
         __snake_case       ,	__snake_case							       =   self.parse_known_args(args=a__      )
         __snake_case							       =   []
         for dtype in self.dataclass_types:
            __snake_case							       =   {f.name for f in dataclasses.fields(a__      ) if f.init}
            __snake_case							       =   {k: v for k, v in vars(a__      ).items() if k in keys}
            for k in keys:
               delattr(a__				,			a__      )
            __snake_case							       =   dtype(**a__      )
            outputs.append(a__      )
         if len(namespace.__dict__      ) > 0:
            # additional namespace.
            outputs.append(a__      )
         if return_remaining_strings:
            return (*outputs, remaining_args)
         else:
            if remaining_args:
               raise ValueError(f"""Some specified arguments are not used by the HfArgumentParser: {remaining_args}"""      )

            return (*outputs,)


      def    a (self       :      Dict				,			a__       :      Dict[str, Any]				,			a__       :      bool = False      ):





         """simple docstring"""



         __snake_case							       =   set(args.keys()      )
         __snake_case							       =   []
         for dtype in self.dataclass_types:
            __snake_case							       =   {f.name for f in dataclasses.fields(a__      ) if f.init}
            __snake_case							       =   {k: v for k, v in args.items() if k in keys}
            unused_keys.difference_update(inputs.keys()      )
            __snake_case							       =   dtype(**a__      )
            outputs.append(a__      )
         if not allow_extra_keys and unused_keys:
            raise ValueError(f"""Some keys are not used by the HfArgumentParser: {sorted(a__      )}"""      )
         return tuple(a__      )


      def    a (self       :      Union[str, Any]				,			a__       :      str				,			a__       :      bool = False      ):





         """simple docstring"""



         with open(Path(a__      )				,			encoding='''utf-8'''      ) as open_json_file:
            __snake_case							       =   json.loads(open_json_file.read()      )
         __snake_case							       =   self.parse_dict(a__				,			allow_extra_keys=a__      )
         return tuple(a__      )


      def    a (self       :      Union[str, Any]				,			a__       :      str				,			a__       :      bool = False      ):





         """simple docstring"""



         __snake_case							       =   self.parse_dict(yaml.safe_load(Path(a__      ).read_text()      )				,			allow_extra_keys=a__      )
         return tuple(a__      )








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 		SCREAMING_SNAKE_CASE__				:


      def __init__(self       :      str				,			a__       :      Dict				,			a__       :      Tuple=None				,			a__       :      List[Any]=None				,			a__       :      Dict=None				,			a__       :      Union[str, Any]="resnet50"				,			a__       :      Dict=3				,			a__       :      str=32				,			a__       :      int=3				,			a__       :      Dict=True				,			a__       :      Any=True				,			):





         """simple docstring"""



         __snake_case							       =   parent
         __snake_case							       =   out_indices if out_indices is not None else [4]
         __snake_case							       =   stage_names
         __snake_case							       =   out_features
         __snake_case							       =   backbone
         __snake_case							       =   batch_size
         __snake_case							       =   image_size
         __snake_case							       =   num_channels
         __snake_case							       =   use_pretrained_backbone
         __snake_case							       =   is_training


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





         """simple docstring"""



         __snake_case							       =   floats_tensor([self.batch_size, self.num_channels, self.image_size, self.image_size]      )
         __snake_case							       =   self.get_config()

         return config, pixel_values


      def    a (self       :      Any      ):





         """simple docstring"""



         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    a (self       :      List[Any]				,			a__       :      int				,			a__       :      int      ):





         """simple docstring"""



         __snake_case							       =   TimmBackbone(config=a__      )
         model.to(a__      )
         model.eval()
         with torch.no_grad():
            __snake_case							       =   model(a__      )
         self.parent.assertEqual(
             result.feature_map[-1].shape				,			(self.batch_size, model.channels[-1], 14, 14)				,			)


      def    a (self       :      str      ):





         """simple docstring"""



         __snake_case							       =   self.prepare_config_and_inputs()
         __snake_case       ,	__snake_case							       =   config_and_inputs
         __snake_case							       =   {'''pixel_values''': pixel_values}
         return config, inputs_dict






@require_torch
@require_timm
class 		SCREAMING_SNAKE_CASE__				(       _UpperCAmelCase						,      _UpperCAmelCase						,      _UpperCAmelCase						,      unittest.TestCase  ):
      A_						:				Union[str, Any]							=    (TimmBackbone,) if is_torch_available() else ()
      A_						:				Optional[Any]							=    {'feature-extraction': TimmBackbone} if is_torch_available() else {}
      A_						:				List[Any]							=    False
      A_						:				Dict							=    False
      A_						:				Any							=    False
      A_						:				List[Any]							=    False


      def    a (self       :      Tuple      ):





         """simple docstring"""



         __snake_case							       =   TimmBackboneModelTester(self      )
         __snake_case							       =   ConfigTester(self				,			config_class=a__				,			has_text_modality=a__      )


      def    a (self       :      Any      ):





         """simple docstring"""



         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    a (self       :      int      ):





         """simple docstring"""



         __snake_case							       =   '''resnet18'''
         __snake_case							       =   '''microsoft/resnet-18'''

         __snake_case							       =   AutoBackbone.from_pretrained(a__				,			use_timm_backbone=a__      )
         __snake_case							       =   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]      )

         __snake_case							       =   AutoBackbone.from_pretrained(a__				,			use_timm_backbone=a__				,			out_indices=[1, 2, 3]      )
         __snake_case							       =   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    a (self       :      str      ):





         """simple docstring"""



         pass


      @unittest.skip('''TimmBackbone doesn\'t have num_hidden_layers attribute'''      )
      def    a (self       :      int      ):





         """simple docstring"""



         pass


      @unittest.skip('''TimmBackbone initialization is managed on the timm side'''      )
      def    a (self       :      Union[str, Any]      ):





         """simple docstring"""



         pass


      @unittest.skip('''TimmBackbone models doesn\'t have inputs_embeds'''      )
      def    a (self       :      Optional[int]      ):





         """simple docstring"""



         pass


      @unittest.skip('''TimmBackbone models doesn\'t have inputs_embeds'''      )
      def    a (self       :      int      ):





         """simple docstring"""



         pass


      @unittest.skip('''TimmBackbone model cannot be created without specifying a backbone checkpoint'''      )
      def    a (self       :      Tuple      ):





         """simple docstring"""



         pass


      @unittest.skip('''Only checkpoints on timm can be loaded into TimmBackbone'''      )
      def    a (self       :      int      ):





         """simple docstring"""



         pass


      @unittest.skip('''model weights aren\'t tied in TimmBackbone.'''      )
      def    a (self       :      Optional[Any]      ):





         """simple docstring"""



         pass


      @unittest.skip('''model weights aren\'t tied in TimmBackbone.'''      )
      def    a (self       :      Tuple      ):





         """simple docstring"""



         pass


      @unittest.skip('''Only checkpoints on timm can be loaded into TimmBackbone'''      )
      def    a (self       :      Dict      ):





         """simple docstring"""



         pass


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





         """simple docstring"""



         pass


      @unittest.skip('''TimmBackbone doesn\'t have hidden size info in its configuration.'''      )
      def    a (self       :      Optional[Any]      ):





         """simple docstring"""



         pass


      @unittest.skip('''TimmBackbone doesn\'t support output_attentions.'''      )
      def    a (self       :      List[Any]      ):





         """simple docstring"""



         pass


      @unittest.skip('''Safetensors is not supported by timm.'''      )
      def    a (self       :      Tuple      ):





         """simple docstring"""



         pass


      @unittest.skip('''Will be fixed soon by reducing the size of the model used for common tests.'''      )
      def    a (self       :      Tuple      ):





         """simple docstring"""



         pass


      def    a (self       :      Tuple      ):





         """simple docstring"""



         __snake_case       ,	__snake_case							       =   self.model_tester.prepare_config_and_inputs_for_common()

         for model_class in self.all_model_classes:
            __snake_case							       =   model_class(a__      )
            __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]				,			a__      )


      def    a (self       :      Dict      ):





         """simple docstring"""



         __snake_case       ,	__snake_case							       =   self.model_tester.prepare_config_and_inputs_for_common()
         __snake_case							       =   True
         __snake_case							       =   self.has_attentions

         # no need to test all models as different heads yield the same functionality
         __snake_case							       =   self.all_model_classes[0]
         __snake_case							       =   model_class(a__      )
         model.to(a__      )

         __snake_case							       =   self._prepare_for_class(a__				,			a__      )
         __snake_case							       =   model(**a__      )
         __snake_case							       =   outputs[0][-1]

         # Encoder-/Decoder-only models
         __snake_case							       =   outputs.hidden_states[0]
         hidden_states.retain_grad()

         if self.has_attentions:
            __snake_case							       =   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    a (self       :      Optional[int]      ):





         """simple docstring"""



         __snake_case       ,	__snake_case							       =   self.model_tester.prepare_config_and_inputs_for_common()

         for model_class in self.all_model_classes:
            __snake_case							       =   model_class(a__      )
            model.to(a__      )
            model.eval()
            __snake_case							       =   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
            __snake_case							       =   copy.deepcopy(a__      )
            __snake_case							       =   None
            __snake_case							       =   model_class(a__      )
            model.to(a__      )
            model.eval()
            __snake_case							       =   model(**a__      )

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

            # Check backbone can be initialized with fresh weights
            __snake_case							       =   copy.deepcopy(a__      )
            __snake_case							       =   False
            __snake_case							       =   model_class(a__      )
            model.to(a__      )
            model.eval()
            __snake_case							       =   model(**a__      )

