
"""simple docstring"""

from typing import Tuple, Union

from ...modeling_outputs import BackboneOutput
from ...modeling_utils import PreTrainedModel
from ...utils import is_timm_available, is_torch_available, requires_backends
from ...utils.backbone_utils import BackboneMixin
from .configuration_timm_backbone import TimmBackboneConfig


if is_timm_available():
   import timm


if is_torch_available():
   from torch import Tensor
class   _UpperCAmelCase				(		UpperCAmelCase__  ,      UpperCAmelCase__				):
      __SCREAMING_SNAKE_CASE :				Tuple				   =						"pixel_values"
      __SCREAMING_SNAKE_CASE :				Optional[Any]				   =						False
      __SCREAMING_SNAKE_CASE :				str				   =						TimmBackboneConfig




      def __init__(				self ,							lowercase_ ,							**lowercase_				)    ->       Optional[Any]:
          requires_backends(self ,							'timm'				)
          super().__init__(UpperCAmelCase__				)
          UpperCAmelCase          =       config

          if config.backbone is None:
              raise ValueError('backbone is not set in the config. Please set it to a timm model name.'				)

          if config.backbone not in timm.list_models():
              raise ValueError(F"backbone {config.backbone} is not supported by timm."				)

          if hasattr(UpperCAmelCase__ ,							'out_features'				) and config.out_features is not None:
              raise ValueError('out_features is not supported by TimmBackbone. Please use out_indices instead.'				)

          UpperCAmelCase          =       getattr(UpperCAmelCase__ ,							'use_pretrained_backbone' ,							UpperCAmelCase__				)
          if pretrained is None:
              raise ValueError('use_pretrained_backbone is not set in the config. Please set it to True or False.'				)

          # We just take the final layer by default. This matches the default for the transformers models.
          UpperCAmelCase          =       config.out_indices if getattr(UpperCAmelCase__ ,							'out_indices' ,							UpperCAmelCase__				) is not None else (-1,)

          UpperCAmelCase          =       timm.create_model(
              config.backbone ,							pretrained=UpperCAmelCase__ ,							features_only=config.features_only ,							in_chans=config.num_channels ,							out_indices=UpperCAmelCase__ ,							**UpperCAmelCase__ ,							)
          # These are used to control the output of the model when called. If output_hidden_states is True, then
          # return_layers is modified to include all layers.
          UpperCAmelCase          =       self._backbone.return_layers
          UpperCAmelCase          =       {layer['module']: str(UpperCAmelCase__				) for i, layer in enumerate(self._backbone.feature_info.info				)}
          super()._init_backbone(UpperCAmelCase__				)




      @classmethod
      def      a_   (				cls ,							lowercase_ ,							*lowercase_ ,							**lowercase_				)    ->       Union[str, Any]:
          requires_backends(cls ,							['vision', 'timm']				)
          from ...models.timm_backbone import TimmBackboneConfig

          UpperCAmelCase          =       kwargs.pop('config' ,							TimmBackboneConfig()				)

          UpperCAmelCase          =       kwargs.pop('use_timm_backbone' ,							UpperCAmelCase__				)
          if not use_timm:
              raise ValueError('use_timm_backbone must be True for timm backbones'				)

          UpperCAmelCase          =       kwargs.pop('num_channels' ,							config.num_channels				)
          UpperCAmelCase          =       kwargs.pop('features_only' ,							config.features_only				)
          UpperCAmelCase          =       kwargs.pop('use_pretrained_backbone' ,							config.use_pretrained_backbone				)
          UpperCAmelCase          =       kwargs.pop('out_indices' ,							config.out_indices				)
          UpperCAmelCase          =       TimmBackboneConfig(
              backbone=UpperCAmelCase__ ,							num_channels=UpperCAmelCase__ ,							features_only=UpperCAmelCase__ ,							use_pretrained_backbone=UpperCAmelCase__ ,							out_indices=UpperCAmelCase__ ,							)
          return super()._from_config(UpperCAmelCase__ ,							**UpperCAmelCase__				)




      def      a_   (				self ,							lowercase_				)    ->       int:
          pass




      def      a_   (				self ,							lowercase_ ,							lowercase_=None ,							lowercase_=None ,							lowercase_=None ,							**lowercase_				)    ->       Union[BackboneOutput, Tuple[Tensor, ...]]:
          UpperCAmelCase          =       return_dict if return_dict is not None else self.config.use_return_dict
          UpperCAmelCase          =       (
              output_hidden_states if output_hidden_states is not None else self.config.output_hidden_states
          )
          UpperCAmelCase          =       output_attentions if output_attentions is not None else self.config.output_attentions

          if output_attentions:
              raise ValueError('Cannot output attentions for timm backbones at the moment'				)

          if output_hidden_states:
              # We modify the return layers to include all the stages of the backbone
              UpperCAmelCase          =       self._all_layers
              UpperCAmelCase          =       self._backbone(UpperCAmelCase__ ,							**UpperCAmelCase__				)
              UpperCAmelCase          =       self._return_layers
              UpperCAmelCase          =       tuple(hidden_states[i] for i in self.out_indices				)
          else:
              UpperCAmelCase          =       self._backbone(UpperCAmelCase__ ,							**UpperCAmelCase__				)
              UpperCAmelCase          =       None

          UpperCAmelCase          =       tuple(UpperCAmelCase__				)
          UpperCAmelCase          =       tuple(UpperCAmelCase__				) if hidden_states is not None else None

          if not return_dict:
              UpperCAmelCase          =       (feature_maps,)
              if output_hidden_states:
                  UpperCAmelCase          =       output + (hidden_states,)
              return output

          return BackboneOutput(feature_maps=UpperCAmelCase__ ,							hidden_states=UpperCAmelCase__ ,							attentions=UpperCAmelCase__				)









from collections import OrderedDict
from typing import Mapping

from packaging import version

from ...configuration_utils import PretrainedConfig
from ...onnx import OnnxConfig
from ...utils import logging


_lowerCamelCase      :						Optional[Any]							=  logging.get_logger(__name__)

_lowerCamelCase      :						Union[str, Any]							=  {
    """google/mobilenet_v1_1.0_224""": """https://huggingface.co/google/mobilenet_v1_1.0_224/resolve/main/config.json""",
    """google/mobilenet_v1_0.75_192""": """https://huggingface.co/google/mobilenet_v1_0.75_192/resolve/main/config.json""",
    # See all MobileNetV1 models at https://huggingface.co/models?filter=mobilenet_v1
}


class 							UpperCamelCase_       (					UpperCAmelCase__	):

    '''simple docstring'''






    UpperCAmelCase__				    = '''mobilenet_v1'''


    def __init__(     self :      Optional[int]   ,					UpperCAmelCase__ :      Optional[int]=3   ,					UpperCAmelCase__ :      Optional[Any]=224   ,					UpperCAmelCase__ :      Optional[int]=1.0   ,					UpperCAmelCase__ :      Optional[int]=8   ,					UpperCAmelCase__ :      Tuple="relu6"   ,					UpperCAmelCase__ :      List[Any]=True   ,					UpperCAmelCase__ :      Dict=0.999   ,					UpperCAmelCase__ :      str=0.02   ,					UpperCAmelCase__ :      Optional[int]=0.001   ,					**UpperCAmelCase__ :      Dict   ,					)		->List[str]:





           '''simple docstring'''

           super().__init__(**UpperCAmelCase__)

           if depth_multiplier <= 0:
                  raise ValueError('''depth_multiplier must be greater than zero.''')

           A__ 					=       num_channels
           A__ 					=       image_size
           A__ 					=       depth_multiplier
           A__ 					=       min_depth
           A__ 					=       hidden_act
           A__ 					=       tf_padding
           A__ 					=       classifier_dropout_prob
           A__ 					=       initializer_range
           A__ 					=       layer_norm_eps


class 							UpperCamelCase_       (					UpperCAmelCase__	):

    '''simple docstring'''






    UpperCAmelCase__				    = version.parse('''1.11'''	)


    @property
    def 			SCREAMING_SNAKE_CASE				(     self :      Any)		->Mapping[str, Mapping[int, str]]:





           '''simple docstring'''

           return OrderedDict([('''pixel_values''', {0: '''batch'''})])


    @property
    def 			SCREAMING_SNAKE_CASE				(     self :      List[str])		->Mapping[str, Mapping[int, str]]:





           '''simple docstring'''

           if self.task == "image-classification":
                  return OrderedDict([('''logits''', {0: '''batch'''})])
           else:
                  return OrderedDict([('''last_hidden_state''', {0: '''batch'''}), ('''pooler_output''', {0: '''batch'''})])





    @property
    def 			SCREAMING_SNAKE_CASE				(     self :      int)		->float:





           '''simple docstring'''

           return 1e-4


