

import os
import sys
import unittest


lowerCAmelCase   :      List[Any]     =     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
lowerCAmelCase   :      str     =     os.path.join(git_repo_path, 'src', 'diffusers')
class        _A						(     unittest.TestCase):

  def        UpperCAmelCase			( self    ):





        """simple docstring"""







        SCREAMING_SNAKE_CASE_ :     Union[str, 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")

        SCREAMING_SNAKE_CASE_ :     Optional[int]							=   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")

        SCREAMING_SNAKE_CASE_ :     Tuple							=   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        UpperCAmelCase			( self    ):





        """simple docstring"""







        SCREAMING_SNAKE_CASE_ :     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        UpperCAmelCase			( self    ):





        """simple docstring"""







        SCREAMING_SNAKE_CASE_ :     List[str]							=   create_dummy_object('CONSTANT'       ,    '\'torch\''    )
        self.assertEqual(__snake_case       ,    '\nCONSTANT = None\n'    )

        SCREAMING_SNAKE_CASE_ :     List[Any]							=   create_dummy_object('function'       ,    '\'torch\''    )
        self.assertEqual(
            __snake_case       ,    '\ndef function(*args, **kwargs):\n    requires_backends(function, \'torch\')\n'    )

        SCREAMING_SNAKE_CASE_ :     Optional[Any]							=   '\nclass FakeClass(metaclass=DummyObject):\n    _backends = \'torch\'\n\n    def __init__(self, *args, **kwargs):\n        requires_backends(self, \'torch\')\n\n    @classmethod\n    def from_config(cls, *args, **kwargs):\n        requires_backends(cls, \'torch\')\n\n    @classmethod\n    def from_pretrained(cls, *args, **kwargs):\n        requires_backends(cls, \'torch\')\n'
        SCREAMING_SNAKE_CASE_ :     Optional[int]							=   create_dummy_object('FakeClass'       ,    '\'torch\''    )
        self.assertEqual(__snake_case       ,    __snake_case    )



  def        UpperCAmelCase			( self    ):





        """simple docstring"""







        SCREAMING_SNAKE_CASE_ :     int							=   '# This file is autogenerated by the command `make fix-copies`, do not edit.\nfrom ..utils import DummyObject, requires_backends\n\n\nCONSTANT = None\n\n\ndef function(*args, **kwargs):\n    requires_backends(function, ["torch"])\n\n\nclass FakeClass(metaclass=DummyObject):\n    _backends = ["torch"]\n\n    def __init__(self, *args, **kwargs):\n        requires_backends(self, ["torch"])\n\n    @classmethod\n    def from_config(cls, *args, **kwargs):\n        requires_backends(cls, ["torch"])\n\n    @classmethod\n    def from_pretrained(cls, *args, **kwargs):\n        requires_backends(cls, ["torch"])\n'
        SCREAMING_SNAKE_CASE_ :     Tuple							=   create_dummy_files({'torch': ['CONSTANT', 'function', 'FakeClass']}    )
        self.assertEqual(dummy_files['torch']       ,    __snake_case    )










import os
import tempfile
import unittest
from pathlib import Path

from transformers import AutoConfig, is_torch_available
from transformers.testing_utils import require_torch, torch_device


if is_torch_available():
						from transformers import PyTorchBenchmark, PyTorchBenchmarkArguments







@require_torch
class        snake_case_   (unittest.TestCase      ):
					def  lowerCamelCase__(      self   :Any			,__snake_case   :List[Any]      )					->    Union[str, Any]:
												for model_result in results.values():
																			for batch_size, sequence_length in zip(model_result['bs']			,model_result['ss']      ):
																										a__             =     model_result['result'][batch_size][sequence_length]
																										self.assertIsNotNone(__snake_case      )
					def  lowerCamelCase__(      self   :List[str]      )					->    Union[str, Any]:
												a__             =     'sshleifer/tiny-gpt2'
												a__             =     PyTorchBenchmarkArguments(
												    models=[MODEL_ID]			,training=__snake_case			,inference=__snake_case			,sequence_lengths=[8]			,batch_sizes=[1]			,multi_process=__snake_case			,)
												a__             =     PyTorchBenchmark(__snake_case      )
												a__             =     benchmark.run()
												self.check_results_dict_not_empty(results.time_inference_result      )
												self.check_results_dict_not_empty(results.memory_inference_result      )
					def  lowerCamelCase__(      self   :List[Any]      )					->    Union[str, Any]:
												a__             =     'sgugger/tiny-distilbert-classification'
												a__             =     PyTorchBenchmarkArguments(
												    models=[MODEL_ID]			,training=__snake_case			,inference=__snake_case			,sequence_lengths=[8]			,batch_sizes=[1]			,multi_process=__snake_case			,only_pretrain_model=__snake_case			,)
												a__             =     PyTorchBenchmark(__snake_case      )
												a__             =     benchmark.run()
												self.check_results_dict_not_empty(results.time_inference_result      )
												self.check_results_dict_not_empty(results.memory_inference_result      )
					def  lowerCamelCase__(      self   :Optional[Any]      )					->    Optional[Any]:
												a__             =     'sshleifer/tiny-gpt2'
												a__             =     PyTorchBenchmarkArguments(
												    models=[MODEL_ID]			,training=__snake_case			,inference=__snake_case			,torchscript=__snake_case			,sequence_lengths=[8]			,batch_sizes=[1]			,multi_process=__snake_case			,)
												a__             =     PyTorchBenchmark(__snake_case      )
												a__             =     benchmark.run()
												self.check_results_dict_not_empty(results.time_inference_result      )
												self.check_results_dict_not_empty(results.memory_inference_result      )
					@unittest.skipIf(torch_device == 'cpu'			,'Cant do half precision'      )
					def  lowerCamelCase__(      self   :int      )					->    str:
												a__             =     'sshleifer/tiny-gpt2'
												a__             =     PyTorchBenchmarkArguments(
												    models=[MODEL_ID]			,training=__snake_case			,inference=__snake_case			,fpaa=__snake_case			,sequence_lengths=[8]			,batch_sizes=[1]			,multi_process=__snake_case			,)
												a__             =     PyTorchBenchmark(__snake_case      )
												a__             =     benchmark.run()
												self.check_results_dict_not_empty(results.time_inference_result      )
												self.check_results_dict_not_empty(results.memory_inference_result      )
					def  lowerCamelCase__(      self   :Optional[int]      )					->    Union[str, Any]:
												a__             =     'sshleifer/tiny-gpt2'
												a__             =     AutoConfig.from_pretrained(__snake_case      )
												# set architectures equal to `None`
												a__             =     None
												a__             =     PyTorchBenchmarkArguments(
												    models=[MODEL_ID]			,training=__snake_case			,inference=__snake_case			,sequence_lengths=[8]			,batch_sizes=[1]			,multi_process=__snake_case			,)
												a__             =     PyTorchBenchmark(__snake_case			,configs=[config]      )
												a__             =     benchmark.run()
												self.check_results_dict_not_empty(results.time_inference_result      )
												self.check_results_dict_not_empty(results.memory_inference_result      )
					def  lowerCamelCase__(      self   :Dict      )					->    int:
												a__             =     'sshleifer/tiny-gpt2'
												a__             =     PyTorchBenchmarkArguments(
												    models=[MODEL_ID]			,training=__snake_case			,inference=__snake_case			,sequence_lengths=[8]			,batch_sizes=[1]			,multi_process=__snake_case			,)
												a__             =     PyTorchBenchmark(__snake_case      )
												a__             =     benchmark.run()
												self.check_results_dict_not_empty(results.time_train_result      )
												self.check_results_dict_not_empty(results.memory_train_result      )
					@unittest.skipIf(torch_device == 'cpu'			,'Can\'t do half precision'      )
					def  lowerCamelCase__(      self   :int      )					->    List[str]:
												a__             =     'sshleifer/tiny-gpt2'
												a__             =     PyTorchBenchmarkArguments(
												    models=[MODEL_ID]			,training=__snake_case			,inference=__snake_case			,sequence_lengths=[8]			,batch_sizes=[1]			,fpaa=__snake_case			,multi_process=__snake_case			,)
												a__             =     PyTorchBenchmark(__snake_case      )
												a__             =     benchmark.run()
												self.check_results_dict_not_empty(results.time_train_result      )
												self.check_results_dict_not_empty(results.memory_train_result      )
					def  lowerCamelCase__(      self   :str      )					->    Union[str, Any]:
												a__             =     'sshleifer/tiny-gpt2'
												a__             =     AutoConfig.from_pretrained(__snake_case      )
												a__             =     PyTorchBenchmarkArguments(
												    models=[MODEL_ID]			,training=__snake_case			,inference=__snake_case			,sequence_lengths=[8]			,batch_sizes=[1]			,multi_process=__snake_case			,)
												a__             =     PyTorchBenchmark(__snake_case			,configs=[config]      )
												a__             =     benchmark.run()
												self.check_results_dict_not_empty(results.time_inference_result      )
												self.check_results_dict_not_empty(results.memory_inference_result      )
					def  lowerCamelCase__(      self   :List[Any]      )					->    Any:
												a__             =     'sshleifer/tinier_bart'
												a__             =     AutoConfig.from_pretrained(__snake_case      )
												a__             =     PyTorchBenchmarkArguments(
												    models=[MODEL_ID]			,training=__snake_case			,inference=__snake_case			,sequence_lengths=[8]			,batch_sizes=[1]			,multi_process=__snake_case			,)
												a__             =     PyTorchBenchmark(__snake_case			,configs=[config]      )
												a__             =     benchmark.run()
												self.check_results_dict_not_empty(results.time_inference_result      )
												self.check_results_dict_not_empty(results.memory_inference_result      )
					def  lowerCamelCase__(      self   :Tuple      )					->    Dict:
												a__             =     'sshleifer/tiny-gpt2'
												a__             =     AutoConfig.from_pretrained(__snake_case      )
												a__             =     PyTorchBenchmarkArguments(
												    models=[MODEL_ID]			,training=__snake_case			,inference=__snake_case			,sequence_lengths=[8]			,batch_sizes=[1]			,multi_process=__snake_case			,)
												a__             =     PyTorchBenchmark(__snake_case			,configs=[config]      )
												a__             =     benchmark.run()
												self.check_results_dict_not_empty(results.time_train_result      )
												self.check_results_dict_not_empty(results.memory_train_result      )
					def  lowerCamelCase__(      self   :Union[str, Any]      )					->    Optional[int]:
												a__             =     'sshleifer/tinier_bart'
												a__             =     AutoConfig.from_pretrained(__snake_case      )
												a__             =     PyTorchBenchmarkArguments(
												    models=[MODEL_ID]			,training=__snake_case			,inference=__snake_case			,sequence_lengths=[8]			,batch_sizes=[1]			,multi_process=__snake_case			,)
												a__             =     PyTorchBenchmark(__snake_case			,configs=[config]      )
												a__             =     benchmark.run()
												self.check_results_dict_not_empty(results.time_train_result      )
												self.check_results_dict_not_empty(results.memory_train_result      )
					def  lowerCamelCase__(      self   :Optional[int]      )					->    List[Any]:
												a__             =     'sshleifer/tiny-gpt2'
												with tempfile.TemporaryDirectory() as tmp_dir:
																			a__             =     PyTorchBenchmarkArguments(
																			    models=[MODEL_ID]			,training=__snake_case			,inference=__snake_case			,save_to_csv=__snake_case			,sequence_lengths=[8]			,batch_sizes=[1]			,inference_time_csv_file=os.path.join(__snake_case			,'inf_time.csv'      )			,train_memory_csv_file=os.path.join(__snake_case			,'train_mem.csv'      )			,inference_memory_csv_file=os.path.join(__snake_case			,'inf_mem.csv'      )			,train_time_csv_file=os.path.join(__snake_case			,'train_time.csv'      )			,env_info_csv_file=os.path.join(__snake_case			,'env.csv'      )			,multi_process=__snake_case			,)
																			a__             =     PyTorchBenchmark(__snake_case      )
																			benchmark.run()
																			self.assertTrue(Path(os.path.join(__snake_case			,'inf_time.csv'      )      ).exists()      )
																			self.assertTrue(Path(os.path.join(__snake_case			,'train_time.csv'      )      ).exists()      )
																			self.assertTrue(Path(os.path.join(__snake_case			,'inf_mem.csv'      )      ).exists()      )
																			self.assertTrue(Path(os.path.join(__snake_case			,'train_mem.csv'      )      ).exists()      )
																			self.assertTrue(Path(os.path.join(__snake_case			,'env.csv'      )      ).exists()      )



					def  lowerCamelCase__(      self   :Optional[int]      )					->    List[str]:
												a__             =     'sshleifer/tiny-gpt2'

												def _check_summary_is_not_empty(__snake_case   :List[str]      ):
																			self.assertTrue(hasattr(__snake_case			,'sequential'      )      )
																			self.assertTrue(hasattr(__snake_case			,'cumulative'      )      )
																			self.assertTrue(hasattr(__snake_case			,'current'      )      )
																			self.assertTrue(hasattr(__snake_case			,'total'      )      )

												with tempfile.TemporaryDirectory() as tmp_dir:
																			a__             =     PyTorchBenchmarkArguments(
																			    models=[MODEL_ID]			,training=__snake_case			,inference=__snake_case			,sequence_lengths=[8]			,batch_sizes=[1]			,log_filename=os.path.join(__snake_case			,'log.txt'      )			,log_print=__snake_case			,trace_memory_line_by_line=__snake_case			,multi_process=__snake_case			,)
																			a__             =     PyTorchBenchmark(__snake_case      )
																			a__             =     benchmark.run()
																			_check_summary_is_not_empty(result.inference_summary      )
																			_check_summary_is_not_empty(result.train_summary      )
																			self.assertTrue(Path(os.path.join(__snake_case			,'log.txt'      )      ).exists()      )




