
"""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 				lowerCAmelCase_				(      _lowercase		,					_lowercase    ):



						'''simple docstring'''


						_lowerCamelCase:    str      =    '''pixel_values'''
						_lowerCamelCase:    Any      =    False
						_lowerCamelCase:    List[Any]      =    TimmBackboneConfig


						def __init__( self     :      str  ,A_     :      Tuple  ,**A_     :      Union[str, Any]      )     ->   Any:
							requires_backends(self  ,'timm'      )
							super().__init__(A_      )
							A						   =   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(A_  ,'out_features'      ) and config.out_features is not None:
								raise ValueError('out_features is not supported by TimmBackbone. Please use out_indices instead.'      )

							A						   =   getattr(A_  ,'use_pretrained_backbone'  ,A_      )
							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.
							A						   =   config.out_indices if getattr(A_  ,'out_indices'  ,A_      ) is not None else (-1,)

							A						   =   timm.create_model(
							    config.backbone  ,pretrained=A_  ,features_only=config.features_only  ,in_chans=config.num_channels  ,out_indices=A_  ,**A_  ,)
							# 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.
							A						   =   self._backbone.return_layers
							A						   =   {layer['module']: str(A_      ) for i, layer in enumerate(self._backbone.feature_info.info      )}
							super()._init_backbone(A_      )


						@classmethod
						def 						_SCREAMING_SNAKE_CASE      ( cls     :      Optional[int]  ,A_     :      Union[str, Any]  ,*A_     :      List[Any]  ,**A_     :      Optional[Any]      )     ->   Optional[Any]:
							requires_backends(cls  ,['vision', 'timm']      )
							from ...models.timm_backbone import TimmBackboneConfig

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

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

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


						def 						_SCREAMING_SNAKE_CASE      ( self     :      str  ,A_     :      Any      )     ->   Any:
							pass




						def 						_SCREAMING_SNAKE_CASE      ( self     :      int  ,A_     :      int  ,A_     :      Optional[int]=None  ,A_     :      Any=None  ,A_     :      List[Any]=None  ,**A_     :      Optional[int]      )     ->   Union[BackboneOutput, Tuple[Tensor, ...]]:
							A						   =   return_dict if return_dict is not None else self.config.use_return_dict
							A						   =   (
							    output_hidden_states if output_hidden_states is not None else self.config.output_hidden_states
							)
							A						   =   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
								A						   =   self._all_layers
								A						   =   self._backbone(A_  ,**A_      )
								A						   =   self._return_layers
								A						   =   tuple(hidden_states[i] for i in self.out_indices      )
							else:
								A						   =   self._backbone(A_  ,**A_      )
								A						   =   None

							A						   =   tuple(A_      )
							A						   =   tuple(A_      ) if hidden_states is not None else None

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

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

"""simple docstring"""


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


_lowercase							   =				logging.get_logger(__name__)

_lowercase							   =				{
    '''hustvl/yolos-small''': '''https://huggingface.co/hustvl/yolos-small/resolve/main/config.json''',
    # See all YOLOS models at https://huggingface.co/models?filter=yolos
}







class 				lowerCAmelCase_				(      _lowercase    ):



						'''simple docstring'''


						_lowerCamelCase:    List[str]      =    '''yolos'''


						def __init__( self     :      Dict  ,A_     :      Optional[Any]=768  ,A_     :      int=12  ,A_     :      List[str]=12  ,A_     :      str=3072  ,A_     :      Tuple="gelu"  ,A_     :      Dict=0.0  ,A_     :      List[Any]=0.0  ,A_     :      Any=0.02  ,A_     :      str=1e-12  ,A_     :      List[Any]=[512, 864]  ,A_     :      Union[str, Any]=16  ,A_     :      List[str]=3  ,A_     :      Optional[int]=True  ,A_     :      Tuple=100  ,A_     :      str=True  ,A_     :      Optional[Any]=False  ,A_     :      Any=1  ,A_     :      Optional[Any]=5  ,A_     :      Optional[Any]=2  ,A_     :      Optional[int]=5  ,A_     :      List[Any]=2  ,A_     :      Union[str, Any]=0.1  ,**A_     :      Tuple  ,)     ->   Any:
							super().__init__(**A_      )

							A						   =   hidden_size
							A						   =   num_hidden_layers
							A						   =   num_attention_heads
							A						   =   intermediate_size
							A						   =   hidden_act
							A						   =   hidden_dropout_prob
							A						   =   attention_probs_dropout_prob
							A						   =   initializer_range
							A						   =   layer_norm_eps
							A						   =   image_size
							A						   =   patch_size
							A						   =   num_channels
							A						   =   qkv_bias
							A						   =   num_detection_tokens
							A						   =   use_mid_position_embeddings
							A						   =   auxiliary_loss
							# Hungarian matcher
							A						   =   class_cost
							A						   =   bbox_cost
							A						   =   giou_cost
							# Loss coefficients
							A						   =   bbox_loss_coefficient
							A						   =   giou_loss_coefficient
							A						   =   eos_coefficient







class 				lowerCAmelCase_				(      _lowercase    ):



						'''simple docstring'''


						_lowerCamelCase:    Any      =    version.parse('''1.11'''    )


						@property
						def 						_SCREAMING_SNAKE_CASE      ( self     :      Optional[int]      )     ->   Mapping[str, Mapping[int, str]]:
							return OrderedDict(
							    [
							        ('pixel_values', {0: 'batch', 1: 'num_channels', 2: 'height', 3: 'width'}),
							    ]      )


						@property
						def 						_SCREAMING_SNAKE_CASE      ( self     :      Any      )     ->   float:
							return 1e-4




						@property
						def 						_SCREAMING_SNAKE_CASE      ( self     :      Tuple      )     ->   int:
							return 12