'''simple docstring'''
import unittest

from transformers import ErnieMConfig, is_torch_available
from transformers.testing_utils import require_torch, slow, torch_device

from ...test_configuration_common import ConfigTester
from ...test_modeling_common import ModelTesterMixin, ids_tensor, random_attention_mask
from ...test_pipeline_mixin import PipelineTesterMixin


if is_torch_available():
 import torch

 from transformers import (
     ErnieMForInformationExtraction,
     ErnieMForMultipleChoice,
     ErnieMForQuestionAnswering,
     ErnieMForSequenceClassification,
     ErnieMForTokenClassification,
     ErnieMModel,
 )
 from transformers.models.ernie_m.modeling_ernie_m import ERNIE_M_PRETRAINED_MODEL_ARCHIVE_LIST




class _lowerCAmelCase			:







      def __init__(  self  ,    lowercase  ,    lowercase=13  ,    lowercase=7  ,    lowercase=True  ,    lowercase=True  ,    lowercase=True  ,    lowercase=99  ,    lowercase=32  ,    lowercase=5  ,    lowercase=4  ,    lowercase=37  ,    lowercase="gelu"  ,    lowercase=0.1  ,    lowercase=0.1  ,    lowercase=512  ,    lowercase=16  ,    lowercase=2  ,    lowercase=0.02  ,    lowercase=3  ,    lowercase=4  ,    lowercase=None  ,    ):
        lowercase				:							List[Any]									=   parent
        lowercase				:							Any									=   batch_size
        lowercase				:							str									=   seq_length
        lowercase				:							Tuple									=   is_training
        lowercase				:							List[str]									=   use_input_mask
        lowercase				:							Tuple									=   use_labels
        lowercase				:							List[Any]									=   vocab_size
        lowercase				:							int									=   hidden_size
        lowercase				:							List[Any]									=   num_hidden_layers
        lowercase				:							Optional[Any]									=   num_attention_heads
        lowercase				:							Tuple									=   intermediate_size
        lowercase				:							Optional[int]									=   hidden_act
        lowercase				:							List[str]									=   hidden_dropout_prob
        lowercase				:							Union[str, Any]									=   attention_probs_dropout_prob
        lowercase				:							str									=   max_position_embeddings
        lowercase				:							Optional[int]									=   type_vocab_size
        lowercase				:							str									=   type_sequence_label_size
        lowercase				:							List[Any]									=   initializer_range
        lowercase				:							Optional[Any]									=   num_labels
        lowercase				:							Dict									=   num_choices
        lowercase				:							List[Any]									=   scope







      def      lowerCamelCase__      (  self     ):
        lowercase				:							Optional[int]									=   ids_tensor([self.batch_size, self.seq_length]  ,    self.vocab_size     )

        lowercase				:							Dict									=   None
        if self.use_input_mask:
          lowercase				:							List[Any]									=   random_attention_mask([self.batch_size, self.seq_length]     )

        lowercase				:							str									=   None
        lowercase				:							int									=   None
        lowercase				:							str									=   None
        if self.use_labels:
          lowercase				:							Optional[int]									=   ids_tensor([self.batch_size]  ,    self.type_sequence_label_size     )
          lowercase				:							Any									=   ids_tensor([self.batch_size, self.seq_length]  ,    self.num_labels     )
          lowercase				:							str									=   ids_tensor([self.batch_size]  ,    self.num_choices     )

        lowercase				:							Tuple									=   self.get_config()

        return config, input_ids, input_mask, sequence_labels, token_labels, choice_labels







      def      lowerCamelCase__      (  self     ):
        lowercase				:							Dict									=   ids_tensor([self.batch_size, self.seq_length]  ,    self.vocab_size     )

        lowercase				:							Any									=   None
        if self.use_input_mask:
          lowercase				:							Union[str, Any]									=   random_attention_mask([self.batch_size, self.seq_length]     )
        lowercase				:							int									=   self.get_config()

        return config, input_ids, input_mask







      def      lowerCamelCase__      (  self     ):
        return ErnieMConfig(
            vocab_size=self.vocab_size  ,    hidden_size=self.hidden_size  ,    num_hidden_layers=self.num_hidden_layers  ,    num_attention_heads=self.num_attention_heads  ,    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  ,    max_position_embeddings=self.max_position_embeddings  ,    type_vocab_size=self.type_vocab_size  ,    initializer_range=self.initializer_range  ,    )







      def      lowerCamelCase__      (  self  ,    lowercase  ,    lowercase  ,    lowercase  ,    lowercase  ,    lowercase  ,    lowercase     ):
        lowercase				:							Any									=   ErnieMModel(config=__lowercase     )
        model.to(__lowercase     )
        model.eval()
        lowercase				:							str									=   model(__lowercase  ,    return_dict=__lowercase     )
        self.parent.assertEqual(result.last_hidden_state.shape  ,    (self.batch_size, self.seq_length, self.hidden_size)     )







      def      lowerCamelCase__      (  self  ,    lowercase  ,    lowercase  ,    lowercase  ,    lowercase  ,    lowercase  ,    lowercase     ):
        lowercase				:							List[Any]									=   ErnieMForQuestionAnswering(config=__lowercase     )
        model.to(__lowercase     )
        model.eval()
        lowercase				:							Tuple									=   model(
            __lowercase  ,    attention_mask=__lowercase  ,    start_positions=__lowercase  ,    end_positions=__lowercase  ,    )
        self.parent.assertEqual(result.start_logits.shape  ,    (self.batch_size, self.seq_length)     )
        self.parent.assertEqual(result.end_logits.shape  ,    (self.batch_size, self.seq_length)     )







      def      lowerCamelCase__      (  self  ,    lowercase  ,    lowercase  ,    lowercase  ,    lowercase  ,    lowercase  ,    lowercase     ):
        lowercase				:							Dict									=   ErnieMForInformationExtraction(config=__lowercase     )
        model.to(__lowercase     )
        model.eval()
        lowercase				:							Optional[int]									=   torch.ones_like(__lowercase  ,    dtype=torch.floataa     )
        lowercase				:							List[str]									=   model(
            __lowercase  ,    attention_mask=__lowercase  ,    start_positions=__lowercase  ,    end_positions=__lowercase  ,    )
        self.parent.assertEqual(result.start_logits.shape  ,    (self.batch_size, self.seq_length)     )
        self.parent.assertEqual(result.end_logits.shape  ,    (self.batch_size, self.seq_length)     )







      def      lowerCamelCase__      (  self  ,    lowercase  ,    lowercase  ,    lowercase  ,    lowercase  ,    lowercase  ,    lowercase     ):
        lowercase				:							Dict									=   self.num_labels
        lowercase				:							str									=   ErnieMForSequenceClassification(__lowercase     )
        model.to(__lowercase     )
        model.eval()
        lowercase				:							Tuple									=   model(__lowercase  ,    attention_mask=__lowercase  ,    labels=__lowercase     )
        self.parent.assertEqual(result.logits.shape  ,    (self.batch_size, self.num_labels)     )







      def      lowerCamelCase__      (  self  ,    lowercase  ,    lowercase  ,    lowercase  ,    lowercase  ,    lowercase  ,    lowercase     ):
        lowercase				:							Tuple									=   self.num_labels
        lowercase				:							List[str]									=   ErnieMForTokenClassification(config=__lowercase     )
        model.to(__lowercase     )
        model.eval()
        input_ids.to(__lowercase     )
        input_mask.to(__lowercase     )
        token_labels.to(__lowercase     )

        lowercase				:							Optional[Any]									=   model(__lowercase  ,    attention_mask=__lowercase  ,    labels=__lowercase     )

        self.parent.assertEqual(result.logits.shape  ,    (self.batch_size, self.seq_length, self.num_labels)     )







      def      lowerCamelCase__      (  self  ,    lowercase  ,    lowercase  ,    lowercase  ,    lowercase  ,    lowercase  ,    lowercase     ):
        lowercase				:							str									=   self.num_choices
        lowercase				:							Union[str, Any]									=   ErnieMForMultipleChoice(config=__lowercase     )
        model.to(__lowercase     )
        model.eval()
        lowercase				:							Optional[int]									=   input_ids.unsqueeze(1     ).expand(-1  ,    self.num_choices  ,    -1     ).contiguous()
        lowercase				:							Optional[Any]									=   input_mask.unsqueeze(1     ).expand(-1  ,    self.num_choices  ,    -1     ).contiguous()
        lowercase				:							Union[str, Any]									=   model(
            __lowercase  ,    attention_mask=__lowercase  ,    labels=__lowercase  ,    )
        self.parent.assertEqual(result.logits.shape  ,    (self.batch_size, self.num_choices)     )







      def      lowerCamelCase__      (  self     ):
        lowercase				:							Tuple									=   self.prepare_config_and_inputs()
        (
            lowercase	
        )				:							List[Any]									=   config_and_inputs
        lowercase				:							Tuple									=   {'''input_ids''': input_ids, '''attention_mask''': input_mask}
        return config, inputs_dict





@require_torch
class _lowerCAmelCase			(	UpperCAmelCase__							,   UpperCAmelCase__							,   unittest.TestCase					):
      UpperCAmelCase_	:						Dict	 =       (
          (
              ErnieMModel,
              ErnieMForMultipleChoice,
              ErnieMForQuestionAnswering,
              ErnieMForSequenceClassification,
              ErnieMForTokenClassification,
          )
          if is_torch_available()
          else ()
      )
      UpperCAmelCase_	:						Union[str, Any]	 =       ()
      UpperCAmelCase_	:						str	 =       (
          {
              """feature-extraction""": ErnieMModel,
              """question-answering""": ErnieMForQuestionAnswering,
              """text-classification""": ErnieMForSequenceClassification,
              """token-classification""": ErnieMForTokenClassification,
              """zero-shot""": ErnieMForSequenceClassification,
          }
          if is_torch_available()
          else {}
      )
      UpperCAmelCase_	:						Tuple	 =       False







      def      lowerCamelCase__      (  self  ,    lowercase  ,    lowercase  ,    lowercase  ,    lowercase  ,    lowercase     ):
        if pipeline_test_casse_name == "QAPipelineTests":
          return True

        return False







      def      lowerCamelCase__      (  self     ):
        lowercase				:							Union[str, Any]									=   ErnieMModelTester(self     )
        lowercase				:							List[Any]									=   ConfigTester(self  ,    config_class=__lowercase  ,    hidden_size=37     )







      def      lowerCamelCase__      (  self     ):
        self.config_tester.run_common_tests()







      def      lowerCamelCase__      (  self     ):
        lowercase				:							int									=   self.model_tester.prepare_config_and_inputs()
        self.model_tester.create_and_check_model(*__lowercase     )







      def      lowerCamelCase__      (  self     ):
        lowercase				:							int									=   self.model_tester.prepare_config_and_inputs()
        for type in ["absolute", "relative_key", "relative_key_query"]:
          lowercase				:							Tuple									=   type
          self.model_tester.create_and_check_model(*__lowercase     )







      def      lowerCamelCase__      (  self     ):
        lowercase				:							Any									=   self.model_tester.prepare_config_and_inputs()
        self.model_tester.create_and_check_for_multiple_choice(*__lowercase     )







      def      lowerCamelCase__      (  self     ):
        lowercase				:							Any									=   self.model_tester.prepare_config_and_inputs()
        self.model_tester.create_and_check_for_question_answering(*__lowercase     )







      def      lowerCamelCase__      (  self     ):
        lowercase				:							Dict									=   self.model_tester.prepare_config_and_inputs()
        self.model_tester.create_and_check_for_sequence_classification(*__lowercase     )







      def      lowerCamelCase__      (  self     ):
        lowercase				:							int									=   self.model_tester.prepare_config_and_inputs()
        self.model_tester.create_and_check_for_information_extraction(*__lowercase     )







      def      lowerCamelCase__      (  self     ):
        lowercase				:							Union[str, Any]									=   self.model_tester.prepare_config_and_inputs()
        self.model_tester.create_and_check_for_token_classification(*__lowercase     )







      @slow
      def      lowerCamelCase__      (  self     ):
        for model_name in ERNIE_M_PRETRAINED_MODEL_ARCHIVE_LIST[:1]:
          lowercase				:							int									=   ErnieMModel.from_pretrained(__lowercase     )
          self.assertIsNotNone(__lowercase     )





@require_torch
class _lowerCAmelCase			(	unittest.TestCase					):







      @slow
      def      lowerCamelCase__      (  self     ):
        lowercase				:							List[str]									=   ErnieMModel.from_pretrained('''susnato/ernie-m-base_pytorch'''     )
        model.eval()
        lowercase				:							Union[str, Any]									=   torch.tensor([[0, 1, 2, 3, 4, 5]]     )
        lowercase				:							Tuple									=   model(__lowercase     )[0]

        # TODO Replace vocab size
        lowercase				:							int									=   768

        lowercase				:							Dict									=   torch.Size((1, 6, hidden_size)     )
        self.assertEqual(output.shape  ,    __lowercase     )

        lowercase				:							Union[str, Any]									=   torch.tensor(
            [[[-0.0012, 0.1245, -0.0214], [-0.0742, 0.0244, -0.0771], [-0.0333, 0.1164, -0.1554]]]     )

        self.assertTrue(torch.allclose(output[:, :3, :3]  ,    __lowercase  ,    atol=1e-3     )     )



import tempfile
import unittest

from diffusers import (
    DDIMScheduler,
    DDPMScheduler,
    DPMSolverMultistepScheduler,
    EulerAncestralDiscreteScheduler,
    EulerDiscreteScheduler,
    PNDMScheduler,
    logging,
)
from diffusers.configuration_utils import ConfigMixin, register_to_config
from diffusers.utils.testing_utils import CaptureLogger







class 					snake_case__(				UpperCAmelCase__				):







						'''simple docstring'''




						SCREAMING_SNAKE_CASE__   :	Union[str, Any]       =				"""config.json"""




						@register_to_config
						def __init__(					self ,    __lowercase=2 ,    __lowercase=5 ,    __lowercase=(2, 5) ,    __lowercase="for diffusion" ,    __lowercase=[1, 3] ,    )       ->     int:
										pass







class 					snake_case__(				UpperCAmelCase__				):







						'''simple docstring'''




						SCREAMING_SNAKE_CASE__   :	int       =				"""config.json"""




						@register_to_config
						def __init__(					self ,    __lowercase=2 ,    __lowercase=5 ,    __lowercase=(2, 5) ,    __lowercase="for diffusion" ,    __lowercase=[1, 3] ,    )       ->     Optional[Any]:
										pass







class 					snake_case__(				UpperCAmelCase__				):







						'''simple docstring'''




						SCREAMING_SNAKE_CASE__   :	int       =				"""config.json"""




						@register_to_config
						def __init__(					self ,    __lowercase=2 ,    __lowercase=5 ,    __lowercase=(2, 5) ,    __lowercase="for diffusion" ,    __lowercase=[1, 3] ,    __lowercase=[1, 3] ,    )       ->     List[str]:
										pass







class 					snake_case__(				UpperCAmelCase__				):







						'''simple docstring'''




						SCREAMING_SNAKE_CASE__   :	Optional[Any]       =				"""config.json"""




						@register_to_config
						def __init__(					self ,    __lowercase=2 ,    __lowercase=5 ,    __lowercase=(2, 5) ,    __lowercase="for diffusion" ,    __lowercase=[1, 5] ,    __lowercase=[5, 4] ,    )       ->     List[str]:
										pass







class 					snake_case__(				unittest.TestCase				):







						'''simple docstring'''




						def     lowercase_			(					self				)       ->     str:
										with self.assertRaises(__lowercase				):
														ConfigMixin.load_config('''dummy_path'''				)




						def     lowercase_			(					self				)       ->     Optional[int]:
										lowerCAmelCase_			:   List[str]     					=					SampleObject()
										lowerCAmelCase_			:   Dict     					=					obj.config
										assert config["a"] == 2
										assert config["b"] == 5
										assert config["c"] == (2, 5)
										assert config["d"] == "for diffusion"
										assert config["e"] == [1, 3]

										# init ignore private arguments
										lowerCAmelCase_			:   List[str]     					=					SampleObject(_name_or_path='''lalala'''				)
										lowerCAmelCase_			:   Dict     					=					obj.config
										assert config["a"] == 2
										assert config["b"] == 5
										assert config["c"] == (2, 5)
										assert config["d"] == "for diffusion"
										assert config["e"] == [1, 3]

										# can override default
										lowerCAmelCase_			:   List[Any]     					=					SampleObject(c=6				)
										lowerCAmelCase_			:   Optional[int]     					=					obj.config
										assert config["a"] == 2
										assert config["b"] == 5
										assert config["c"] == 6
										assert config["d"] == "for diffusion"
										assert config["e"] == [1, 3]

										# can use positional arguments.
										lowerCAmelCase_			:   Optional[Any]     					=					SampleObject(1 ,    c=6				)
										lowerCAmelCase_			:   Dict     					=					obj.config
										assert config["a"] == 1
										assert config["b"] == 5
										assert config["c"] == 6
										assert config["d"] == "for diffusion"
										assert config["e"] == [1, 3]




						def     lowercase_			(					self				)       ->     int:
										lowerCAmelCase_			:   List[Any]     					=					SampleObject()
										lowerCAmelCase_			:   str     					=					obj.config

										assert config["a"] == 2
										assert config["b"] == 5
										assert config["c"] == (2, 5)
										assert config["d"] == "for diffusion"
										assert config["e"] == [1, 3]

										with tempfile.TemporaryDirectory() as tmpdirname:
														obj.save_config(__lowercase				)
														lowerCAmelCase_			:   int     					=					SampleObject.from_config(SampleObject.load_config(__lowercase				)				)
														lowerCAmelCase_			:   Optional[Any]     					=					new_obj.config

										# unfreeze configs
										lowerCAmelCase_			:   str     					=					dict(__lowercase				)
										lowerCAmelCase_			:   Any     					=					dict(__lowercase				)

										assert config.pop('''c'''				) == (2, 5)  # instantiated as tuple
										assert new_config.pop('''c'''				) == [2, 5]  # saved & loaded as list because of json
										config.pop('''_use_default_values'''				)
										assert config == new_config




						def     lowercase_			(					self				)       ->     List[str]:
										lowerCAmelCase_			:   Optional[Any]     					=					logging.get_logger('''diffusers.configuration_utils'''				)
										# 30 for warning
										logger.setLevel(3_0				)

										with CaptureLogger(__lowercase				) as cap_logger:
														lowerCAmelCase_			:   int     					=					DDIMScheduler.from_pretrained(
														    '''hf-internal-testing/tiny-stable-diffusion-torch''' ,    subfolder='''scheduler'''				)

										assert ddim.__class__ == DDIMScheduler
										# no warning should be thrown
										assert cap_logger.out == ""




						def     lowercase_			(					self				)       ->     Optional[Any]:
										lowerCAmelCase_			:   List[Any]     					=					logging.get_logger('''diffusers.configuration_utils'''				)
										# 30 for warning
										logger.setLevel(3_0				)

										with CaptureLogger(__lowercase				) as cap_logger:
														lowerCAmelCase_			:   Any     					=					EulerDiscreteScheduler.from_pretrained(
														    '''hf-internal-testing/tiny-stable-diffusion-torch''' ,    subfolder='''scheduler'''				)

										assert euler.__class__ == EulerDiscreteScheduler
										# no warning should be thrown
										assert cap_logger.out == ""




						def     lowercase_			(					self				)       ->     Any:
										lowerCAmelCase_			:   Tuple     					=					logging.get_logger('''diffusers.configuration_utils'''				)
										# 30 for warning
										logger.setLevel(3_0				)

										with CaptureLogger(__lowercase				) as cap_logger:
														lowerCAmelCase_			:   Optional[int]     					=					EulerAncestralDiscreteScheduler.from_pretrained(
														    '''hf-internal-testing/tiny-stable-diffusion-torch''' ,    subfolder='''scheduler'''				)

										assert euler.__class__ == EulerAncestralDiscreteScheduler
										# no warning should be thrown
										assert cap_logger.out == ""




						def     lowercase_			(					self				)       ->     List[Any]:
										lowerCAmelCase_			:   Any     					=					logging.get_logger('''diffusers.configuration_utils'''				)
										# 30 for warning
										logger.setLevel(3_0				)

										with CaptureLogger(__lowercase				) as cap_logger:
														lowerCAmelCase_			:   Dict     					=					PNDMScheduler.from_pretrained(
														    '''hf-internal-testing/tiny-stable-diffusion-torch''' ,    subfolder='''scheduler'''				)

										assert pndm.__class__ == PNDMScheduler
										# no warning should be thrown
										assert cap_logger.out == ""




						def     lowercase_			(					self				)       ->     Tuple:
										lowerCAmelCase_			:   Optional[int]     					=					logging.get_logger('''diffusers.configuration_utils'''				)
										# 30 for warning
										logger.setLevel(3_0				)

										with CaptureLogger(__lowercase				) as cap_logger:
														lowerCAmelCase_			:   int     					=					DDPMScheduler.from_pretrained(
														    '''hf-internal-testing/tiny-stable-diffusion-torch''' ,    subfolder='''scheduler''' ,    prediction_type='''sample''' ,    beta_end=8 ,    )

										with CaptureLogger(__lowercase				) as cap_logger_a:
														lowerCAmelCase_			:   Tuple     					=					DDPMScheduler.from_pretrained('''google/ddpm-celebahq-256''' ,    beta_start=8_8				)

										assert ddpm.__class__ == DDPMScheduler
										assert ddpm.config.prediction_type == "sample"
										assert ddpm.config.beta_end == 8
										assert ddpm_a.config.beta_start == 8_8

										# no warning should be thrown
										assert cap_logger.out == ""
										assert cap_logger_a.out == ""




						def     lowercase_			(					self				)       ->     int:
										lowerCAmelCase_			:   Tuple     					=					logging.get_logger('''diffusers.configuration_utils'''				)
										# 30 for warning
										logger.setLevel(3_0				)

										with CaptureLogger(__lowercase				) as cap_logger:
														lowerCAmelCase_			:   List[str]     					=					DPMSolverMultistepScheduler.from_pretrained(
														    '''hf-internal-testing/tiny-stable-diffusion-torch''' ,    subfolder='''scheduler'''				)

										assert dpm.__class__ == DPMSolverMultistepScheduler
										# no warning should be thrown
										assert cap_logger.out == ""




						def     lowercase_			(					self				)       ->     Optional[Any]:
										# let's first save a config that should be in the form
										#    a=2,
										#    b=5,
										#    c=(2, 5),
										#    d="for diffusion",
										#    e=[1, 3],

										lowerCAmelCase_			:   Dict     					=					SampleObject()

										lowerCAmelCase_			:   Optional[int]     					=					{k: v for k, v in config.config.items() if not k.startswith('''_'''				)}

										# make sure that default config has all keys in `_use_default_values`
										assert set(config_dict.keys()				) == set(config.config._use_default_values				)

										with tempfile.TemporaryDirectory() as tmpdirname:
														config.save_config(__lowercase				)

														# now loading it with SampleObject2 should put f into `_use_default_values`
														lowerCAmelCase_			:   List[Any]     					=					SampleObjecta.from_config(__lowercase				)

														assert "f" in config._use_default_values
														assert config.f == [1, 3]

										# now loading the config, should **NOT** use [1, 3] for `f`, but the default [1, 4] value
										# **BECAUSE** it is part of `config._use_default_values`
										lowerCAmelCase_			:   List[Any]     					=					SampleObjecta.from_config(config.config				)
										assert new_config.f == [5, 4]

										config.config._use_default_values.pop()
										lowerCAmelCase_			:   int     					=					SampleObjecta.from_config(config.config				)
										assert new_config_a.f == [1, 3]

										# Nevertheless "e" should still be correctly loaded to [1, 3] from SampleObject2 instead of defaulting to [1, 5]
										assert new_config_a.e == [1, 3]