





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					(       __a   ,    __a      ):


	'''simple docstring'''





	_A													=				"pixel_values"
	_A													=				False
	_A													=				TimmBackboneConfig

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

			lowercase__					:      Tuple      =		getattr(lowercase_,					'use_pretrained_backbone',					lowercase_			)
			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.
			lowercase__					:      Optional[int]      =		config.out_indices if getattr(lowercase_,					'out_indices',					lowercase_			) is not None else (-1,)

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

	@classmethod
	def    snake_case__(						cls:						Tuple,					lowerCamelCase_:						List[Any],					*lowerCamelCase_:						List[str],					**lowerCamelCase_:						str			):
			requires_backends(cls,					['vision', 'timm']			)
			from ...models.timm_backbone import TimmBackboneConfig

			lowercase__					:      Optional[Any]      =		kwargs.pop('config',					TimmBackboneConfig()			)

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

			lowercase__					:      List[str]      =		kwargs.pop('num_channels',					config.num_channels			)
			lowercase__					:      Dict      =		kwargs.pop('features_only',					config.features_only			)
			lowercase__					:      str      =		kwargs.pop('use_pretrained_backbone',					config.use_pretrained_backbone			)
			lowercase__					:      Dict      =		kwargs.pop('out_indices',					config.out_indices			)
			lowercase__					:      Dict      =		TimmBackboneConfig(
			    backbone=lowercase_,					num_channels=lowercase_,					features_only=lowercase_,					use_pretrained_backbone=lowercase_,					out_indices=lowercase_,					)
			return super()._from_config(lowercase_,					**lowercase_			)

	def    snake_case__(						self:						Any,					lowerCamelCase_:						Tuple			):
			pass





	def    snake_case__(						self:						str,					lowerCamelCase_:						Dict,					lowerCamelCase_:						Optional[int]=None,					lowerCamelCase_:						Union[str, Any]=None,					lowerCamelCase_:						Any=None,					**lowerCamelCase_:						List[Any]			):
			lowercase__					:      int      =		return_dict if return_dict is not None else self.config.use_return_dict
			lowercase__					:      Optional[Any]      =		(
			    output_hidden_states if output_hidden_states is not None else self.config.output_hidden_states
			)
			lowercase__					:      List[str]      =		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
					lowercase__					:      str      =		self._all_layers
					lowercase__					:      Any      =		self._backbone(lowercase_,					**lowercase_			)
					lowercase__					:      int      =		self._return_layers
					lowercase__					:      List[Any]      =		tuple(hidden_states[i] for i in self.out_indices			)
			else:
					lowercase__					:      Optional[int]      =		self._backbone(lowercase_,					**lowercase_			)
					lowercase__					:      Dict      =		None

			lowercase__					:      List[str]      =		tuple(lowercase_			)
			lowercase__					:      Optional[Any]      =		tuple(lowercase_			) if hidden_states is not None else None

			if not return_dict:
					lowercase__					:      Optional[Any]      =		(feature_maps,)
					if output_hidden_states:
							lowercase__					:      Optional[int]      =		output + (hidden_states,)
					return output

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



'''simple docstring'''


from typing import TYPE_CHECKING

# rely on isort to merge the imports
from ...utils import OptionalDependencyNotAvailable, _LazyModule, is_torch_available


__snake_case						  =		{"""configuration_focalnet""": ["""FOCALNET_PRETRAINED_CONFIG_ARCHIVE_MAP""", """FocalNetConfig"""]}


try:
       if not is_torch_available():
              raise OptionalDependencyNotAvailable()
except OptionalDependencyNotAvailable:
       pass
else:
       __snake_case						  =		[
           """FOCALNET_PRETRAINED_MODEL_ARCHIVE_LIST""",
           """FocalNetForImageClassification""",
           """FocalNetForMaskedImageModeling""",
           """FocalNetBackbone""",
           """FocalNetModel""",
           """FocalNetPreTrainedModel""",
       ]

if TYPE_CHECKING:
       from .configuration_focalnet import FOCALNET_PRETRAINED_CONFIG_ARCHIVE_MAP, FocalNetConfig

       try:
              if not is_torch_available():
                     raise OptionalDependencyNotAvailable()
       except OptionalDependencyNotAvailable:
              pass
       else:
              from .modeling_focalnet import (
                  FOCALNET_PRETRAINED_MODEL_ARCHIVE_LIST,
                  FocalNetBackbone,
                  FocalNetForImageClassification,
                  FocalNetForMaskedImageModeling,
                  FocalNetModel,
                  FocalNetPreTrainedModel,
              )

else:
       import sys

       __snake_case						  =		_LazyModule(__name__, globals()["""__file__"""], _import_structure, module_spec=__spec__)

