import tempfile

import torch

from diffusers import (
    DEISMultistepScheduler,
    DPMSolverMultistepScheduler,
    DPMSolverSinglestepScheduler,
    UniPCMultistepScheduler,
)

from .test_schedulers import SchedulerCommonTest






class 						A   (   a__   ):
							a_        =      (UniPCMultistepScheduler,)
							a_        =      (('''num_inference_steps''', 2_5),)





							def       snake_case__						(      self				:							List[Any]     ,		**__a				:							int	)							->	str:
								__UpperCAmelCase							=			{
								    'num_train_timesteps': 1_0_0_0,
								    'beta_start': 0.0_0_0_1,
								    'beta_end': 0.0_2,
								    'beta_schedule': 'linear',
								    'solver_order': 2,
								    'solver_type': 'bh2',
								}

								config.update(**_A	)
								return config





							def       snake_case__						(      self				:							Optional[Any]     ,		__a				:							int=0     ,		**__a				:							Tuple	)							->	List[str]:
								__UpperCAmelCase							=			dict(self.forward_default_kwargs	)
								__UpperCAmelCase							=			kwargs.pop('''num_inference_steps'''     ,		_A	)
								__UpperCAmelCase							=			self.dummy_sample
								__UpperCAmelCase							=			0.1 * sample
								__UpperCAmelCase							=			[residual + 0.2, residual + 0.1_5, residual + 0.1_0]

								for scheduler_class in self.scheduler_classes:
									__UpperCAmelCase							=			self.get_scheduler_config(**_A	)
									__UpperCAmelCase							=			scheduler_class(**_A	)
									scheduler.set_timesteps(_A	)
									# copy over dummy past residuals
									__UpperCAmelCase							=			dummy_past_residuals[: scheduler.config.solver_order]

									with tempfile.TemporaryDirectory() as tmpdirname:
										scheduler.save_config(_A	)
										__UpperCAmelCase							=			scheduler_class.from_pretrained(_A	)
										new_scheduler.set_timesteps(_A	)
										# copy over dummy past residuals
										__UpperCAmelCase							=			dummy_past_residuals[: new_scheduler.config.solver_order]

									__UpperCAmelCase							=			sample, sample
									for t in range(_A     ,		time_step + scheduler.config.solver_order + 1	):
										__UpperCAmelCase							=			scheduler.step(_A     ,		_A     ,		_A     ,		**_A	).prev_sample
										__UpperCAmelCase							=			new_scheduler.step(_A     ,		_A     ,		_A     ,		**_A	).prev_sample

										assert torch.sum(torch.abs(output - new_output	)	) < 1e-5, "Scheduler outputs are not identical"





							def       snake_case__						(      self				:							Any     ,		__a				:							Tuple=0     ,		**__a				:							str	)							->	List[Any]:
								__UpperCAmelCase							=			dict(self.forward_default_kwargs	)
								__UpperCAmelCase							=			kwargs.pop('''num_inference_steps'''     ,		_A	)
								__UpperCAmelCase							=			self.dummy_sample
								__UpperCAmelCase							=			0.1 * sample
								__UpperCAmelCase							=			[residual + 0.2, residual + 0.1_5, residual + 0.1_0]

								for scheduler_class in self.scheduler_classes:
									__UpperCAmelCase							=			self.get_scheduler_config()
									__UpperCAmelCase							=			scheduler_class(**_A	)
									scheduler.set_timesteps(_A	)

									# copy over dummy past residuals (must be after setting timesteps)
									__UpperCAmelCase							=			dummy_past_residuals[: scheduler.config.solver_order]

									with tempfile.TemporaryDirectory() as tmpdirname:
										scheduler.save_config(_A	)
										__UpperCAmelCase							=			scheduler_class.from_pretrained(_A	)
										# copy over dummy past residuals
										new_scheduler.set_timesteps(_A	)

										# copy over dummy past residual (must be after setting timesteps)
										__UpperCAmelCase							=			dummy_past_residuals[: new_scheduler.config.solver_order]

									__UpperCAmelCase							=			scheduler.step(_A     ,		_A     ,		_A     ,		**_A	).prev_sample
									__UpperCAmelCase							=			new_scheduler.step(_A     ,		_A     ,		_A     ,		**_A	).prev_sample

									assert torch.sum(torch.abs(output - new_output	)	) < 1e-5, "Scheduler outputs are not identical"





							def       snake_case__						(      self				:							Dict     ,		__a				:							List[Any]=None     ,		**__a				:							str	)							->	List[Any]:

								if scheduler is None:
									__UpperCAmelCase							=			self.scheduler_classes[0]
									__UpperCAmelCase							=			self.get_scheduler_config(**_A	)
									__UpperCAmelCase							=			scheduler_class(**_A	)

								__UpperCAmelCase							=			self.scheduler_classes[0]
								__UpperCAmelCase							=			self.get_scheduler_config(**_A	)
								__UpperCAmelCase							=			scheduler_class(**_A	)

								__UpperCAmelCase							=			1_0
								__UpperCAmelCase							=			self.dummy_model()
								__UpperCAmelCase							=			self.dummy_sample_deter
								scheduler.set_timesteps(_A	)

								for i, t in enumerate(scheduler.timesteps	):
									__UpperCAmelCase							=			model(_A     ,		_A	)
									__UpperCAmelCase							=			scheduler.step(_A     ,		_A     ,		_A	).prev_sample

								return sample





							def       snake_case__						(      self				:							List[str]	)							->	Dict:
								__UpperCAmelCase							=			dict(self.forward_default_kwargs	)

								__UpperCAmelCase							=			kwargs.pop('''num_inference_steps'''     ,		_A	)

								for scheduler_class in self.scheduler_classes:
									__UpperCAmelCase							=			self.get_scheduler_config()
									__UpperCAmelCase							=			scheduler_class(**_A	)

									__UpperCAmelCase							=			self.dummy_sample
									__UpperCAmelCase							=			0.1 * sample

									if num_inference_steps is not None and hasattr(_A     ,		'''set_timesteps'''	):
										scheduler.set_timesteps(_A	)
									elif num_inference_steps is not None and not hasattr(_A     ,		'''set_timesteps'''	):
										__UpperCAmelCase							=			num_inference_steps

									# copy over dummy past residuals (must be done after set_timesteps)
									__UpperCAmelCase							=			[residual + 0.2, residual + 0.1_5, residual + 0.1_0]
									__UpperCAmelCase							=			dummy_past_residuals[: scheduler.config.solver_order]

									__UpperCAmelCase							=			scheduler.timesteps[5]
									__UpperCAmelCase							=			scheduler.timesteps[6]

									__UpperCAmelCase							=			scheduler.step(_A     ,		_A     ,		_A     ,		**_A	).prev_sample
									__UpperCAmelCase							=			scheduler.step(_A     ,		_A     ,		_A     ,		**_A	).prev_sample

									self.assertEqual(output_a.shape     ,		sample.shape	)
									self.assertEqual(output_a.shape     ,		output_a.shape	)





							def       snake_case__						(      self				:							Optional[int]	)							->	int:
								__UpperCAmelCase							=			UniPCMultistepScheduler(**self.get_scheduler_config()	)
								__UpperCAmelCase							=			self.full_loop(scheduler=_A	)
								__UpperCAmelCase							=			torch.mean(torch.abs(_A	)	)

								assert abs(result_mean.item() - 0.2_4_6_4	) < 1e-3

								__UpperCAmelCase							=			DPMSolverSinglestepScheduler.from_config(scheduler.config	)
								__UpperCAmelCase							=			DEISMultistepScheduler.from_config(scheduler.config	)
								__UpperCAmelCase							=			DPMSolverMultistepScheduler.from_config(scheduler.config	)
								__UpperCAmelCase							=			UniPCMultistepScheduler.from_config(scheduler.config	)

								__UpperCAmelCase							=			self.full_loop(scheduler=_A	)
								__UpperCAmelCase							=			torch.mean(torch.abs(_A	)	)

								assert abs(result_mean.item() - 0.2_4_6_4	) < 1e-3





							def       snake_case__						(      self				:							int	)							->	str:

								for timesteps in [2_5, 5_0, 1_0_0, 9_9_9, 1_0_0_0]:
									self.check_over_configs(num_train_timesteps=_A	)





							def       snake_case__						(      self				:							Optional[Any]	)							->	Optional[int]:
								self.check_over_configs(thresholding=_A	)
								for order in [1, 2, 3]:
									for solver_type in ["bh1", "bh2"]:
										for threshold in [0.5, 1.0, 2.0]:
											for prediction_type in ["epsilon", "sample"]:
												self.check_over_configs(
												    thresholding=_A     ,		prediction_type=_A     ,		sample_max_value=_A     ,		solver_order=_A     ,		solver_type=_A     ,		)





							def       snake_case__						(      self				:							Any	)							->	Any:

								for prediction_type in ["epsilon", "v_prediction"]:
									self.check_over_configs(prediction_type=_A	)





							def       snake_case__						(      self				:							str	)							->	Optional[Any]:

								for solver_type in ["bh1", "bh2"]:
									for order in [1, 2, 3]:
										for prediction_type in ["epsilon", "sample"]:
											self.check_over_configs(
											    solver_order=_A     ,		solver_type=_A     ,		prediction_type=_A     ,		)
											__UpperCAmelCase							=			self.full_loop(
											    solver_order=_A     ,		solver_type=_A     ,		prediction_type=_A     ,		)
											assert not torch.isnan(_A	).any(), "Samples have nan numbers"





							def       snake_case__						(      self				:							List[Any]	)							->	List[Any]:
								self.check_over_configs(lower_order_final=_A	)
								self.check_over_configs(lower_order_final=_A	)





							def       snake_case__						(      self				:							Optional[int]	)							->	Optional[int]:

								for num_inference_steps in [1, 2, 3, 5, 1_0, 5_0, 1_0_0, 9_9_9, 1_0_0_0]:
									self.check_over_forward(num_inference_steps=_A     ,		time_step=0	)





							def       snake_case__						(      self				:							Optional[Any]	)							->	int:
								__UpperCAmelCase							=			self.full_loop()
								__UpperCAmelCase							=			torch.mean(torch.abs(_A	)	)

								assert abs(result_mean.item() - 0.2_4_6_4	) < 1e-3





							def       snake_case__						(      self				:							List[str]	)							->	Optional[int]:
								__UpperCAmelCase							=			self.full_loop(prediction_type='''v_prediction'''	)
								__UpperCAmelCase							=			torch.mean(torch.abs(_A	)	)

								assert abs(result_mean.item() - 0.1_0_1_4	) < 1e-3





							def       snake_case__						(      self				:							Any	)							->	str:
								__UpperCAmelCase							=			self.scheduler_classes[0]
								__UpperCAmelCase							=			self.get_scheduler_config(thresholding=_A     ,		dynamic_thresholding_ratio=0	)
								__UpperCAmelCase							=			scheduler_class(**_A	)

								__UpperCAmelCase							=			1_0
								__UpperCAmelCase							=			self.dummy_model()
								__UpperCAmelCase							=			self.dummy_sample_deter.half()
								scheduler.set_timesteps(_A	)

								for i, t in enumerate(scheduler.timesteps	):
									__UpperCAmelCase							=			model(_A     ,		_A	)
									__UpperCAmelCase							=			scheduler.step(_A     ,		_A     ,		_A	).prev_sample

								assert sample.dtype == torch.floataa






							def       snake_case__						(      self				:							Optional[int]     ,		**__a				:							List[str]	)							->	Any:

								for scheduler_class in self.scheduler_classes:
									__UpperCAmelCase							=			self.get_scheduler_config(**_A	)
									__UpperCAmelCase							=			scheduler_class(**_A	)

									scheduler.set_timesteps(scheduler.config.num_train_timesteps	)
									assert len(scheduler.timesteps.unique()	) == scheduler.num_inference_steps

'''simple docstring'''


from __future__ import annotations

import unittest

from transformers import DistilBertConfig, is_tf_available
from transformers.testing_utils import require_tf, slow

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


if is_tf_available():
					import tensorflow as tf

					from transformers.models.distilbert.modeling_tf_distilbert import (
					    TF_DISTILBERT_PRETRAINED_MODEL_ARCHIVE_LIST,
					    TFDistilBertForMaskedLM,
					    TFDistilBertForMultipleChoice,
					    TFDistilBertForQuestionAnswering,
					    TFDistilBertForSequenceClassification,
					    TFDistilBertForTokenClassification,
					    TFDistilBertModel,
					)






class 						A   :





							def __init__(      self				:							List[Any]     ,		__a				:							Any     ,		)							->	Dict:
								__UpperCAmelCase							=			parent
								__UpperCAmelCase							=			1_3
								__UpperCAmelCase							=			7
								__UpperCAmelCase							=			True
								__UpperCAmelCase							=			True
								__UpperCAmelCase							=			False
								__UpperCAmelCase							=			True
								__UpperCAmelCase							=			9_9
								__UpperCAmelCase							=			3_2
								__UpperCAmelCase							=			2
								__UpperCAmelCase							=			4
								__UpperCAmelCase							=			3_7
								__UpperCAmelCase							=			'''gelu'''
								__UpperCAmelCase							=			0.1
								__UpperCAmelCase							=			0.1
								__UpperCAmelCase							=			5_1_2
								__UpperCAmelCase							=			1_6
								__UpperCAmelCase							=			2
								__UpperCAmelCase							=			0.0_2
								__UpperCAmelCase							=			3
								__UpperCAmelCase							=			4
								__UpperCAmelCase							=			None





							def       snake_case__						(      self				:							Optional[int]	)							->	Dict:
								__UpperCAmelCase							=			ids_tensor([self.batch_size, self.seq_length]     ,		self.vocab_size	)

								__UpperCAmelCase							=			None
								if self.use_input_mask:
									__UpperCAmelCase							=			random_attention_mask([self.batch_size, self.seq_length]	)

								__UpperCAmelCase							=			None
								__UpperCAmelCase							=			None
								__UpperCAmelCase							=			None
								if self.use_labels:
									__UpperCAmelCase							=			ids_tensor([self.batch_size]     ,		self.type_sequence_label_size	)
									__UpperCAmelCase							=			ids_tensor([self.batch_size, self.seq_length]     ,		self.num_labels	)
									__UpperCAmelCase							=			ids_tensor([self.batch_size]     ,		self.num_choices	)

								__UpperCAmelCase							=			DistilBertConfig(
								    vocab_size=self.vocab_size     ,		dim=self.hidden_size     ,		n_layers=self.num_hidden_layers     ,		n_heads=self.num_attention_heads     ,		hidden_dim=self.intermediate_size     ,		hidden_act=self.hidden_act     ,		dropout=self.hidden_dropout_prob     ,		attention_dropout=self.attention_probs_dropout_prob     ,		max_position_embeddings=self.max_position_embeddings     ,		initializer_range=self.initializer_range     ,		)

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





							def       snake_case__						(      self				:							Union[str, Any]     ,		__a				:							List[str]     ,		__a				:							int     ,		__a				:							Union[str, Any]     ,		__a				:							Union[str, Any]     ,		__a				:							List[Any]     ,		__a				:							int	)							->	Any:
								__UpperCAmelCase							=			TFDistilBertModel(config=__a	)
								__UpperCAmelCase							=			{'''input_ids''': input_ids, '''attention_mask''': input_mask}

								__UpperCAmelCase							=			model(__a	)

								__UpperCAmelCase							=			[input_ids, input_mask]

								__UpperCAmelCase							=			model(__a	)

								self.parent.assertEqual(result.last_hidden_state.shape     ,		(self.batch_size, self.seq_length, self.hidden_size)	)





							def       snake_case__						(      self				:							Tuple     ,		__a				:							List[Any]     ,		__a				:							int     ,		__a				:							Tuple     ,		__a				:							List[Any]     ,		__a				:							Union[str, Any]     ,		__a				:							List[Any]	)							->	int:
								__UpperCAmelCase							=			TFDistilBertForMaskedLM(config=__a	)
								__UpperCAmelCase							=			{'''input_ids''': input_ids, '''attention_mask''': input_mask}
								__UpperCAmelCase							=			model(__a	)
								self.parent.assertEqual(result.logits.shape     ,		(self.batch_size, self.seq_length, self.vocab_size)	)





							def       snake_case__						(      self				:							Optional[int]     ,		__a				:							Any     ,		__a				:							Union[str, Any]     ,		__a				:							Optional[int]     ,		__a				:							int     ,		__a				:							Optional[Any]     ,		__a				:							Optional[int]	)							->	Dict:
								__UpperCAmelCase							=			TFDistilBertForQuestionAnswering(config=__a	)
								__UpperCAmelCase							=			{
								    '''input_ids''': input_ids,
								    '''attention_mask''': input_mask,
								}
								__UpperCAmelCase							=			model(__a	)
								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       snake_case__						(      self				:							Any     ,		__a				:							Optional[Any]     ,		__a				:							List[str]     ,		__a				:							Dict     ,		__a				:							Dict     ,		__a				:							int     ,		__a				:							List[Any]	)							->	Dict:
								__UpperCAmelCase							=			self.num_labels
								__UpperCAmelCase							=			TFDistilBertForSequenceClassification(__a	)
								__UpperCAmelCase							=			{'''input_ids''': input_ids, '''attention_mask''': input_mask}
								__UpperCAmelCase							=			model(__a	)
								self.parent.assertEqual(result.logits.shape     ,		(self.batch_size, self.num_labels)	)





							def       snake_case__						(      self				:							Union[str, Any]     ,		__a				:							int     ,		__a				:							str     ,		__a				:							Union[str, Any]     ,		__a				:							Optional[int]     ,		__a				:							List[str]     ,		__a				:							Dict	)							->	str:
								__UpperCAmelCase							=			self.num_choices
								__UpperCAmelCase							=			TFDistilBertForMultipleChoice(__a	)
								__UpperCAmelCase							=			tf.tile(tf.expand_dims(__a     ,		1	)     ,		(1, self.num_choices, 1)	)
								__UpperCAmelCase							=			tf.tile(tf.expand_dims(__a     ,		1	)     ,		(1, self.num_choices, 1)	)
								__UpperCAmelCase							=			{
								    '''input_ids''': multiple_choice_inputs_ids,
								    '''attention_mask''': multiple_choice_input_mask,
								}
								__UpperCAmelCase							=			model(__a	)
								self.parent.assertEqual(result.logits.shape     ,		(self.batch_size, self.num_choices)	)





							def       snake_case__						(      self				:							int     ,		__a				:							Optional[Any]     ,		__a				:							int     ,		__a				:							Tuple     ,		__a				:							int     ,		__a				:							Optional[int]     ,		__a				:							Optional[int]	)							->	int:
								__UpperCAmelCase							=			self.num_labels
								__UpperCAmelCase							=			TFDistilBertForTokenClassification(__a	)
								__UpperCAmelCase							=			{'''input_ids''': input_ids, '''attention_mask''': input_mask}
								__UpperCAmelCase							=			model(__a	)
								self.parent.assertEqual(result.logits.shape     ,		(self.batch_size, self.seq_length, self.num_labels)	)






							def       snake_case__						(      self				:							str	)							->	Any:
								__UpperCAmelCase							=			self.prepare_config_and_inputs()
								((__UpperCAmelCase)				,			(__UpperCAmelCase)				,			(__UpperCAmelCase)				,			(__UpperCAmelCase)				,			(__UpperCAmelCase)				,			(__UpperCAmelCase))							=			config_and_inputs
								__UpperCAmelCase							=			{'''input_ids''': input_ids, '''attention_mask''': input_mask}
								return config, inputs_dict






@require_tf
class 						A   (   UpperCAmelCase       ,	UpperCAmelCase       ,	unittest.TestCase   ):
							a_        =      (
							    (
							        TFDistilBertModel,
							        TFDistilBertForMaskedLM,
							        TFDistilBertForQuestionAnswering,
							        TFDistilBertForSequenceClassification,
							        TFDistilBertForTokenClassification,
							        TFDistilBertForMultipleChoice,
							    )
							    if is_tf_available()
							    else None
							)
							a_        =      (
							    {
							        '''feature-extraction''': TFDistilBertModel,
							        '''fill-mask''': TFDistilBertForMaskedLM,
							        '''question-answering''': TFDistilBertForQuestionAnswering,
							        '''text-classification''': TFDistilBertForSequenceClassification,
							        '''token-classification''': TFDistilBertForTokenClassification,
							        '''zero-shot''': TFDistilBertForSequenceClassification,
							    }
							    if is_tf_available()
							    else {}
							)
							a_        =      False
							a_        =      False





							def       snake_case__						(      self				:							Any	)							->	Any:
								__UpperCAmelCase							=			TFDistilBertModelTester(self	)
								__UpperCAmelCase							=			ConfigTester(self     ,		config_class=__a     ,		dim=3_7	)





							def       snake_case__						(      self				:							List[Any]	)							->	Optional[int]:
								self.config_tester.run_common_tests()





							def       snake_case__						(      self				:							Any	)							->	str:
								__UpperCAmelCase							=			self.model_tester.prepare_config_and_inputs()
								self.model_tester.create_and_check_distilbert_model(*__a	)





							def       snake_case__						(      self				:							Tuple	)							->	Dict:
								__UpperCAmelCase							=			self.model_tester.prepare_config_and_inputs()
								self.model_tester.create_and_check_distilbert_for_masked_lm(*__a	)





							def       snake_case__						(      self				:							Union[str, Any]	)							->	Any:
								__UpperCAmelCase							=			self.model_tester.prepare_config_and_inputs()
								self.model_tester.create_and_check_distilbert_for_question_answering(*__a	)





							def       snake_case__						(      self				:							Optional[Any]	)							->	Dict:
								__UpperCAmelCase							=			self.model_tester.prepare_config_and_inputs()
								self.model_tester.create_and_check_distilbert_for_sequence_classification(*__a	)





							def       snake_case__						(      self				:							Any	)							->	int:
								__UpperCAmelCase							=			self.model_tester.prepare_config_and_inputs()
								self.model_tester.create_and_check_distilbert_for_multiple_choice(*__a	)





							def       snake_case__						(      self				:							List[str]	)							->	List[Any]:
								__UpperCAmelCase							=			self.model_tester.prepare_config_and_inputs()
								self.model_tester.create_and_check_distilbert_for_token_classification(*__a	)






							@slow
							def       snake_case__						(      self				:							Dict	)							->	Tuple:
								for model_name in list(TF_DISTILBERT_PRETRAINED_MODEL_ARCHIVE_LIST[:1]	):
									__UpperCAmelCase							=			TFDistilBertModel.from_pretrained(__a	)
									self.assertIsNotNone(__a	)






@require_tf
class 						A   (   unittest.TestCase   ):





							@slow
							def       snake_case__						(      self				:							int	)							->	Dict:
								__UpperCAmelCase							=			TFDistilBertModel.from_pretrained('''distilbert-base-uncased'''	)
								__UpperCAmelCase							=			tf.constant([[0, 1, 2, 3, 4, 5]]	)
								__UpperCAmelCase							=			model(__a	)[0]

								__UpperCAmelCase							=			[1, 6, 7_6_8]
								self.assertEqual(output.shape     ,		__a	)

								__UpperCAmelCase							=			tf.constant(
								    [
								        [
								            [0.1_9_2_6_1_8_8_5, -0.1_3_7_3_2_9_5_5, 0.4_1_1_9_7_9_9],
								            [0.2_2_1_5_0_1_5_6, -0.0_7_4_2_2_6_6_1, 0.3_9_0_3_7_2_0_4],
								            [0.2_2_7_5_6_0_1_8, -0.0_8_9_6_4_1_4, 0.3_7_0_1_4_6_7],
								        ]
								    ]	)
								tf.debugging.assert_near(output[:, :3, :3]     ,		__a     ,		atol=1e-4	)
