



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




 def __init__(    self						,					__UpperCAmelCase						,					**__UpperCAmelCase					):



    '''simple docstring'''
    requires_backends(self						,					'''timm'''					)
    super().__init__(__UpperCAmelCase					)
    __lowerCamelCase    				=     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.'''					)

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

    __lowerCamelCase    				=     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.
    __lowerCamelCase    				=     self._backbone.return_layers
    __lowerCamelCase    				=     {layer['''module''']: str(__UpperCAmelCase					) for i, layer in enumerate(self._backbone.feature_info.info					)}
    super()._init_backbone(__UpperCAmelCase					)




 @classmethod
 def 							lowerCamelCase   (    cls						,					__UpperCAmelCase						,					*__UpperCAmelCase						,					**__UpperCAmelCase					):



    '''simple docstring'''
    requires_backends(cls						,					['''vision''', '''timm''']					)
    from ...models.timm_backbone import TimmBackboneConfig

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

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

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




 def 							lowerCamelCase   (    self						,					__UpperCAmelCase					):



    '''simple docstring'''
    pass




 def 							lowerCamelCase   (    self						,					__UpperCAmelCase						,					__UpperCAmelCase=None						,					__UpperCAmelCase=None						,					__UpperCAmelCase=None						,					**__UpperCAmelCase					):



    '''simple docstring'''
    __lowerCamelCase    				=     return_dict if return_dict is not None else self.config.use_return_dict
    __lowerCamelCase    				=     (
        output_hidden_states if output_hidden_states is not None else self.config.output_hidden_states
    )
    __lowerCamelCase    				=     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
       __lowerCamelCase    				=     self._all_layers
       __lowerCamelCase    				=     self._backbone(__UpperCAmelCase						,					**__UpperCAmelCase					)
       __lowerCamelCase    				=     self._return_layers
       __lowerCamelCase    				=     tuple(hidden_states[i] for i in self.out_indices					)
    else:
       __lowerCamelCase    				=     self._backbone(__UpperCAmelCase						,					**__UpperCAmelCase					)
       __lowerCamelCase    				=     None

    __lowerCamelCase    				=     tuple(__UpperCAmelCase					)
    __lowerCamelCase    				=     tuple(__UpperCAmelCase					) if hidden_states is not None else None

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

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











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_								=       """
{0} = None
"""

a_								=       """
class {0}(metaclass=DummyObject):
    _backends = {1}

    def __init__(self, *args, **kwargs):
        requires_backends(self, {1})
"""


a_								=       """
def {0}(*args, **kwargs):
    requires_backends({0}, {1})
"""



class 			__lowerCAmelCase  (						unittest.TestCase ):




 def 							lowerCamelCase   (    self					):



    '''simple docstring'''
    __lowerCamelCase    				=     find_backend('''    _import_structure["models.albert"].append("AlbertTokenizerFast")'''					)
    self.assertIsNone(__UpperCAmelCase					)

    __lowerCamelCase    				=     find_backend('''    if not is_tokenizers_available():'''					)
    self.assertEqual(__UpperCAmelCase						,					'''tokenizers'''					)

    __lowerCamelCase    				=     find_backend('''    if not is_tensorflow_text_available():'''					)
    self.assertEqual(__UpperCAmelCase						,					'''tensorflow_text'''					)

    __lowerCamelCase    				=     find_backend('''    if not (is_sentencepiece_available() and is_tokenizers_available()):'''					)
    self.assertEqual(__UpperCAmelCase						,					'''sentencepiece_and_tokenizers'''					)

    __lowerCamelCase    				=     find_backend(
        '''    if not (is_sentencepiece_available() and is_tensorflow_text_available()):'''					)
    self.assertEqual(__UpperCAmelCase						,					'''sentencepiece_and_tensorflow_text'''					)

    __lowerCamelCase    				=     find_backend(
        '''    if not (is_sentencepiece_available() and is_tokenizers_available() and is_vision_available()):'''					)
    self.assertEqual(__UpperCAmelCase						,					'''sentencepiece_and_tokenizers_and_vision'''					)




 def 							lowerCamelCase   (    self					):



    '''simple docstring'''
    __lowerCamelCase    				=     read_init()
    # We don't assert on the exact list of keys to allow for smooth grow of backend-specific objects
    self.assertIn('''torch'''						,					__UpperCAmelCase					)
    self.assertIn('''tensorflow_text'''						,					__UpperCAmelCase					)
    self.assertIn('''sentencepiece_and_tokenizers'''						,					__UpperCAmelCase					)

    # 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 							lowerCamelCase   (    self					):



    '''simple docstring'''
    __lowerCamelCase    				=     create_dummy_object('''CONSTANT'''						,					'''\'torch\''''					)
    self.assertEqual(__UpperCAmelCase						,					'''\nCONSTANT = None\n'''					)

    __lowerCamelCase    				=     create_dummy_object('''function'''						,					'''\'torch\''''					)
    self.assertEqual(
        __UpperCAmelCase						,					'''\ndef function(*args, **kwargs):\n    requires_backends(function, \'torch\')\n'''					)

    __lowerCamelCase    				=     '''
class FakeClass(metaclass=DummyObject):
    _backends = \'torch\'

    def __init__(self, *args, **kwargs):
        requires_backends(self, \'torch\')
'''
    __lowerCamelCase    				=     create_dummy_object('''FakeClass'''						,					'''\'torch\''''					)
    self.assertEqual(__UpperCAmelCase						,					__UpperCAmelCase					)




 def 							lowerCamelCase   (    self					):



    '''simple docstring'''
    __lowerCamelCase    				=     '''# 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"])
'''
    __lowerCamelCase    				=     create_dummy_files({'''torch''': ['''CONSTANT''', '''function''', '''FakeClass''']}					)
    self.assertEqual(dummy_files['''torch''']						,					__UpperCAmelCase					)






