




import unittest

import numpy as np
import torch

from diffusers import DDIMPipeline, DDIMScheduler, UNetaDModel
from diffusers.utils.testing_utils import enable_full_determinism, require_torch_gpu, slow, torch_device

from ..pipeline_params import UNCONDITIONAL_IMAGE_GENERATION_BATCH_PARAMS, UNCONDITIONAL_IMAGE_GENERATION_PARAMS
from ..test_pipelines_common import PipelineTesterMixin


enable_full_determinism()





class 	lowerCamelCase_							(				_SCREAMING_SNAKE_CASE	,       unittest.TestCase ):


 '''simple docstring'''







 lowercase_       =   DDIMPipeline
 lowercase_       =   UNCONDITIONAL_IMAGE_GENERATION_PARAMS
 lowercase_       =   PipelineTesterMixin.required_optional_params - {
     "num_images_per_prompt",
     "latents",
     "callback",
     "callback_steps",
 }
 lowercase_       =   UNCONDITIONAL_IMAGE_GENERATION_BATCH_PARAMS
 lowercase_       =   False



 def 				lowerCAmelCase_  (							self  :		Union[str, Any]						):
       torch.manual_seed(0						)
       SCREAMING_SNAKE_CASE_     						=      UNetaDModel(
           block_out_channels=(32, 64)    ,    layers_per_block=2    ,    sample_size=32    ,    in_channels=3    ,    out_channels=3    ,    down_block_types=('DownBlock2D', 'AttnDownBlock2D')    ,    up_block_types=('AttnUpBlock2D', 'UpBlock2D')    ,    )
       SCREAMING_SNAKE_CASE_     						=      DDIMScheduler()
       SCREAMING_SNAKE_CASE_     						=      {'unet': unet, 'scheduler': scheduler}
       return components



 def 				lowerCAmelCase_  (							self  :		Tuple    ,    _lowerCAmelCase  :		int    ,    _lowerCAmelCase  :		int=0						):
       if str(_lowerCAmelCase						).startswith('mps'						):
             SCREAMING_SNAKE_CASE_     						=      torch.manual_seed(_lowerCAmelCase						)
       else:
             SCREAMING_SNAKE_CASE_     						=      torch.Generator(device=_lowerCAmelCase						).manual_seed(_lowerCAmelCase						)
       SCREAMING_SNAKE_CASE_     						=      {
           'batch_size': 1,
           'generator': generator,
           'num_inference_steps': 2,
           'output_type': 'numpy',
       }
       return inputs



 def 				lowerCAmelCase_  (							self  :		Union[str, Any]						):
       SCREAMING_SNAKE_CASE_     						=      'cpu'

       SCREAMING_SNAKE_CASE_     						=      self.get_dummy_components()
       SCREAMING_SNAKE_CASE_     						=      self.pipeline_class(**_lowerCAmelCase						)
       pipe.to(_lowerCAmelCase						)
       pipe.set_progress_bar_config(disable=_lowerCAmelCase						)

       SCREAMING_SNAKE_CASE_     						=      self.get_dummy_inputs(_lowerCAmelCase						)
       SCREAMING_SNAKE_CASE_     						=      pipe(**_lowerCAmelCase						).images
       SCREAMING_SNAKE_CASE_     						=      image[0, -3:, -3:, -1]

       self.assertEqual(image.shape    ,    (1, 32, 32, 3)						)
       SCREAMING_SNAKE_CASE_     						=      np.array(
           [1.000E00, 5.717E-01, 4.717E-01, 1.000E00, 0.000E00, 1.000E00, 3.000E-04, 0.000E00, 9.000E-04]						)
       SCREAMING_SNAKE_CASE_     						=      np.abs(image_slice.flatten() - expected_slice						).max()
       self.assertLessEqual(_lowerCAmelCase    ,    1E-3						)



 def 				lowerCAmelCase_  (							self  :		Optional[Any]						):
       super().test_dict_tuple_outputs_equivalent(expected_max_difference=3E-3						)



 def 				lowerCAmelCase_  (							self  :		Optional[Any]						):
       super().test_save_load_local(expected_max_difference=3E-3						)



 def 				lowerCAmelCase_  (							self  :		Optional[Any]						):
       super().test_save_load_optional_components(expected_max_difference=3E-3						)




 def 				lowerCAmelCase_  (							self  :		str						):
       super().test_inference_batch_single_identical(expected_max_diff=3E-3						)





@slow
@require_torch_gpu
class 	lowerCamelCase_							(				unittest.TestCase ):


 '''simple docstring'''







 def 				lowerCAmelCase_  (							self  :		Any						):
       SCREAMING_SNAKE_CASE_     						=      'google/ddpm-cifar10-32'

       SCREAMING_SNAKE_CASE_     						=      UNetaDModel.from_pretrained(_lowerCAmelCase						)
       SCREAMING_SNAKE_CASE_     						=      DDIMScheduler()

       SCREAMING_SNAKE_CASE_     						=      DDIMPipeline(unet=_lowerCAmelCase    ,    scheduler=_lowerCAmelCase						)
       ddim.to(_lowerCAmelCase						)
       ddim.set_progress_bar_config(disable=_lowerCAmelCase						)

       SCREAMING_SNAKE_CASE_     						=      torch.manual_seed(0						)
       SCREAMING_SNAKE_CASE_     						=      ddim(generator=_lowerCAmelCase    ,    eta=0.0    ,    output_type='numpy'						).images

       SCREAMING_SNAKE_CASE_     						=      image[0, -3:, -3:, -1]

       assert image.shape == (1, 32, 32, 3)
       SCREAMING_SNAKE_CASE_     						=      np.array([0.1723, 0.1617, 0.1600, 0.1626, 0.1497, 0.1513, 0.1505, 0.1442, 0.1453]						)

       assert np.abs(image_slice.flatten() - expected_slice						).max() < 1E-2




 def 				lowerCAmelCase_  (							self  :		List[str]						):
       SCREAMING_SNAKE_CASE_     						=      'google/ddpm-ema-bedroom-256'

       SCREAMING_SNAKE_CASE_     						=      UNetaDModel.from_pretrained(_lowerCAmelCase						)
       SCREAMING_SNAKE_CASE_     						=      DDIMScheduler.from_pretrained(_lowerCAmelCase						)

       SCREAMING_SNAKE_CASE_     						=      DDIMPipeline(unet=_lowerCAmelCase    ,    scheduler=_lowerCAmelCase						)
       ddpm.to(_lowerCAmelCase						)
       ddpm.set_progress_bar_config(disable=_lowerCAmelCase						)

       SCREAMING_SNAKE_CASE_     						=      torch.manual_seed(0						)
       SCREAMING_SNAKE_CASE_     						=      ddpm(generator=_lowerCAmelCase    ,    output_type='numpy'						).images

       SCREAMING_SNAKE_CASE_     						=      image[0, -3:, -3:, -1]

       assert image.shape == (1, 256, 256, 3)
       SCREAMING_SNAKE_CASE_     						=      np.array([0.0060, 0.0201, 0.0344, 0.0024, 0.0018, 0.0002, 0.0022, 0.0000, 0.0069]						)

       assert np.abs(image_slice.flatten() - expected_slice						).max() < 1E-2





import importlib
import json
import os
import sys
import tempfile
import unittest
from pathlib import Path

import transformers
import transformers.models.auto
from transformers.models.auto.configuration_auto import CONFIG_MAPPING, AutoConfig
from transformers.models.bert.configuration_bert import BertConfig
from transformers.models.roberta.configuration_roberta import RobertaConfig
from transformers.testing_utils import DUMMY_UNKNOWN_IDENTIFIER, get_tests_dir


sys.path.append(str(Path(__file__).parent.parent.parent.parent / 'utils'))

from test_module.custom_configuration import CustomConfig  # noqa E402


lowerCamelCase__			:       str         =							get_tests_dir('fixtures/dummy-config.json')





class 	lowerCamelCase_							(				unittest.TestCase ):


 '''simple docstring'''







 def 				lowerCAmelCase_  (							self  :		Dict						):
       SCREAMING_SNAKE_CASE_     						=      0



 def 				lowerCAmelCase_  (							self  :		Optional[int]						):
       self.assertIsNotNone(transformers.models.auto.__spec__						)
       self.assertIsNotNone(importlib.util.find_spec('transformers.models.auto'						)						)



 def 				lowerCAmelCase_  (							self  :		Any						):
       SCREAMING_SNAKE_CASE_     						=      AutoConfig.from_pretrained('bert-base-uncased'						)
       self.assertIsInstance(_lowerCAmelCase    ,    _lowerCAmelCase						)



 def 				lowerCAmelCase_  (							self  :		Union[str, Any]						):
       SCREAMING_SNAKE_CASE_     						=      AutoConfig.from_pretrained(_lowerCAmelCase						)
       self.assertIsInstance(_lowerCAmelCase    ,    _lowerCAmelCase						)



 def 				lowerCAmelCase_  (							self  :		Optional[Any]						):
       SCREAMING_SNAKE_CASE_     						=      AutoConfig.from_pretrained(_lowerCAmelCase						)
       self.assertIsInstance(_lowerCAmelCase    ,    _lowerCAmelCase						)



 def 				lowerCAmelCase_  (							self  :		Dict						):
       SCREAMING_SNAKE_CASE_     						=      AutoConfig.for_model('roberta'						)
       self.assertIsInstance(_lowerCAmelCase    ,    _lowerCAmelCase						)



 def 				lowerCAmelCase_  (							self  :		Dict						):
       with tempfile.TemporaryDirectory() as tmp_dir:
             # This model name contains bert and roberta, but roberta ends up being picked.
             SCREAMING_SNAKE_CASE_     						=      os.path.join(_lowerCAmelCase    ,    'fake-roberta'						)
             os.makedirs(_lowerCAmelCase    ,    exist_ok=_lowerCAmelCase						)
             with open(os.path.join(_lowerCAmelCase    ,    'config.json'						)    ,    'w'						) as f:
                   f.write(json.dumps({}						)						)
             SCREAMING_SNAKE_CASE_     						=      AutoConfig.from_pretrained(_lowerCAmelCase						)
             self.assertEqual(type(_lowerCAmelCase						)    ,    _lowerCAmelCase						)



 def 				lowerCAmelCase_  (							self  :		Optional[Any]						):
       try:
             AutoConfig.register('custom'    ,    _lowerCAmelCase						)
             # Wrong model type will raise an error
             with self.assertRaises(_lowerCAmelCase						):
                   AutoConfig.register('model'    ,    _lowerCAmelCase						)
             # Trying to register something existing in the Transformers library will raise an error
             with self.assertRaises(_lowerCAmelCase						):
                   AutoConfig.register('bert'    ,    _lowerCAmelCase						)

             # Now that the config is registered, it can be used as any other config with the auto-API
             SCREAMING_SNAKE_CASE_     						=      CustomConfig()
             with tempfile.TemporaryDirectory() as tmp_dir:
                   config.save_pretrained(_lowerCAmelCase						)
                   SCREAMING_SNAKE_CASE_     						=      AutoConfig.from_pretrained(_lowerCAmelCase						)
                   self.assertIsInstance(_lowerCAmelCase    ,    _lowerCAmelCase						)

       finally:
             if "custom" in CONFIG_MAPPING._extra_content:
                   del CONFIG_MAPPING._extra_content["custom"]



 def 				lowerCAmelCase_  (							self  :		Optional[int]						):
       with self.assertRaisesRegex(
           _lowerCAmelCase    ,    'bert-base is not a local folder and is not a valid model identifier'						):
             SCREAMING_SNAKE_CASE_     						=      AutoConfig.from_pretrained('bert-base'						)



 def 				lowerCAmelCase_  (							self  :		int						):
       with self.assertRaisesRegex(
           _lowerCAmelCase    ,    R'aaaaaa is not a valid git identifier \(branch name, tag name or commit id\)'						):
             SCREAMING_SNAKE_CASE_     						=      AutoConfig.from_pretrained(_lowerCAmelCase    ,    revision='aaaaaa'						)



 def 				lowerCAmelCase_  (							self  :		Tuple						):
       with self.assertRaisesRegex(
           _lowerCAmelCase    ,    'hf-internal-testing/no-config-test-repo does not appear to have a file named config.json.'    ,    ):
             SCREAMING_SNAKE_CASE_     						=      AutoConfig.from_pretrained('hf-internal-testing/no-config-test-repo'						)



 def 				lowerCAmelCase_  (							self  :		Union[str, Any]						):
       # If remote code is not set, we will time out when asking whether to load the model.
       with self.assertRaises(_lowerCAmelCase						):
             SCREAMING_SNAKE_CASE_     						=      AutoConfig.from_pretrained('hf-internal-testing/test_dynamic_model'						)
       # If remote code is disabled, we can't load this config.
       with self.assertRaises(_lowerCAmelCase						):
             SCREAMING_SNAKE_CASE_     						=      AutoConfig.from_pretrained('hf-internal-testing/test_dynamic_model'    ,    trust_remote_code=_lowerCAmelCase						)

       SCREAMING_SNAKE_CASE_     						=      AutoConfig.from_pretrained('hf-internal-testing/test_dynamic_model'    ,    trust_remote_code=_lowerCAmelCase						)
       self.assertEqual(config.__class__.__name__    ,    'NewModelConfig'						)

       # Test config can be reloaded.
       with tempfile.TemporaryDirectory() as tmp_dir:
             config.save_pretrained(_lowerCAmelCase						)
             SCREAMING_SNAKE_CASE_     						=      AutoConfig.from_pretrained(_lowerCAmelCase    ,    trust_remote_code=_lowerCAmelCase						)
       self.assertEqual(reloaded_config.__class__.__name__    ,    'NewModelConfig'						)




 def 				lowerCAmelCase_  (							self  :		Any						):





       class 	lowerCamelCase_							(				_SCREAMING_SNAKE_CASE ):


        '''simple docstring'''







        lowercase_       =   "new-model"

       try:
             AutoConfig.register('new-model'    ,    _lowerCAmelCase						)
             # If remote code is not set, the default is to use local
             SCREAMING_SNAKE_CASE_     						=      AutoConfig.from_pretrained('hf-internal-testing/test_dynamic_model'						)
             self.assertEqual(config.__class__.__name__    ,    'NewModelConfigLocal'						)

             # If remote code is disabled, we load the local one.
             SCREAMING_SNAKE_CASE_     						=      AutoConfig.from_pretrained('hf-internal-testing/test_dynamic_model'    ,    trust_remote_code=_lowerCAmelCase						)
             self.assertEqual(config.__class__.__name__    ,    'NewModelConfigLocal'						)

             # If remote is enabled, we load from the Hub
             SCREAMING_SNAKE_CASE_     						=      AutoConfig.from_pretrained('hf-internal-testing/test_dynamic_model'    ,    trust_remote_code=_lowerCAmelCase						)
             self.assertEqual(config.__class__.__name__    ,    'NewModelConfig'						)

       finally:
             if "new-model" in CONFIG_MAPPING._extra_content:
                   del CONFIG_MAPPING._extra_content["new-model"]