'''simple docstring'''





import copy
import inspect
import unittest

from transformers import AutoBackbone
from transformers.configuration_utils import PretrainedConfig
from transformers.testing_utils import require_timm, require_torch, torch_device
from transformers.utils.import_utils import is_torch_available

from ...test_backbone_common import BackboneTesterMixin
from ...test_configuration_common import ConfigTester
from ...test_modeling_common import ModelTesterMixin, floats_tensor


if is_torch_available():
    import torch

    from transformers import TimmBackbone, TimmBackboneConfig

from ...test_pipeline_mixin import PipelineTesterMixin




class 	__A				:



    def __init__(self   :   int       ,      __a   :   Optional[int]       ,      __a   :   List[str]=None       ,      __a   :   Any=None       ,      __a   :   Optional[Any]=None       ,      __a   :   Tuple="resnet50"       ,      __a   :   Optional[int]=3       ,      __a   :   Optional[Any]=32       ,      __a   :   Any=3       ,      __a   :   Optional[int]=True       ,      __a   :   List[Any]=True       ,      ):
         UpperCAmelCase_	   =       parent
         UpperCAmelCase_	   =       out_indices if out_indices is not None else [4]
         UpperCAmelCase_	   =       stage_names
         UpperCAmelCase_	   =       out_features
         UpperCAmelCase_	   =       backbone
         UpperCAmelCase_	   =       batch_size
         UpperCAmelCase_	   =       image_size
         UpperCAmelCase_	   =       num_channels
         UpperCAmelCase_	   =       use_pretrained_backbone
         UpperCAmelCase_	   =       is_training



    def  _lowercase						(self   :   Optional[int]			):
         UpperCAmelCase_	   =       floats_tensor([self.batch_size, self.num_channels, self.image_size, self.image_size]			)
         UpperCAmelCase_	   =       self.get_config()

         return config, pixel_values



    def  _lowercase						(self   :   Optional[Any]			):
         return TimmBackboneConfig(
             image_size=self.image_size       ,      num_channels=self.num_channels       ,      out_features=self.out_features       ,      out_indices=self.out_indices       ,      stage_names=self.stage_names       ,      use_pretrained_backbone=self.use_pretrained_backbone       ,      backbone=self.backbone       ,      )



    def  _lowercase						(self   :   Optional[Any]       ,      __a   :   Any       ,      __a   :   Dict			):
         UpperCAmelCase_	   =       TimmBackbone(config=__a			)
         model.to(__a			)
         model.eval()
         with torch.no_grad():
              UpperCAmelCase_	   =       model(__a			)
         self.parent.assertEqual(
             result.feature_map[-1].shape       ,      (self.batch_size, model.channels[-1], 14, 14)       ,      )






    def  _lowercase						(self   :   Dict			):
         UpperCAmelCase_	   =       self.prepare_config_and_inputs()
         UpperCAmelCase_   ,			UpperCAmelCase_	   =       config_and_inputs
         UpperCAmelCase_	   =       {"pixel_values": pixel_values}
         return config, inputs_dict




@require_torch
@require_timm
class 	__A				(			UpperCamelCase__		,     UpperCamelCase__		,     UpperCamelCase__		,     unittest.TestCase     ):
    a__	:						List[str]	       =  (TimmBackbone,) if is_torch_available() else ()
    a__	:						Optional[Any]	       =  {"""feature-extraction""": TimmBackbone} if is_torch_available() else {}
    a__	:						str	       =  False
    a__	:						Optional[int]	       =  False
    a__	:						List[str]	       =  False
    a__	:						Dict	       =  False



    def  _lowercase						(self   :   Union[str, Any]			):
         UpperCAmelCase_	   =       TimmBackboneModelTester(self			)
         UpperCAmelCase_	   =       ConfigTester(self       ,      config_class=__a       ,      has_text_modality=__a			)



    def  _lowercase						(self   :   Union[str, Any]			):
         self.config_tester.create_and_test_config_to_json_string()
         self.config_tester.create_and_test_config_to_json_file()
         self.config_tester.create_and_test_config_from_and_save_pretrained()
         self.config_tester.create_and_test_config_with_num_labels()
         self.config_tester.check_config_can_be_init_without_params()
         self.config_tester.check_config_arguments_init()



    def  _lowercase						(self   :   Tuple			):
         UpperCAmelCase_	   =       "resnet18"
         UpperCAmelCase_	   =       "microsoft/resnet-18"

         UpperCAmelCase_	   =       AutoBackbone.from_pretrained(__a       ,      use_timm_backbone=__a			)
         UpperCAmelCase_	   =       AutoBackbone.from_pretrained(__a			)

         self.assertEqual(len(timm_model.out_features			)       ,      len(transformers_model.out_features			)			)
         self.assertEqual(len(timm_model.stage_names			)       ,      len(transformers_model.stage_names			)			)
         self.assertEqual(timm_model.channels       ,      transformers_model.channels			)
         # Out indices are set to the last layer by default. For timm models, we don't know
         # the number of layers in advance, so we set it to (-1,), whereas for transformers
         # models, we set it to [len(stage_names) - 1] (kept for backward compatibility).
         self.assertEqual(timm_model.out_indices       ,      (-1,)			)
         self.assertEqual(transformers_model.out_indices       ,      [len(timm_model.stage_names			) - 1]			)

         UpperCAmelCase_	   =       AutoBackbone.from_pretrained(__a       ,      use_timm_backbone=__a       ,      out_indices=[1, 2, 3]			)
         UpperCAmelCase_	   =       AutoBackbone.from_pretrained(__a       ,      out_indices=[1, 2, 3]			)

         self.assertEqual(timm_model.out_indices       ,      transformers_model.out_indices			)
         self.assertEqual(len(timm_model.out_features			)       ,      len(transformers_model.out_features			)			)
         self.assertEqual(timm_model.channels       ,      transformers_model.channels			)



    @unittest.skip("TimmBackbone doesn't support feed forward chunking"			)
    def  _lowercase						(self   :   Optional[Any]			):
         pass



    @unittest.skip("TimmBackbone doesn't have num_hidden_layers attribute"			)
    def  _lowercase						(self   :   Dict			):
         pass



    @unittest.skip("TimmBackbone initialization is managed on the timm side"			)
    def  _lowercase						(self   :   Union[str, Any]			):
         pass



    @unittest.skip("TimmBackbone models doesn't have inputs_embeds"			)
    def  _lowercase						(self   :   Any			):
         pass



    @unittest.skip("TimmBackbone models doesn't have inputs_embeds"			)
    def  _lowercase						(self   :   Optional[Any]			):
         pass



    @unittest.skip("TimmBackbone model cannot be created without specifying a backbone checkpoint"			)
    def  _lowercase						(self   :   Optional[Any]			):
         pass



    @unittest.skip("Only checkpoints on timm can be loaded into TimmBackbone"			)
    def  _lowercase						(self   :   str			):
         pass



    @unittest.skip("model weights aren't tied in TimmBackbone."			)
    def  _lowercase						(self   :   Any			):
         pass



    @unittest.skip("model weights aren't tied in TimmBackbone."			)
    def  _lowercase						(self   :   Any			):
         pass



    @unittest.skip("Only checkpoints on timm can be loaded into TimmBackbone"			)
    def  _lowercase						(self   :   Union[str, Any]			):
         pass



    @unittest.skip("Only checkpoints on timm can be loaded into TimmBackbone"			)
    def  _lowercase						(self   :   Optional[Any]			):
         pass



    @unittest.skip("TimmBackbone doesn't have hidden size info in its configuration."			)
    def  _lowercase						(self   :   List[str]			):
         pass



    @unittest.skip("TimmBackbone doesn't support output_attentions."			)
    def  _lowercase						(self   :   Union[str, Any]			):
         pass



    @unittest.skip("Safetensors is not supported by timm."			)
    def  _lowercase						(self   :   str			):
         pass



    @unittest.skip("Will be fixed soon by reducing the size of the model used for common tests."			)
    def  _lowercase						(self   :   List[str]			):
         pass



    def  _lowercase						(self   :   str			):
         UpperCAmelCase_   ,			UpperCAmelCase_	   =       self.model_tester.prepare_config_and_inputs_for_common()

         for model_class in self.all_model_classes:
              UpperCAmelCase_	   =       model_class(__a			)
              UpperCAmelCase_	   =       inspect.signature(model.forward			)
              # signature.parameters is an OrderedDict => so arg_names order is deterministic
              UpperCAmelCase_	   =       [*signature.parameters.keys()]

              UpperCAmelCase_	   =       ["pixel_values"]
              self.assertListEqual(arg_names[:1]       ,      __a			)



    def  _lowercase						(self   :   Tuple			):
         UpperCAmelCase_   ,			UpperCAmelCase_	   =       self.model_tester.prepare_config_and_inputs_for_common()
         UpperCAmelCase_	   =       True
         UpperCAmelCase_	   =       self.has_attentions

         # no need to test all models as different heads yield the same functionality
         UpperCAmelCase_	   =       self.all_model_classes[0]
         UpperCAmelCase_	   =       model_class(__a			)
         model.to(__a			)

         UpperCAmelCase_	   =       self._prepare_for_class(__a       ,      __a			)
         UpperCAmelCase_	   =       model(**__a			)
         UpperCAmelCase_	   =       outputs[0][-1]

         # Encoder-/Decoder-only models
         UpperCAmelCase_	   =       outputs.hidden_states[0]
         hidden_states.retain_grad()

         if self.has_attentions:
              UpperCAmelCase_	   =       outputs.attentions[0]
              attentions.retain_grad()

         output.flatten()[0].backward(retain_graph=__a			)

         self.assertIsNotNone(hidden_states.grad			)

         if self.has_attentions:
              self.assertIsNotNone(attentions.grad			)






    def  _lowercase						(self   :   Optional[int]			):
         UpperCAmelCase_   ,			UpperCAmelCase_	   =       self.model_tester.prepare_config_and_inputs_for_common()

         for model_class in self.all_model_classes:
              UpperCAmelCase_	   =       model_class(__a			)
              model.to(__a			)
              model.eval()
              UpperCAmelCase_	   =       model(**__a			)

              self.assertEqual(len(result.feature_maps			)       ,      len(config.out_indices			)			)
              self.assertEqual(len(model.channels			)       ,      len(config.out_indices			)			)

              # Check output of last stage is taken if out_features=None, out_indices=None
              UpperCAmelCase_	   =       copy.deepcopy(__a			)
              UpperCAmelCase_	   =       None
              UpperCAmelCase_	   =       model_class(__a			)
              model.to(__a			)
              model.eval()
              UpperCAmelCase_	   =       model(**__a			)

              self.assertEqual(len(result.feature_maps			)       ,      1			)
              self.assertEqual(len(model.channels			)       ,      1			)

              # Check backbone can be initialized with fresh weights
              UpperCAmelCase_	   =       copy.deepcopy(__a			)
              UpperCAmelCase_	   =       False
              UpperCAmelCase_	   =       model_class(__a			)
              model.to(__a			)
              model.eval()
              UpperCAmelCase_	   =       model(**__a			)





'''simple docstring'''





import unittest

from transformers import load_tool
from transformers.utils import is_torch_available


if is_torch_available():
    import torch

from transformers.testing_utils import require_torch

from .test_tools_common import ToolTesterMixin




@require_torch
class 	__A				(			unittest.TestCase		,     UpperCamelCase__     ):



    def  _lowercase						(self   :   Tuple			):
         UpperCAmelCase_	   =       load_tool("text-to-speech"			)
         self.tool.setup()



    def  _lowercase						(self   :   Union[str, Any]			):
         # SpeechT5 isn't deterministic
         torch.manual_seed(0			)
         UpperCAmelCase_	   =       self.tool("hey"			)
         UpperCAmelCase_	   =       result.to_raw()
         self.assertTrue(
             torch.allclose(
                 resulting_tensor[:3]       ,      torch.tensor([-0.0_00_59_66_66_88_32_11_58_29, -0.0_00_36_57_64_01_90_79_50_64, -0.00_01_34_39_50_27_99_88_34_85]			)       ,      )			)






    def  _lowercase						(self   :   List[str]			):
         # SpeechT5 isn't deterministic
         torch.manual_seed(0			)
         UpperCAmelCase_	   =       self.tool("hey"			)
         UpperCAmelCase_	   =       result.to_raw()
         self.assertTrue(
             torch.allclose(
                 resulting_tensor[:3]       ,      torch.tensor([-0.0_00_59_66_66_88_32_11_58_29, -0.0_00_36_57_64_01_90_79_50_64, -0.00_01_34_39_50_27_99_88_34_85]			)       ,      )			)




