


'''simple docstring'''



from __future__ import annotations

import copy
import inspect
import json
import math
import os
import tempfile
import unittest
from importlib import import_module

import numpy as np

from transformers import ViTMAEConfig
from transformers.file_utils import cached_property, is_tf_available, is_vision_available
from transformers.testing_utils import require_tf, require_vision, slow

from ...test_configuration_common import ConfigTester
from ...test_modeling_tf_common import TFModelTesterMixin, floats_tensor, ids_tensor
from ...test_pipeline_mixin import PipelineTesterMixin


if is_tf_available():
      import tensorflow as tf

      from transformers import TFViTMAEForPreTraining, TFViTMAEModel


if is_vision_available():
      from PIL import Image

      from transformers import ViTImageProcessor



class      a    :


     """simple docstring"""






     def __init__(    self					:		Optional[int]							,			snake_case					:		Any							,			snake_case					:		List[str]=13							,			snake_case					:		Optional[Any]=30							,			snake_case					:		List[str]=2							,			snake_case					:		int=3							,			snake_case					:		List[str]=True							,			snake_case					:		Optional[Any]=True							,			snake_case					:		List[str]=32							,			snake_case					:		Dict=2							,			snake_case					:		List[str]=4							,			snake_case					:		Union[str, Any]=37							,			snake_case					:		Tuple="gelu"							,			snake_case					:		Union[str, Any]=0.1							,			snake_case					:		List[Any]=0.1							,			snake_case					:		Union[str, Any]=10							,			snake_case					:		Optional[int]=0.02							,			snake_case					:		int=3							,			snake_case					:		Optional[Any]=0.6							,			snake_case					:		Optional[int]=None							,			)						->							Dict:
          __UpperCAmelCase     :			int  							=      parent
          __UpperCAmelCase     :			List[str]  							=      batch_size
          __UpperCAmelCase     :			List[str]  							=      image_size
          __UpperCAmelCase     :			Dict  							=      patch_size
          __UpperCAmelCase     :			Any  							=      num_channels
          __UpperCAmelCase     :			int  							=      is_training
          __UpperCAmelCase     :			str  							=      use_labels
          __UpperCAmelCase     :			Tuple  							=      hidden_size
          __UpperCAmelCase     :			List[str]  							=      num_hidden_layers
          __UpperCAmelCase     :			Union[str, Any]  							=      num_attention_heads
          __UpperCAmelCase     :			Dict  							=      intermediate_size
          __UpperCAmelCase     :			Tuple  							=      hidden_act
          __UpperCAmelCase     :			int  							=      hidden_dropout_prob
          __UpperCAmelCase     :			List[str]  							=      attention_probs_dropout_prob
          __UpperCAmelCase     :			Union[str, Any]  							=      type_sequence_label_size
          __UpperCAmelCase     :			Union[str, Any]  							=      initializer_range
          __UpperCAmelCase     :			str  							=      mask_ratio
          __UpperCAmelCase     :			List[Any]  							=      scope

          # in ViTMAE, the expected sequence length = (num_patches + 1) * (1 - config.mask_ratio), rounded above
          # (we add 1 for the [CLS] token)
          __UpperCAmelCase     :			Tuple  							=      (image_size // patch_size) ** 2
          __UpperCAmelCase     :			str  							=      int(math.ceil((1 - mask_ratio) * (num_patches + 1)      )      )

     def 			lowerCamelCase__			(    self					:		Optional[int]      )						->							Union[str, Any]:
          __UpperCAmelCase     :			List[str]  							=      floats_tensor([self.batch_size, self.num_channels, self.image_size, self.image_size]      )

          __UpperCAmelCase     :			List[str]  							=      None
          if self.use_labels:
               __UpperCAmelCase     :			Any  							=      ids_tensor([self.batch_size]							,			self.type_sequence_label_size      )

          __UpperCAmelCase     :			Optional[Any]  							=      self.get_config()

          return config, pixel_values, labels

     def 			lowerCamelCase__			(    self					:		Tuple      )						->							Optional[Any]:
          return ViTMAEConfig(
              image_size=self.image_size							,			patch_size=self.patch_size							,			num_channels=self.num_channels							,			hidden_size=self.hidden_size							,			num_hidden_layers=self.num_hidden_layers							,			num_attention_heads=self.num_attention_heads							,			intermediate_size=self.intermediate_size							,			decoder_hidden_size=self.hidden_size							,			decoder_num_hidden_layers=self.num_hidden_layers							,			decoder_num_attention_heads=self.num_attention_heads							,			decoder_intermediate_size=self.intermediate_size							,			hidden_act=self.hidden_act							,			hidden_dropout_prob=self.hidden_dropout_prob							,			attention_probs_dropout_prob=self.attention_probs_dropout_prob							,			is_decoder=snake_case							,			initializer_range=self.initializer_range							,			mask_ratio=self.mask_ratio							,			)

     def 			lowerCamelCase__			(    self					:		Tuple							,			snake_case					:		Any							,			snake_case					:		Optional[Any]							,			snake_case					:		Optional[Any]      )						->							int:
          __UpperCAmelCase     :			Optional[int]  							=      TFViTMAEModel(config=snake_case      )
          __UpperCAmelCase     :			str  							=      model(snake_case							,			training=snake_case      )
          self.parent.assertEqual(result.last_hidden_state.shape							,			(self.batch_size, self.seq_length, self.hidden_size)      )

     def 			lowerCamelCase__			(    self					:		str							,			snake_case					:		Optional[Any]							,			snake_case					:		Dict							,			snake_case					:		Optional[Any]      )						->							Tuple:
          __UpperCAmelCase     :			Optional[Any]  							=      TFViTMAEForPreTraining(snake_case      )
          __UpperCAmelCase     :			List[str]  							=      model(snake_case							,			training=snake_case      )
          # expected sequence length = num_patches
          __UpperCAmelCase     :			int  							=      (self.image_size // self.patch_size) ** 2
          __UpperCAmelCase     :			Tuple  							=      self.patch_size**2 * self.num_channels
          self.parent.assertEqual(result.logits.shape							,			(self.batch_size, num_patches, expected_num_channels)      )

          # test greyscale images
          __UpperCAmelCase     :			List[str]  							=      1
          __UpperCAmelCase     :			Optional[int]  							=      TFViTMAEForPreTraining(snake_case      )

          __UpperCAmelCase     :			Tuple  							=      floats_tensor([self.batch_size, 1, self.image_size, self.image_size]      )
          __UpperCAmelCase     :			Any  							=      model(snake_case							,			training=snake_case      )
          __UpperCAmelCase     :			List[Any]  							=      self.patch_size**2
          self.parent.assertEqual(result.logits.shape							,			(self.batch_size, num_patches, expected_num_channels)      )






     def 			lowerCamelCase__			(    self					:		Optional[int]      )						->							Dict:
          __UpperCAmelCase     :			Optional[int]  							=      self.prepare_config_and_inputs()
          ((__UpperCAmelCase)							,       (__UpperCAmelCase)							,       (__UpperCAmelCase))     :			str  							=      config_and_inputs
          __UpperCAmelCase     :			str  							=      {'''pixel_values''': pixel_values}
          return config, inputs_dict



@require_tf
class      a    (		_a     ,  _a     ,  unittest.TestCase	):


     """simple docstring"""






     SCREAMING_SNAKE_CASE	:			Union[str, Any]							       =       (TFViTMAEModel, TFViTMAEForPreTraining) if is_tf_available() else ()
     SCREAMING_SNAKE_CASE	:			Optional[int]							       =       {"feature-extraction": TFViTMAEModel} if is_tf_available() else {}

     SCREAMING_SNAKE_CASE	:			int							       =       False
     SCREAMING_SNAKE_CASE	:			List[str]							       =       False
     SCREAMING_SNAKE_CASE	:			Dict							       =       False
     SCREAMING_SNAKE_CASE	:			Tuple							       =       False

     def 			lowerCamelCase__			(    self					:		Dict      )						->							Optional[Any]:
          __UpperCAmelCase     :			List[Any]  							=      TFViTMAEModelTester(self      )
          __UpperCAmelCase     :			int  							=      ConfigTester(self							,			config_class=snake_case							,			has_text_modality=snake_case							,			hidden_size=37      )

     def 			lowerCamelCase__			(    self					:		Any      )						->							Optional[Any]:
          self.config_tester.run_common_tests()

     @unittest.skip(reason='''ViTMAE does not use inputs_embeds'''      )
     def 			lowerCamelCase__			(    self					:		Dict      )						->							int:
          pass

     def 			lowerCamelCase__			(    self					:		Optional[int]      )						->							Dict:
          __UpperCAmelCase							,       __UpperCAmelCase     :			List[Any]  							=      self.model_tester.prepare_config_and_inputs_for_common()

          for model_class in self.all_model_classes:
               __UpperCAmelCase     :			str  							=      model_class(snake_case      )
               self.assertIsInstance(model.get_input_embeddings()							,			(tf.keras.layers.Layer)      )
               __UpperCAmelCase     :			Union[str, Any]  							=      model.get_output_embeddings()
               self.assertTrue(x is None or isinstance(snake_case							,			tf.keras.layers.Layer      )      )

     def 			lowerCamelCase__			(    self					:		List[str]      )						->							int:
          __UpperCAmelCase							,       __UpperCAmelCase     :			Dict  							=      self.model_tester.prepare_config_and_inputs_for_common()

          for model_class in self.all_model_classes:
               __UpperCAmelCase     :			Tuple  							=      model_class(snake_case      )
               __UpperCAmelCase     :			List[str]  							=      inspect.signature(model.call      )
               # signature.parameters is an OrderedDict => so arg_names order is deterministic
               __UpperCAmelCase     :			Tuple  							=      [*signature.parameters.keys()]

               __UpperCAmelCase     :			List[Any]  							=      ['''pixel_values''']
               self.assertListEqual(arg_names[:1]							,			snake_case      )

     def 			lowerCamelCase__			(    self					:		Optional[Any]      )						->							Union[str, Any]:
          __UpperCAmelCase     :			Tuple  							=      self.model_tester.prepare_config_and_inputs()
          self.model_tester.create_and_check_model(*snake_case      )

     def 			lowerCamelCase__			(    self					:		List[Any]      )						->							Tuple:
          __UpperCAmelCase     :			Union[str, Any]  							=      self.model_tester.prepare_config_and_inputs()
          self.model_tester.create_and_check_for_pretraining(*snake_case      )

     def 			lowerCamelCase__			(    self					:		List[Any]      )						->							List[Any]:
          # make the mask reproducible
          np.random.seed(2      )

          __UpperCAmelCase							,       __UpperCAmelCase     :			Union[str, Any]  							=      self.model_tester.prepare_config_and_inputs_for_common()

          __UpperCAmelCase     :			Any  							=      int((config.image_size // config.patch_size) ** 2      )
          __UpperCAmelCase     :			Union[str, Any]  							=      np.random.uniform(size=(self.model_tester.batch_size, num_patches)      )

          for model_class in self.all_model_classes:
               __UpperCAmelCase     :			List[Any]  							=      model_class(snake_case      )
               __UpperCAmelCase     :			Tuple  							=      self._prepare_for_class(snake_case							,			snake_case      )

               __UpperCAmelCase     :			Tuple  							=      model(snake_case							,			noise=snake_case      )

               __UpperCAmelCase     :			List[Any]  							=      copy.deepcopy(self._prepare_for_class(snake_case							,			snake_case      )      )
               __UpperCAmelCase     :			List[Any]  							=      model(**snake_case							,			noise=snake_case      )
               __UpperCAmelCase     :			Optional[int]  							=      outputs_dict[0].numpy()
               __UpperCAmelCase     :			Tuple  							=      outputs_keywords[0].numpy()

               self.assertLess(np.sum(np.abs(output_dict - output_keywords      )      )							,			1E-6      )

     def 			lowerCamelCase__			(    self					:		Dict      )						->							Dict:
          # make the mask reproducible
          np.random.seed(2      )

          __UpperCAmelCase							,       __UpperCAmelCase     :			Any  							=      self.model_tester.prepare_config_and_inputs_for_common()

          __UpperCAmelCase     :			Optional[int]  							=      int((config.image_size // config.patch_size) ** 2      )
          __UpperCAmelCase     :			Tuple  							=      np.random.uniform(size=(self.model_tester.batch_size, num_patches)      )

          def prepare_numpy_arrays(snake_case					:		Optional[int]      ):
               __UpperCAmelCase     :			Any  							=      {}
               for k, v in inputs_dict.items():
                    if tf.is_tensor(snake_case      ):
                         __UpperCAmelCase     :			Optional[Any]  							=      v.numpy()
                    else:
                         __UpperCAmelCase     :			Dict  							=      np.array(snake_case      )

               return inputs_np_dict

          for model_class in self.all_model_classes:
               __UpperCAmelCase     :			List[Any]  							=      model_class(snake_case      )

               __UpperCAmelCase     :			Dict  							=      self._prepare_for_class(snake_case							,			snake_case      )
               __UpperCAmelCase     :			Dict  							=      prepare_numpy_arrays(snake_case      )

               __UpperCAmelCase     :			str  							=      model(snake_case							,			noise=snake_case      )
               __UpperCAmelCase     :			int  							=      model(**snake_case							,			noise=snake_case      )
               self.assert_outputs_same(snake_case							,			snake_case      )

     def 			lowerCamelCase__			(    self					:		List[str]							,			snake_case					:		int							,			snake_case					:		Optional[int]							,			snake_case					:		Tuple      )						->							List[Any]:
          # make masks reproducible
          np.random.seed(2      )

          __UpperCAmelCase     :			Union[str, Any]  							=      int((tf_model.config.image_size // tf_model.config.patch_size) ** 2      )
          __UpperCAmelCase     :			Any  							=      np.random.uniform(size=(self.model_tester.batch_size, num_patches)      )
          __UpperCAmelCase     :			Any  							=      tf.constant(snake_case      )

          # Add `noise` argument.
          # PT inputs will be prepared in `super().check_pt_tf_models()` with this added `noise` argument
          __UpperCAmelCase     :			str  							=      tf_noise

          super().check_pt_tf_models(snake_case							,			snake_case							,			snake_case      )

     def 			lowerCamelCase__			(    self					:		Union[str, Any]      )						->							Dict:
          # make mask reproducible
          np.random.seed(2      )

          __UpperCAmelCase							,       __UpperCAmelCase     :			str  							=      self.model_tester.prepare_config_and_inputs_for_common()

          __UpperCAmelCase     :			Union[str, Any]  							=      {
              module_member
              for model_class in self.all_model_classes
              for module in (import_module(model_class.__module__      ),)
              for module_member_name in dir(snake_case      )
              if module_member_name.endswith('''MainLayer'''      )
              # This condition is required, since `modeling_tf_clip.py` has 3 classes whose names end with `MainLayer`.
              and module_member_name[: -len('''MainLayer'''      )] == model_class.__name__[: -len('''Model'''      )]
              for module_member in (getattr(snake_case							,			snake_case      ),)
              if isinstance(snake_case							,			snake_case      )
              and tf.keras.layers.Layer in module_member.__bases__
              and getattr(snake_case							,			'''_keras_serializable'''							,			snake_case      )
          }

          __UpperCAmelCase     :			List[Any]  							=      int((config.image_size // config.patch_size) ** 2      )
          __UpperCAmelCase     :			Optional[int]  							=      np.random.uniform(size=(self.model_tester.batch_size, num_patches)      )
          __UpperCAmelCase     :			str  							=      tf.convert_to_tensor(snake_case      )
          inputs_dict.update({'''noise''': noise}      )

          for main_layer_class in tf_main_layer_classes:
               __UpperCAmelCase     :			Tuple  							=      main_layer_class(snake_case      )

               __UpperCAmelCase     :			Optional[int]  							=      {
                   name: tf.keras.Input(tensor.shape[1:]							,			dtype=tensor.dtype      ) for name, tensor in inputs_dict.items()
               }

               __UpperCAmelCase     :			Optional[Any]  							=      tf.keras.Model(snake_case							,			outputs=main_layer(snake_case      )      )
               __UpperCAmelCase     :			Optional[Any]  							=      model(snake_case      )

               with tempfile.TemporaryDirectory() as tmpdirname:
                    __UpperCAmelCase     :			str  							=      os.path.join(snake_case							,			'''keras_model.h5'''      )
                    model.save(snake_case      )
                    __UpperCAmelCase     :			List[str]  							=      tf.keras.models.load_model(
                        snake_case							,			custom_objects={main_layer_class.__name__: main_layer_class}      )
                    assert isinstance(snake_case							,			tf.keras.Model      )
                    __UpperCAmelCase     :			Dict  							=      model(snake_case      )
                    self.assert_outputs_same(snake_case							,			snake_case      )

     @slow
     def 			lowerCamelCase__			(    self					:		Optional[int]      )						->							Optional[Any]:
          # make mask reproducible
          np.random.seed(2      )

          __UpperCAmelCase							,       __UpperCAmelCase     :			Optional[Any]  							=      self.model_tester.prepare_config_and_inputs_for_common()

          __UpperCAmelCase     :			Optional[int]  							=      int((config.image_size // config.patch_size) ** 2      )
          __UpperCAmelCase     :			List[str]  							=      np.random.uniform(size=(self.model_tester.batch_size, num_patches)      )

          for model_class in self.all_model_classes:
               __UpperCAmelCase     :			str  							=      model_class(snake_case      )
               __UpperCAmelCase     :			Tuple  							=      self._prepare_for_class(snake_case							,			snake_case      )
               __UpperCAmelCase     :			Union[str, Any]  							=      model(snake_case							,			noise=snake_case      )

               if model_class.__name__ == "TFViTMAEModel":
                    __UpperCAmelCase     :			Tuple  							=      outputs.last_hidden_state.numpy()
                    __UpperCAmelCase     :			List[Any]  							=      0
               else:
                    __UpperCAmelCase     :			Optional[Any]  							=      outputs.logits.numpy()
                    __UpperCAmelCase     :			Tuple  							=      0

               with tempfile.TemporaryDirectory() as tmpdirname:
                    model.save_pretrained(snake_case							,			saved_model=snake_case      )
                    __UpperCAmelCase     :			List[Any]  							=      model_class.from_pretrained(snake_case      )
                    __UpperCAmelCase     :			Optional[int]  							=      model(snake_case							,			noise=snake_case      )

                    if model_class.__name__ == "TFViTMAEModel":
                         __UpperCAmelCase     :			Optional[Any]  							=      after_outputs['''last_hidden_state'''].numpy()
                         __UpperCAmelCase     :			int  							=      0
                    else:
                         __UpperCAmelCase     :			Tuple  							=      after_outputs['''logits'''].numpy()
                         __UpperCAmelCase     :			Optional[Any]  							=      0

                    __UpperCAmelCase     :			List[str]  							=      np.amax(np.abs(out_a - out_a      )      )
                    self.assertLessEqual(snake_case							,			1E-5      )

     def 			lowerCamelCase__			(    self					:		Any      )						->							Tuple:
          # make mask reproducible
          np.random.seed(2      )

          __UpperCAmelCase							,       __UpperCAmelCase     :			str  							=      self.model_tester.prepare_config_and_inputs_for_common()

          __UpperCAmelCase     :			int  							=      int((config.image_size // config.patch_size) ** 2      )
          __UpperCAmelCase     :			int  							=      np.random.uniform(size=(self.model_tester.batch_size, num_patches)      )

          for model_class in self.all_model_classes:
               __UpperCAmelCase     :			Optional[Any]  							=      model_class(snake_case      )
               __UpperCAmelCase     :			List[str]  							=      self._prepare_for_class(snake_case							,			snake_case      )

               __UpperCAmelCase     :			int  							=      model(snake_case							,			noise=snake_case      )
               __UpperCAmelCase     :			Optional[int]  							=      model.get_config()
               # make sure that returned config is jsonifiable, which is required by keras
               json.dumps(snake_case      )
               __UpperCAmelCase     :			str  							=      model_class.from_config(model.get_config()      )
               # make sure it also accepts a normal config
               __UpperCAmelCase     :			str  							=      model_class.from_config(model.config      )
               __UpperCAmelCase     :			List[Any]  							=      new_model(snake_case      )  # Build model
               new_model.set_weights(model.get_weights()      )
               __UpperCAmelCase     :			List[Any]  							=      new_model(snake_case							,			noise=snake_case      )

               self.assert_outputs_same(snake_case							,			snake_case      )

     @unittest.skip(
         reason='''ViTMAE returns a random mask + ids_restore in each forward pass. See test_save_load
    to get deterministic results.'''      )
     def 			lowerCamelCase__			(    self					:		int      )						->							Optional[Any]:
          pass

     @unittest.skip(reason='''ViTMAE returns a random mask + ids_restore in each forward pass. See test_save_load'''      )
     def 			lowerCamelCase__			(    self					:		List[str]      )						->							Optional[int]:
          pass






     @slow
     def 			lowerCamelCase__			(    self					:		List[Any]      )						->							List[str]:
          __UpperCAmelCase     :			List[str]  							=      TFViTMAEModel.from_pretrained('''google/vit-base-patch16-224'''      )
          self.assertIsNotNone(snake_case      )




def      _a     (						):





     '''simple docstring'''






     __UpperCAmelCase     :			Optional[Any]  							=      Image.open('''./tests/fixtures/tests_samples/COCO/000000039769.png'''  )
     return image



@require_tf
@require_vision
class      a    (		unittest.TestCase	):


     """simple docstring"""






     @cached_property
     def 			lowerCamelCase__			(    self					:		List[Any]      )						->							Any:
          return ViTImageProcessor.from_pretrained('''facebook/vit-mae-base'''      ) if is_vision_available() else None






     @slow
     def 			lowerCamelCase__			(    self					:		Tuple      )						->							List[str]:
          # make random mask reproducible across the PT and TF model
          np.random.seed(2      )

          __UpperCAmelCase     :			Optional[int]  							=      TFViTMAEForPreTraining.from_pretrained('''facebook/vit-mae-base'''      )

          __UpperCAmelCase     :			str  							=      self.default_image_processor
          __UpperCAmelCase     :			List[Any]  							=      prepare_img()
          __UpperCAmelCase     :			Optional[Any]  							=      image_processor(images=snake_case							,			return_tensors='''tf'''      )

          # prepare a noise vector that will be also used for testing the TF model
          # (this way we can ensure that the PT and TF models operate on the same inputs)
          __UpperCAmelCase     :			Union[str, Any]  							=      ViTMAEConfig()
          __UpperCAmelCase     :			Union[str, Any]  							=      int((vit_mae_config.image_size // vit_mae_config.patch_size) ** 2      )
          __UpperCAmelCase     :			List[Any]  							=      np.random.uniform(size=(1, num_patches)      )

          # forward pass
          __UpperCAmelCase     :			Any  							=      model(**snake_case							,			noise=snake_case      )

          # verify the logits
          __UpperCAmelCase     :			Union[str, Any]  							=      tf.convert_to_tensor([1, 196, 768]      )
          self.assertEqual(outputs.logits.shape							,			snake_case      )

          __UpperCAmelCase     :			Any  							=      tf.convert_to_tensor(
              [[-0.0_548, -1.7_023, -0.9_325], [0.3_721, -0.5_670, -0.2_233], [0.8_235, -1.3_878, -0.3_524]]      )

          tf.debugging.assert_near(outputs.logits[0, :3, :3]							,			snake_case							,			atol=1E-4      )



'''simple docstring'''



import os
import sys
import unittest


__UpperCAmelCase      :Optional[int]			    =       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
__UpperCAmelCase      :Dict			    =       os.path.join(git_repo_path, "src", "diffusers")



class      a    (		unittest.TestCase	):


     """simple docstring"""






     def 			lowerCamelCase__			(    self					:		Any      )						->							int:
          __UpperCAmelCase     :			Optional[Any]  							=      find_backend('''    if not is_torch_available():'''      )
          self.assertEqual(snake_case							,			'''torch'''      )

          # backend_with_underscore = find_backend("    if not is_tensorflow_text_available():")
          # self.assertEqual(backend_with_underscore, "tensorflow_text")

          __UpperCAmelCase     :			Union[str, Any]  							=      find_backend('''    if not (is_torch_available() and is_transformers_available()):'''      )
          self.assertEqual(snake_case							,			'''torch_and_transformers'''      )

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

          __UpperCAmelCase     :			List[str]  							=      find_backend(
              '''    if not (is_torch_available() and is_transformers_available() and is_onnx_available()):'''      )
          self.assertEqual(snake_case							,			'''torch_and_transformers_and_onnx'''      )

     def 			lowerCamelCase__			(    self					:		Optional[int]      )						->							int:
          __UpperCAmelCase     :			Tuple  							=      read_init()
          # We don't assert on the exact list of keys to allow for smooth grow of backend-specific objects
          self.assertIn('''torch'''							,			snake_case      )
          self.assertIn('''torch_and_transformers'''							,			snake_case      )
          self.assertIn('''flax_and_transformers'''							,			snake_case      )
          self.assertIn('''torch_and_transformers_and_onnx'''							,			snake_case      )

          # Likewise, we can't assert on the exact content of a key
          self.assertIn('''UNet2DModel'''							,			objects['''torch''']      )
          self.assertIn('''FlaxUNet2DConditionModel'''							,			objects['''flax''']      )
          self.assertIn('''StableDiffusionPipeline'''							,			objects['''torch_and_transformers''']      )
          self.assertIn('''FlaxStableDiffusionPipeline'''							,			objects['''flax_and_transformers''']      )
          self.assertIn('''LMSDiscreteScheduler'''							,			objects['''torch_and_scipy''']      )
          self.assertIn('''OnnxStableDiffusionPipeline'''							,			objects['''torch_and_transformers_and_onnx''']      )

     def 			lowerCamelCase__			(    self					:		Optional[int]      )						->							List[Any]:
          __UpperCAmelCase     :			str  							=      create_dummy_object('''CONSTANT'''							,			'''\'torch\''''      )
          self.assertEqual(snake_case							,			'''\nCONSTANT = None\n'''      )

          __UpperCAmelCase     :			Union[str, Any]  							=      create_dummy_object('''function'''							,			'''\'torch\''''      )
          self.assertEqual(
              snake_case							,			'''\ndef function(*args, **kwargs):\n    requires_backends(function, \'torch\')\n'''      )

          __UpperCAmelCase     :			Optional[int]  							=      '''
class FakeClass(metaclass=DummyObject):
    _backends = \'torch\'

    def __init__(self, *args, **kwargs):
        requires_backends(self, \'torch\')

    @classmethod
    def from_config(cls, *args, **kwargs):
        requires_backends(cls, \'torch\')

    @classmethod
    def from_pretrained(cls, *args, **kwargs):
        requires_backends(cls, \'torch\')
'''
          __UpperCAmelCase     :			Optional[Any]  							=      create_dummy_object('''FakeClass'''							,			'''\'torch\''''      )
          self.assertEqual(snake_case							,			snake_case      )






     def 			lowerCamelCase__			(    self					:		int      )						->							List[Any]:
          __UpperCAmelCase     :			List[str]  							=      '''# 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"])

    @classmethod
    def from_config(cls, *args, **kwargs):
        requires_backends(cls, ["torch"])

    @classmethod
    def from_pretrained(cls, *args, **kwargs):
        requires_backends(cls, ["torch"])
'''
          __UpperCAmelCase     :			Optional[int]  							=      create_dummy_files({'''torch''': ['''CONSTANT''', '''function''', '''FakeClass''']}      )
          self.assertEqual(dummy_files['''torch''']							,			snake_case      )