



"""simple docstring"""


from __future__ import annotations

import unittest

import numpy as np

from transformers import BlipTextConfig
from transformers.testing_utils import require_tf, slow
from transformers.utils import is_tf_available

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


if is_tf_available():
		import tensorflow as tf

		from transformers import TFBlipTextModel
		from transformers.models.blip.modeling_tf_blip import TF_BLIP_PRETRAINED_MODEL_ARCHIVE_LIST







class 				A_      :



						"""simple docstring"""






						def __init__( self			:List[str]       ,  lowercase_			:List[Any]       ,  lowercase_			:Union[str, Any]=12       ,  lowercase_			:str=7       ,  lowercase_			:Any=True       ,  lowercase_			:Optional[int]=True       ,  lowercase_			:Optional[int]=True       ,  lowercase_			:str=99       ,  lowercase_			:int=32       ,  lowercase_			:Optional[int]=32       ,  lowercase_			:List[Any]=2       ,  lowercase_			:int=4       ,  lowercase_			:Dict=37       ,  lowercase_			:Optional[Any]=0.1       ,  lowercase_			:str=0.1       ,  lowercase_			:List[Any]=5_12       ,  lowercase_			:Dict=0.02       ,  lowercase_			:Optional[Any]=0       ,  lowercase_			:List[Any]=None       ,  )    ->      Tuple:
												UpperCAmelCase					=			parent
												UpperCAmelCase					=			batch_size
												UpperCAmelCase					=			seq_length
												UpperCAmelCase					=			is_training
												UpperCAmelCase					=			use_input_mask
												UpperCAmelCase					=			use_labels
												UpperCAmelCase					=			vocab_size
												UpperCAmelCase					=			hidden_size
												UpperCAmelCase					=			projection_dim
												UpperCAmelCase					=			num_hidden_layers
												UpperCAmelCase					=			num_attention_heads
												UpperCAmelCase					=			intermediate_size
												UpperCAmelCase					=			dropout
												UpperCAmelCase					=			attention_dropout
												UpperCAmelCase					=			max_position_embeddings
												UpperCAmelCase					=			initializer_range
												UpperCAmelCase					=			scope
												UpperCAmelCase					=			bos_token_id






						def      UpperCAmelCase__					( self			:List[str] )    ->      Optional[int]:
												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] )

												if input_mask is not None:
																		UpperCAmelCase					=			input_mask.numpy()
																		UpperCAmelCase					=			input_mask.shape
																		UpperCAmelCase					=			np.random.randint(1       ,  seq_length - 1       ,  size=(batch_size,) )
																		for batch_idx, start_index in enumerate(a_ ):
																								UpperCAmelCase					=			1
																								UpperCAmelCase					=			0

												UpperCAmelCase					=			self.get_config()

												return config, input_ids, tf.convert_to_tensor(a_ )






						def      UpperCAmelCase__					( self			:int )    ->      Optional[int]:
												return BlipTextConfig(
												    vocab_size=self.vocab_size       ,  hidden_size=self.hidden_size       ,  projection_dim=self.projection_dim       ,  num_hidden_layers=self.num_hidden_layers       ,  num_attention_heads=self.num_attention_heads       ,  intermediate_size=self.intermediate_size       ,  dropout=self.dropout       ,  attention_dropout=self.attention_dropout       ,  max_position_embeddings=self.max_position_embeddings       ,  initializer_range=self.initializer_range       ,  bos_token_id=self.bos_token_id       ,  )






						def      UpperCAmelCase__					( self			:Tuple       ,  lowercase_			:List[str]       ,  lowercase_			:List[Any]       ,  lowercase_			:List[str] )    ->      List[Any]:
												UpperCAmelCase					=			TFBlipTextModel(config=a_ )
												UpperCAmelCase					=			model(a_       ,  attention_mask=a_       ,  training=a_ )
												UpperCAmelCase					=			model(a_       ,  training=a_ )
												self.parent.assertEqual(result.last_hidden_state.shape       ,  (self.batch_size, self.seq_length, self.hidden_size) )
												self.parent.assertEqual(result.pooler_output.shape       ,  (self.batch_size, self.hidden_size) )






						def      UpperCAmelCase__					( self			:List[Any] )    ->      List[Any]:
												UpperCAmelCase					=			self.prepare_config_and_inputs()
												UpperCAmelCase					=			config_and_inputs
												UpperCAmelCase					=			{'''input_ids''': input_ids, '''attention_mask''': input_mask}
												return config, inputs_dict







@require_tf
class 				A_      (					__snake_case     ,       unittest.TestCase    ):



						"""simple docstring"""
						__UpperCamelCase		    =							(TFBlipTextModel,) if is_tf_available() else ()
						__UpperCamelCase		    =							False
						__UpperCamelCase		    =							False
						__UpperCamelCase		    =							False






						def      UpperCAmelCase__					( self			:Union[str, Any] )    ->      Any:
												UpperCAmelCase					=			BlipTextModelTester(self )
												UpperCAmelCase					=			ConfigTester(self       ,  config_class=a_       ,  hidden_size=37 )






						def      UpperCAmelCase__					( self			:Tuple )    ->      List[Any]:
												self.config_tester.run_common_tests()






						def      UpperCAmelCase__					( self			:List[Any] )    ->      Optional[int]:
												UpperCAmelCase					=			self.model_tester.prepare_config_and_inputs()
												self.model_tester.create_and_check_model(*a_ )






						def      UpperCAmelCase__					( self			:int )    ->      Optional[Any]:
												pass






						def      UpperCAmelCase__					( self			:Dict )    ->      Union[str, Any]:
												pass






						@unittest.skip(reason='Blip does not use inputs_embeds' )
						def      UpperCAmelCase__					( self			:List[Any] )    ->      Optional[int]:
												pass






						@unittest.skip(reason='BlipTextModel has no base class and is not available in MODEL_MAPPING' )
						def      UpperCAmelCase__					( self			:Any )    ->      Tuple:
												pass






						@unittest.skip(reason='BlipTextModel has no base class and is not available in MODEL_MAPPING' )
						def      UpperCAmelCase__					( self			:Any )    ->      Tuple:
												pass






						@slow
						def      UpperCAmelCase__					( self			:int )    ->      Any:

												for model_name in TF_BLIP_PRETRAINED_MODEL_ARCHIVE_LIST[:1]:
																		UpperCAmelCase					=			TFBlipTextModel.from_pretrained(a_ )
																		self.assertIsNotNone(a_ )






						def      UpperCAmelCase__					( self			:Optional[int]       ,  lowercase_			:str=True )    ->      int:
												super().test_pt_tf_model_equivalence(allow_missing_keys=a_ )










"""simple docstring"""


import tempfile

import torch

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

from .test_schedulers import SchedulerCommonTest







class 				A_      (					SCREAMING_SNAKE_CASE_    ):



						"""simple docstring"""
						__UpperCamelCase		    =							(UniPCMultistepScheduler,)
						__UpperCamelCase		    =							(("""num_inference_steps""", 25),)






						def      UpperCAmelCase__					( self			:Any       ,  **lowercase_			:Optional[Any] )    ->      Dict:
												UpperCAmelCase					=			{
												    'num_train_timesteps': 10_00,
												    'beta_start': 0.0001,
												    'beta_end': 0.02,
												    'beta_schedule': 'linear',
												    'solver_order': 2,
												    'solver_type': 'bh2',
												}

												config.update(**lowercase_ )
												return config






						def      UpperCAmelCase__					( self			:Optional[Any]       ,  lowercase_			:Optional[int]=0       ,  **lowercase_			:Optional[Any] )    ->      List[str]:
												UpperCAmelCase					=			dict(self.forward_default_kwargs )
												UpperCAmelCase					=			kwargs.pop('num_inference_steps'       ,  lowercase_ )
												UpperCAmelCase					=			self.dummy_sample
												UpperCAmelCase					=			0.1 * sample
												UpperCAmelCase					=			[residual + 0.2, residual + 0.15, residual + 0.10]

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

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

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

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






						def      UpperCAmelCase__					( self			:List[Any]       ,  lowercase_			:Dict=0       ,  **lowercase_			:Optional[int] )    ->      List[str]:
												UpperCAmelCase					=			dict(self.forward_default_kwargs )
												UpperCAmelCase					=			kwargs.pop('num_inference_steps'       ,  lowercase_ )
												UpperCAmelCase					=			self.dummy_sample
												UpperCAmelCase					=			0.1 * sample
												UpperCAmelCase					=			[residual + 0.2, residual + 0.15, residual + 0.10]

												for scheduler_class in self.scheduler_classes:
																		UpperCAmelCase					=			self.get_scheduler_config()
																		UpperCAmelCase					=			scheduler_class(**lowercase_ )
																		scheduler.set_timesteps(lowercase_ )

																		# 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(lowercase_ )
																								UpperCAmelCase					=			scheduler_class.from_pretrained(lowercase_ )
																								# copy over dummy past residuals
																								new_scheduler.set_timesteps(lowercase_ )

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

																		UpperCAmelCase					=			scheduler.step(lowercase_       ,  lowercase_       ,  lowercase_       ,  **lowercase_ ).prev_sample
																		UpperCAmelCase					=			new_scheduler.step(lowercase_       ,  lowercase_       ,  lowercase_       ,  **lowercase_ ).prev_sample

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






						def      UpperCAmelCase__					( self			:List[Any]       ,  lowercase_			:Optional[int]=None       ,  **lowercase_			:str )    ->      Dict:
												if scheduler is None:
																		UpperCAmelCase					=			self.scheduler_classes[0]
																		UpperCAmelCase					=			self.get_scheduler_config(**lowercase_ )
																		UpperCAmelCase					=			scheduler_class(**lowercase_ )

												UpperCAmelCase					=			self.scheduler_classes[0]
												UpperCAmelCase					=			self.get_scheduler_config(**lowercase_ )
												UpperCAmelCase					=			scheduler_class(**lowercase_ )

												UpperCAmelCase					=			10
												UpperCAmelCase					=			self.dummy_model()
												UpperCAmelCase					=			self.dummy_sample_deter
												scheduler.set_timesteps(lowercase_ )

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

												return sample






						def      UpperCAmelCase__					( self			:Union[str, Any] )    ->      Tuple:
												UpperCAmelCase					=			dict(self.forward_default_kwargs )

												UpperCAmelCase					=			kwargs.pop('num_inference_steps'       ,  lowercase_ )

												for scheduler_class in self.scheduler_classes:
																		UpperCAmelCase					=			self.get_scheduler_config()
																		UpperCAmelCase					=			scheduler_class(**lowercase_ )

																		UpperCAmelCase					=			self.dummy_sample
																		UpperCAmelCase					=			0.1 * sample

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

																		# copy over dummy past residuals (must be done after set_timesteps)
																		UpperCAmelCase					=			[residual + 0.2, residual + 0.15, residual + 0.10]
																		UpperCAmelCase					=			dummy_past_residuals[: scheduler.config.solver_order]

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

																		UpperCAmelCase					=			scheduler.step(lowercase_       ,  lowercase_       ,  lowercase_       ,  **lowercase_ ).prev_sample
																		UpperCAmelCase					=			scheduler.step(lowercase_       ,  lowercase_       ,  lowercase_       ,  **lowercase_ ).prev_sample

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






						def      UpperCAmelCase__					( self			:Optional[int] )    ->      Optional[Any]:
												# make sure that iterating over schedulers with same config names gives same results
												# for defaults
												UpperCAmelCase					=			UniPCMultistepScheduler(**self.get_scheduler_config() )
												UpperCAmelCase					=			self.full_loop(scheduler=lowercase_ )
												UpperCAmelCase					=			torch.mean(torch.abs(lowercase_ ) )

												assert abs(result_mean.item() - 0.2464 ) < 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=lowercase_ )
												UpperCAmelCase					=			torch.mean(torch.abs(lowercase_ ) )

												assert abs(result_mean.item() - 0.2464 ) < 1E-3






						def      UpperCAmelCase__					( self			:Optional[int] )    ->      List[str]:
												for timesteps in [25, 50, 1_00, 9_99, 10_00]:
																		self.check_over_configs(num_train_timesteps=lowercase_ )






						def      UpperCAmelCase__					( self			:int )    ->      str:
												self.check_over_configs(thresholding=lowercase_ )
												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=lowercase_       ,  prediction_type=lowercase_       ,  sample_max_value=lowercase_       ,  solver_order=lowercase_       ,  solver_type=lowercase_       ,  )






						def      UpperCAmelCase__					( self			:Any )    ->      str:
												for prediction_type in ["epsilon", "v_prediction"]:
																		self.check_over_configs(prediction_type=lowercase_ )






						def      UpperCAmelCase__					( 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=lowercase_       ,  solver_type=lowercase_       ,  prediction_type=lowercase_       ,  )
																														UpperCAmelCase					=			self.full_loop(
																														    solver_order=lowercase_       ,  solver_type=lowercase_       ,  prediction_type=lowercase_       ,  )
																														assert not torch.isnan(lowercase_ ).any(), "Samples have nan numbers"






						def      UpperCAmelCase__					( self			:Dict )    ->      List[Any]:
												self.check_over_configs(lower_order_final=lowercase_ )
												self.check_over_configs(lower_order_final=lowercase_ )






						def      UpperCAmelCase__					( self			:Any )    ->      List[Any]:
												for num_inference_steps in [1, 2, 3, 5, 10, 50, 1_00, 9_99, 10_00]:
																		self.check_over_forward(num_inference_steps=lowercase_       ,  time_step=0 )






						def      UpperCAmelCase__					( self			:int )    ->      Union[str, Any]:
												UpperCAmelCase					=			self.full_loop()
												UpperCAmelCase					=			torch.mean(torch.abs(lowercase_ ) )

												assert abs(result_mean.item() - 0.2464 ) < 1E-3






						def      UpperCAmelCase__					( self			:Optional[int] )    ->      str:
												UpperCAmelCase					=			self.full_loop(prediction_type='v_prediction' )
												UpperCAmelCase					=			torch.mean(torch.abs(lowercase_ ) )

												assert abs(result_mean.item() - 0.1014 ) < 1E-3






						def      UpperCAmelCase__					( self			:Tuple )    ->      Tuple:
												UpperCAmelCase					=			self.scheduler_classes[0]
												UpperCAmelCase					=			self.get_scheduler_config(thresholding=lowercase_       ,  dynamic_thresholding_ratio=0 )
												UpperCAmelCase					=			scheduler_class(**lowercase_ )

												UpperCAmelCase					=			10
												UpperCAmelCase					=			self.dummy_model()
												UpperCAmelCase					=			self.dummy_sample_deter.half()
												scheduler.set_timesteps(lowercase_ )

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

												assert sample.dtype == torch.floataa






						def      UpperCAmelCase__					( self			:List[Any]       ,  **lowercase_			:Optional[Any] )    ->      Dict:
												for scheduler_class in self.scheduler_classes:
																		UpperCAmelCase					=			self.get_scheduler_config(**lowercase_ )
																		UpperCAmelCase					=			scheduler_class(**lowercase_ )

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





