
import unittest

import numpy as np

from transformers import BlipTextConfig
from transformers.testing_utils import require_torch, slow, torch_device
from transformers.utils import is_torch_available

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


if is_torch_available():
      import torch

      from transformers import BlipTextModel
      from transformers.models.blip.modeling_blip import BLIP_PRETRAINED_MODEL_ARCHIVE_LIST

class 		lowercase_							:

 def __init__(   self  ,						__UpperCamelCase  ,						__UpperCamelCase=1_2  ,						__UpperCamelCase=7  ,						__UpperCamelCase=True  ,						__UpperCamelCase=True  ,						__UpperCamelCase=True  ,						__UpperCamelCase=9_9  ,						__UpperCamelCase=3_2  ,						__UpperCamelCase=3_2  ,						__UpperCamelCase=5  ,						__UpperCamelCase=4  ,						__UpperCamelCase=3_7  ,						__UpperCamelCase=0.1  ,						__UpperCamelCase=0.1  ,						__UpperCamelCase=5_1_2  ,						__UpperCamelCase=0.02  ,						__UpperCamelCase=0  ,						__UpperCamelCase=None  ,						):




        """simple docstring"""


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




        """simple docstring"""


        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_							,					UpperCamelCase_											=							input_mask.shape
               UpperCamelCase_											=							np.random.randint(1  ,						seq_length - 1  ,						size=(batch_size,)  )
               for batch_idx, start_index in enumerate(__UpperCamelCase  ):
                      UpperCamelCase_											=							1
                      UpperCamelCase_											=							0

        UpperCamelCase_											=							self.get_config()

        return config, input_ids, input_mask

 def lowerCamelCase_					(   self  ):




        """simple docstring"""


        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 lowerCamelCase_					(   self  ,						__UpperCamelCase  ,						__UpperCamelCase  ,						__UpperCamelCase  ):




        """simple docstring"""


        UpperCamelCase_											=							BlipTextModel(config=__UpperCamelCase  )
        model.to(__UpperCamelCase  )
        model.eval()
        with torch.no_grad():
               UpperCamelCase_											=							model(__UpperCamelCase  ,						attention_mask=__UpperCamelCase  )
               UpperCamelCase_											=							model(__UpperCamelCase  )
        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 lowerCamelCase_					(   self  ):




        """simple docstring"""


        UpperCamelCase_											=							self.prepare_config_and_inputs()
        UpperCamelCase_							,					UpperCamelCase_							,					UpperCamelCase_											=							config_and_inputs
        UpperCamelCase_											=							{"""input_ids""": input_ids, """attention_mask""": input_mask}
        return config, inputs_dict



@require_torch
class 		lowercase_							(							__SCREAMING_SNAKE_CASE				,						unittest.TestCase					):
 A__    :					List[Any]    =     (BlipTextModel,) if is_torch_available() else ()
 A__    :					Union[str, Any]    =     False
 A__    :					Any    =     False
 A__    :					Optional[Any]    =     False

 def lowerCamelCase_					(   self  ):




        """simple docstring"""


        UpperCamelCase_											=							BlipTextModelTester(self  )
        UpperCamelCase_											=							ConfigTester(self  ,						config_class=__UpperCamelCase  ,						hidden_size=3_7  )

 def lowerCamelCase_					(   self  ):




        """simple docstring"""


        self.config_tester.run_common_tests()

 def lowerCamelCase_					(   self  ):




        """simple docstring"""


        UpperCamelCase_											=							self.model_tester.prepare_config_and_inputs()
        self.model_tester.create_and_check_model(*__UpperCamelCase  )

 def lowerCamelCase_					(   self  ):




        """simple docstring"""


        pass

 def lowerCamelCase_					(   self  ):




        """simple docstring"""


        pass

 @unittest.skip(reason="""Blip does not use inputs_embeds"""  )
 def lowerCamelCase_					(   self  ):




        """simple docstring"""


        pass

 @unittest.skip(reason="""BlipTextModel has no base class and is not available in MODEL_MAPPING"""  )
 def lowerCamelCase_					(   self  ):




        """simple docstring"""


        pass

 @unittest.skip(reason="""BlipTextModel has no base class and is not available in MODEL_MAPPING"""  )
 def lowerCamelCase_					(   self  ):




        """simple docstring"""


        pass

 @slow
 def lowerCamelCase_					(   self  ):




        """simple docstring"""


        for model_name in BLIP_PRETRAINED_MODEL_ARCHIVE_LIST[:1]:
               UpperCamelCase_											=							BlipTextModel.from_pretrained(__UpperCamelCase  )
               self.assertIsNotNone(__UpperCamelCase  )

 def lowerCamelCase_					(   self  ):




        """simple docstring"""


        super().test_pt_tf_model_equivalence(allow_missing_keys=__UpperCamelCase  )





import tempfile

import torch

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

from .test_schedulers import SchedulerCommonTest

class 		lowercase_							(							__SCREAMING_SNAKE_CASE					):
 A__    :					List[Any]    =     (DPMSolverMultistepScheduler,)
 A__    :					List[str]    =     (("""num_inference_steps""", 25),)

 def lowerCamelCase_					(   self  ,						**__UpperCamelCase  ):




        """simple docstring"""


        UpperCamelCase_											=							{
            """num_train_timesteps""": 1_0_0_0,
            """beta_start""": 0.0_001,
            """beta_end""": 0.02,
            """beta_schedule""": """linear""",
            """solver_order""": 2,
            """prediction_type""": """epsilon""",
            """thresholding""": False,
            """sample_max_value""": 1.0,
            """algorithm_type""": """dpmsolver++""",
            """solver_type""": """midpoint""",
            """lower_order_final""": False,
            """lambda_min_clipped""": -float("""inf"""  ),
            """variance_type""": None,
        }

        config.update(**__UpperCamelCase  )
        return config

 def lowerCamelCase_					(   self  ,						__UpperCamelCase=0  ,						**__UpperCamelCase  ):




        """simple docstring"""


        UpperCamelCase_											=							dict(self.forward_default_kwargs  )
        UpperCamelCase_											=							kwargs.pop("""num_inference_steps"""  ,						__UpperCamelCase  )
        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  )
               UpperCamelCase_											=							scheduler_class(**__UpperCamelCase  )
               scheduler.set_timesteps(__UpperCamelCase  )
               # copy over dummy past residuals
               UpperCamelCase_											=							dummy_past_residuals[: scheduler.config.solver_order]

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

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

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

 def lowerCamelCase_					(   self  ):




        """simple docstring"""


        pass

 def lowerCamelCase_					(   self  ,						__UpperCamelCase=0  ,						**__UpperCamelCase  ):




        """simple docstring"""


        UpperCamelCase_											=							dict(self.forward_default_kwargs  )
        UpperCamelCase_											=							kwargs.pop("""num_inference_steps"""  ,						__UpperCamelCase  )
        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(**__UpperCamelCase  )
               scheduler.set_timesteps(__UpperCamelCase  )

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

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

               UpperCamelCase_											=							scheduler.step(__UpperCamelCase  ,						__UpperCamelCase  ,						__UpperCamelCase  ,						**__UpperCamelCase  ).prev_sample
               UpperCamelCase_											=							new_scheduler.step(__UpperCamelCase  ,						__UpperCamelCase  ,						__UpperCamelCase  ,						**__UpperCamelCase  ).prev_sample

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

 def lowerCamelCase_					(   self  ,						__UpperCamelCase=None  ,						**__UpperCamelCase  ):




        """simple docstring"""


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

        UpperCamelCase_											=							1_0
        UpperCamelCase_											=							self.dummy_model()
        UpperCamelCase_											=							self.dummy_sample_deter
        scheduler.set_timesteps(__UpperCamelCase  )

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

        return sample

 def lowerCamelCase_					(   self  ):




        """simple docstring"""


        UpperCamelCase_											=							dict(self.forward_default_kwargs  )

        UpperCamelCase_											=							kwargs.pop("""num_inference_steps"""  ,						__UpperCamelCase  )

        for scheduler_class in self.scheduler_classes:
               UpperCamelCase_											=							self.get_scheduler_config()
               UpperCamelCase_											=							scheduler_class(**__UpperCamelCase  )

               UpperCamelCase_											=							self.dummy_sample
               UpperCamelCase_											=							0.1 * sample

               if num_inference_steps is not None and hasattr(__UpperCamelCase  ,						"""set_timesteps"""  ):
                      scheduler.set_timesteps(__UpperCamelCase  )
               elif num_inference_steps is not None and not hasattr(__UpperCamelCase  ,						"""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(__UpperCamelCase  ,						__UpperCamelCase  ,						__UpperCamelCase  ,						**__UpperCamelCase  ).prev_sample
               UpperCamelCase_											=							scheduler.step(__UpperCamelCase  ,						__UpperCamelCase  ,						__UpperCamelCase  ,						**__UpperCamelCase  ).prev_sample

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

 def lowerCamelCase_					(   self  ):




        """simple docstring"""


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

 def lowerCamelCase_					(   self  ):




        """simple docstring"""


        self.check_over_configs(thresholding=__UpperCamelCase  )
        for order in [1, 2, 3]:
               for solver_type in ["midpoint", "heun"]:
                      for threshold in [0.5, 1.0, 2.0]:
                             for prediction_type in ["epsilon", "sample"]:
                                    self.check_over_configs(
                                        thresholding=__UpperCamelCase  ,						prediction_type=__UpperCamelCase  ,						sample_max_value=__UpperCamelCase  ,						algorithm_type="""dpmsolver++"""  ,						solver_order=__UpperCamelCase  ,						solver_type=__UpperCamelCase  ,						)

 def lowerCamelCase_					(   self  ):




        """simple docstring"""


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

 def lowerCamelCase_					(   self  ):




        """simple docstring"""


        for algorithm_type in ["dpmsolver", "dpmsolver++", "sde-dpmsolver", "sde-dpmsolver++"]:
               for solver_type in ["midpoint", "heun"]:
                      for order in [1, 2, 3]:
                             for prediction_type in ["epsilon", "sample"]:
                                    if algorithm_type in ["sde-dpmsolver", "sde-dpmsolver++"]:
                                           if order == 3:
                                                  continue
                                    else:
                                           self.check_over_configs(
                                               solver_order=__UpperCamelCase  ,						solver_type=__UpperCamelCase  ,						prediction_type=__UpperCamelCase  ,						algorithm_type=__UpperCamelCase  ,						)
                                    UpperCamelCase_											=							self.full_loop(
                                        solver_order=__UpperCamelCase  ,						solver_type=__UpperCamelCase  ,						prediction_type=__UpperCamelCase  ,						algorithm_type=__UpperCamelCase  ,						)
                                    assert not torch.isnan(__UpperCamelCase  ).any(), "Samples have nan numbers"

 def lowerCamelCase_					(   self  ):




        """simple docstring"""


        self.check_over_configs(lower_order_final=__UpperCamelCase  )
        self.check_over_configs(lower_order_final=__UpperCamelCase  )

 def lowerCamelCase_					(   self  ):




        """simple docstring"""


        self.check_over_configs(lambda_min_clipped=-float("""inf"""  )  )
        self.check_over_configs(lambda_min_clipped=-5.1  )

 def lowerCamelCase_					(   self  ):




        """simple docstring"""


        self.check_over_configs(variance_type=__UpperCamelCase  )
        self.check_over_configs(variance_type="""learned_range"""  )

 def lowerCamelCase_					(   self  ):




        """simple docstring"""


        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=__UpperCamelCase  ,						time_step=0  )

 def lowerCamelCase_					(   self  ):




        """simple docstring"""


        UpperCamelCase_											=							self.full_loop()
        UpperCamelCase_											=							torch.mean(torch.abs(__UpperCamelCase  )  )

        assert abs(result_mean.item() - 0.3_301  ) < 1e-3

 def lowerCamelCase_					(   self  ):




        """simple docstring"""


        UpperCamelCase_											=							self.full_loop(thresholding=__UpperCamelCase  ,						dynamic_thresholding_ratio=0.87  ,						sample_max_value=0.5  )
        UpperCamelCase_											=							torch.mean(torch.abs(__UpperCamelCase  )  )

        assert abs(result_mean.item() - 1.1_364  ) < 1e-3

 def lowerCamelCase_					(   self  ):




        """simple docstring"""


        UpperCamelCase_											=							self.full_loop(prediction_type="""v_prediction"""  )
        UpperCamelCase_											=							torch.mean(torch.abs(__UpperCamelCase  )  )

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

 def lowerCamelCase_					(   self  ):




        """simple docstring"""


        UpperCamelCase_											=							self.full_loop(prediction_type="""v_prediction"""  ,						use_karras_sigmas=__UpperCamelCase  )
        UpperCamelCase_											=							torch.mean(torch.abs(__UpperCamelCase  )  )

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

 def lowerCamelCase_					(   self  ):




        """simple docstring"""


        UpperCamelCase_											=							DPMSolverMultistepScheduler(**self.get_scheduler_config()  )
        UpperCamelCase_											=							self.full_loop(scheduler=__UpperCamelCase  )
        UpperCamelCase_											=							torch.mean(torch.abs(__UpperCamelCase  )  )

        assert abs(result_mean.item() - 0.3_301  ) < 1e-3

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

        UpperCamelCase_											=							self.full_loop(scheduler=__UpperCamelCase  )
        UpperCamelCase_											=							torch.mean(torch.abs(__UpperCamelCase  )  )

        assert abs(result_mean.item() - 0.3_301  ) < 1e-3

 def lowerCamelCase_					(   self  ):




        """simple docstring"""


        UpperCamelCase_											=							self.scheduler_classes[0]
        UpperCamelCase_											=							self.get_scheduler_config(thresholding=__UpperCamelCase  ,						dynamic_thresholding_ratio=0  )
        UpperCamelCase_											=							scheduler_class(**__UpperCamelCase  )

        UpperCamelCase_											=							1_0
        UpperCamelCase_											=							self.dummy_model()
        UpperCamelCase_											=							self.dummy_sample_deter.half()
        scheduler.set_timesteps(__UpperCamelCase  )

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

        assert sample.dtype == torch.floataa

 def lowerCamelCase_					(   self  ,						**__UpperCamelCase  ):




        """simple docstring"""


        for scheduler_class in self.scheduler_classes:
               UpperCamelCase_											=							self.get_scheduler_config(**__UpperCamelCase  )
               UpperCamelCase_											=							scheduler_class(**__UpperCamelCase  )

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



