




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       _A				(		__lowercase       ,     __lowercase     ):
		__a					    =       """pixel_values"""
		__a					    =       False
		__a					    =       TimmBackboneConfig






		def __init__(    self						,		_SCREAMING_SNAKE_CASE						,		**_SCREAMING_SNAKE_CASE			):
								requires_backends(self						,		"""timm"""			)
								super().__init__(_SCREAMING_SNAKE_CASE			)
								_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(_SCREAMING_SNAKE_CASE						,		"""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(_SCREAMING_SNAKE_CASE						,		"""use_pretrained_backbone"""						,		_SCREAMING_SNAKE_CASE			)
								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(_SCREAMING_SNAKE_CASE						,		"""out_indices"""						,		_SCREAMING_SNAKE_CASE			) is not None else (-1,)

								_UpperCAmelCase      =			timm.create_model(
								    config.backbone						,		pretrained=_SCREAMING_SNAKE_CASE						,		features_only=config.features_only						,		in_chans=config.num_channels						,		out_indices=_SCREAMING_SNAKE_CASE						,		**_SCREAMING_SNAKE_CASE						,		)
								# 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(_SCREAMING_SNAKE_CASE			) for i, layer in enumerate(self._backbone.feature_info.info			)}
								super()._init_backbone(_SCREAMING_SNAKE_CASE			)






		@classmethod
		def 				UpperCAmelCase (    cls						,		_SCREAMING_SNAKE_CASE						,		*_SCREAMING_SNAKE_CASE						,		**_SCREAMING_SNAKE_CASE			):
								requires_backends(cls						,		["""vision""", """timm"""]			)
								from ...models.timm_backbone import TimmBackboneConfig

								_UpperCAmelCase      =			kwargs.pop("""config"""						,		TimmBackboneConfig()			)

								_UpperCAmelCase      =			kwargs.pop("""use_timm_backbone"""						,		_SCREAMING_SNAKE_CASE			)
								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=_SCREAMING_SNAKE_CASE						,		num_channels=_SCREAMING_SNAKE_CASE						,		features_only=_SCREAMING_SNAKE_CASE						,		use_pretrained_backbone=_SCREAMING_SNAKE_CASE						,		out_indices=_SCREAMING_SNAKE_CASE						,		)
								return super()._from_config(_SCREAMING_SNAKE_CASE						,		**_SCREAMING_SNAKE_CASE			)






		def 				UpperCAmelCase (    self						,		_SCREAMING_SNAKE_CASE			):
								pass






		def 				UpperCAmelCase (    self						,		_SCREAMING_SNAKE_CASE						,		_SCREAMING_SNAKE_CASE=None						,		_SCREAMING_SNAKE_CASE=None						,		_SCREAMING_SNAKE_CASE=None						,		**_SCREAMING_SNAKE_CASE			):
								_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(_SCREAMING_SNAKE_CASE						,		**_SCREAMING_SNAKE_CASE			)
														_UpperCAmelCase      =			self._return_layers
														_UpperCAmelCase      =			tuple(hidden_states[i] for i in self.out_indices			)
								else:
														_UpperCAmelCase      =			self._backbone(_SCREAMING_SNAKE_CASE						,		**_SCREAMING_SNAKE_CASE			)
														_UpperCAmelCase      =			None

								_UpperCAmelCase      =			tuple(_SCREAMING_SNAKE_CASE			)
								_UpperCAmelCase      =			tuple(_SCREAMING_SNAKE_CASE			) 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=_SCREAMING_SNAKE_CASE						,		hidden_states=_SCREAMING_SNAKE_CASE						,		attentions=_SCREAMING_SNAKE_CASE			)





import os
import sys
import unittest


a													=			os.path.abspath(os.path.dirname(os.path.dirname(os.path.dirname(__file__))))
sys.path.append(os.path.join(git_repo_path, "utils"))

import check_dummies  # noqa: E402
from check_dummies import create_dummy_files, create_dummy_object, find_backend, read_init  # noqa: E402


# Align TRANSFORMERS_PATH in check_dummies with the current path
a													=			os.path.join(git_repo_path, "src", "transformers")

a													=			"\n{0} = None\n"

a													=			"\nclass {0}(metaclass=DummyObject):\n    _backends = {1}\n\n    def __init__(self, *args, **kwargs):\n        requires_backends(self, {1})\n"


a													=			"\ndef {0}(*args, **kwargs):\n    requires_backends({0}, {1})\n"




class       _A				(		unittest.TestCase     ):






		def 				UpperCAmelCase (    self			):
								_UpperCAmelCase      =			find_backend("""    _import_structure[\"models.albert\"].append(\"AlbertTokenizerFast\")"""			)
								self.assertIsNone(_SCREAMING_SNAKE_CASE			)

								_UpperCAmelCase      =			find_backend("""    if not is_tokenizers_available():"""			)
								self.assertEqual(_SCREAMING_SNAKE_CASE						,		"""tokenizers"""			)

								_UpperCAmelCase      =			find_backend("""    if not is_tensorflow_text_available():"""			)
								self.assertEqual(_SCREAMING_SNAKE_CASE						,		"""tensorflow_text"""			)

								_UpperCAmelCase      =			find_backend("""    if not (is_sentencepiece_available() and is_tokenizers_available()):"""			)
								self.assertEqual(_SCREAMING_SNAKE_CASE						,		"""sentencepiece_and_tokenizers"""			)

								_UpperCAmelCase      =			find_backend(
								    """    if not (is_sentencepiece_available() and is_tensorflow_text_available()):"""			)
								self.assertEqual(_SCREAMING_SNAKE_CASE						,		"""sentencepiece_and_tensorflow_text"""			)

								_UpperCAmelCase      =			find_backend(
								    """    if not (is_sentencepiece_available() and is_tokenizers_available() and is_vision_available()):"""			)
								self.assertEqual(_SCREAMING_SNAKE_CASE						,		"""sentencepiece_and_tokenizers_and_vision"""			)






		def 				UpperCAmelCase (    self			):
								_UpperCAmelCase      =			read_init()
								# We don't assert on the exact list of keys to allow for smooth grow of backend-specific objects
								self.assertIn("""torch"""						,		_SCREAMING_SNAKE_CASE			)
								self.assertIn("""tensorflow_text"""						,		_SCREAMING_SNAKE_CASE			)
								self.assertIn("""sentencepiece_and_tokenizers"""						,		_SCREAMING_SNAKE_CASE			)

								# Likewise, we can't assert on the exact content of a key
								self.assertIn("""BertModel"""						,		objects["""torch"""]			)
								self.assertIn("""TFBertModel"""						,		objects["""tf"""]			)
								self.assertIn("""FlaxBertModel"""						,		objects["""flax"""]			)
								self.assertIn("""BertModel"""						,		objects["""torch"""]			)
								self.assertIn("""TFBertTokenizer"""						,		objects["""tensorflow_text"""]			)
								self.assertIn("""convert_slow_tokenizer"""						,		objects["""sentencepiece_and_tokenizers"""]			)






		def 				UpperCAmelCase (    self			):
								_UpperCAmelCase      =			create_dummy_object("""CONSTANT"""						,		"""'torch'"""			)
								self.assertEqual(_SCREAMING_SNAKE_CASE						,		"""\nCONSTANT = None\n"""			)

								_UpperCAmelCase      =			create_dummy_object("""function"""						,		"""'torch'"""			)
								self.assertEqual(
								    _SCREAMING_SNAKE_CASE						,		"""\ndef function(*args, **kwargs):\n    requires_backends(function, 'torch')\n"""			)

								_UpperCAmelCase      =			"""
class FakeClass(metaclass=DummyObject):
    _backends = 'torch'

    def __init__(self, *args, **kwargs):
        requires_backends(self, 'torch')
"""
								_UpperCAmelCase      =			create_dummy_object("""FakeClass"""						,		"""'torch'"""			)
								self.assertEqual(_SCREAMING_SNAKE_CASE						,		_SCREAMING_SNAKE_CASE			)






		def 				UpperCAmelCase (    self			):
								_UpperCAmelCase      =			"""# This file is autogenerated by the command `make fix-copies`, do not edit.
from ..utils import DummyObject, requires_backends


CONSTANT = None


def function(*args, **kwargs):
    requires_backends(function, [\"torch\"])


class FakeClass(metaclass=DummyObject):
    _backends = [\"torch\"]

    def __init__(self, *args, **kwargs):
        requires_backends(self, [\"torch\"])
"""
								_UpperCAmelCase      =			create_dummy_files({"""torch""": ["""CONSTANT""", """function""", """FakeClass"""]}			)
								self.assertEqual(dummy_files["""torch"""]						,		_SCREAMING_SNAKE_CASE			)