


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       UpperCAmelCase_   :

   '''simple docstring'''




   def __init__(						self		,							__A		,							__A=12		,							__A=7		,							__A=True		,							__A=True		,							__A=True		,							__A=99		,							__A=32		,							__A=32		,							__A=2		,							__A=4		,							__A=37		,							__A=0.1		,							__A=0.1		,							__A=512		,							__A=0.02		,							__A=0		,							__A=None		,							):






     """simple docstring"""





     lowerCamelCase					:   List[Any]       =							parent
     lowerCamelCase					:   Tuple       =							batch_size
     lowerCamelCase					:   Optional[Any]       =							seq_length
     lowerCamelCase					:   List[Any]       =							is_training
     lowerCamelCase					:   List[Any]       =							use_input_mask
     lowerCamelCase					:   Tuple       =							use_labels
     lowerCamelCase					:   Tuple       =							vocab_size
     lowerCamelCase					:   int       =							hidden_size
     lowerCamelCase					:   int       =							projection_dim
     lowerCamelCase					:   Any       =							num_hidden_layers
     lowerCamelCase					:   str       =							num_attention_heads
     lowerCamelCase					:   Dict       =							intermediate_size
     lowerCamelCase					:   int       =							dropout
     lowerCamelCase					:   int       =							attention_dropout
     lowerCamelCase					:   Optional[int]       =							max_position_embeddings
     lowerCamelCase					:   List[str]       =							initializer_range
     lowerCamelCase					:   int       =							scope
     lowerCamelCase					:   Dict       =							bos_token_id






   def _snake_case       (						self					):






     """simple docstring"""





     lowerCamelCase					:   Tuple       =							ids_tensor([self.batch_size, self.seq_length]		,							self.vocab_size					)

     lowerCamelCase					:   int       =							None
     if self.use_input_mask:
       lowerCamelCase					:   Optional[int]       =							random_attention_mask([self.batch_size, self.seq_length]					)

     if input_mask is not None:
       lowerCamelCase					:   List[Any]       =							input_mask.numpy()
       lowerCamelCase       ,      lowerCamelCase					:   Any       =							input_mask.shape
       lowerCamelCase					:   Any       =							np.random.randint(1		,							seq_length - 1		,							size=(batch_size,)					)
       for batch_idx, start_index in enumerate(UpperCamelCase__					):
         lowerCamelCase					:   Any       =							1
         lowerCamelCase					:   str       =							0

     lowerCamelCase					:   Optional[Any]       =							self.get_config()

     return config, input_ids, tf.convert_to_tensor(UpperCamelCase__					)






   def _snake_case       (						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 _snake_case       (						self		,							__A		,							__A		,							__A					):






     """simple docstring"""





     lowerCamelCase					:   Optional[Any]       =							TFBlipTextModel(config=UpperCamelCase__					)
     lowerCamelCase					:   Tuple       =							model(UpperCamelCase__		,							attention_mask=UpperCamelCase__		,							training=UpperCamelCase__					)
     lowerCamelCase					:   Union[str, Any]       =							model(UpperCamelCase__		,							training=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 _snake_case       (						self					):






     """simple docstring"""





     lowerCamelCase					:   Any       =							self.prepare_config_and_inputs()
     lowerCamelCase       ,      lowerCamelCase       ,      lowerCamelCase					:   Any       =							config_and_inputs
     lowerCamelCase					:   List[Any]       =							{"input_ids": input_ids, "attention_mask": input_mask}
     return config, inputs_dict



@require_tf
class       UpperCAmelCase_   (   _snake_case						,					unittest.TestCase       ):

   '''simple docstring'''




   __A					: Optional[int]							=						(TFBlipTextModel,) if is_tf_available() else ()
   __A					: Optional[int]							=						False
   __A					: Tuple							=						False
   __A					: Optional[int]							=						False






   def _snake_case       (						self					):






     """simple docstring"""





     lowerCamelCase					:   str       =							BlipTextModelTester(self					)
     lowerCamelCase					:   Tuple       =							ConfigTester(self		,							config_class=UpperCamelCase__		,							hidden_size=37					)






   def _snake_case       (						self					):






     """simple docstring"""





     self.config_tester.run_common_tests()






   def _snake_case       (						self					):






     """simple docstring"""





     lowerCamelCase					:   List[Any]       =							self.model_tester.prepare_config_and_inputs()
     self.model_tester.create_and_check_model(*UpperCamelCase__					)






   def _snake_case       (						self					):






     """simple docstring"""





     pass






   def _snake_case       (						self					):






     """simple docstring"""





     pass






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






     """simple docstring"""





     pass






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






     """simple docstring"""





     pass






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






     """simple docstring"""





     pass






   @slow
   def _snake_case       (						self					):






     """simple docstring"""





     for model_name in TF_BLIP_PRETRAINED_MODEL_ARCHIVE_LIST[:1]:
       lowerCamelCase					:   Dict       =							TFBlipTextModel.from_pretrained(UpperCamelCase__					)
       self.assertIsNotNone(UpperCamelCase__					)






   def _snake_case       (						self		,							__A=True					):






     """simple docstring"""





     super().test_pt_tf_model_equivalence(allow_missing_keys=UpperCamelCase__					)






'''simple docstring'''







import unittest

import numpy as np
import torch

from diffusers import PNDMPipeline, PNDMScheduler, UNetaDModel
from diffusers.utils.testing_utils import enable_full_determinism, require_torch, slow, torch_device


enable_full_determinism()


class        A__   (   unittest.TestCase      ):



    @property
    def        snake_case_      (       self							)    ->   int:





           '''simple docstring'''
           torch.manual_seed(0							)
           A_						       =   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""")		,					)
           return model







    def        snake_case_      (       self							)    ->   str:





           '''simple docstring'''
           A_						       =   self.dummy_uncond_unet
           A_						       =   PNDMScheduler()

           A_						       =   PNDMPipeline(unet=UpperCamelCase__		,					scheduler=UpperCamelCase__							)
           pndm.to(UpperCamelCase__							)
           pndm.set_progress_bar_config(disable=UpperCamelCase__							)

           A_						       =   torch.manual_seed(0							)
           A_						       =   pndm(generator=UpperCamelCase__		,					num_inference_steps=20		,					output_type="""numpy"""							).images

           A_						       =   torch.manual_seed(0							)
           A_						       =   pndm(generator=UpperCamelCase__		,					num_inference_steps=20		,					output_type="""numpy"""		,					return_dict=UpperCamelCase__							)[0]

           A_						       =   image[0, -3:, -3:, -1]
           A_						       =   image_from_tuple[0, -3:, -3:, -1]

           assert image.shape == (1, 32, 32, 3)
           A_						       =   np.array([1.0, 1.0, 0.0, 1.0, 0.0, 1.0, 0.0, 0.0, 0.0]							)

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


@slow
@require_torch
class        A__   (   unittest.TestCase      ):



    def        snake_case_      (       self							)    ->   Tuple:





           '''simple docstring'''
           A_						       =   """google/ddpm-cifar10-32"""

           A_						       =   UNetaDModel.from_pretrained(UpperCamelCase__							)
           A_						       =   PNDMScheduler()

           A_						       =   PNDMPipeline(unet=UpperCamelCase__		,					scheduler=UpperCamelCase__							)
           pndm.to(UpperCamelCase__							)
           pndm.set_progress_bar_config(disable=UpperCamelCase__							)
           A_						       =   torch.manual_seed(0							)
           A_						       =   pndm(generator=UpperCamelCase__		,					output_type="""numpy"""							).images

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

           assert image.shape == (1, 32, 32, 3)
           A_						       =   np.array([0.1564, 0.14645, 0.1406, 0.14715, 0.12425, 0.14045, 0.13115, 0.12175, 0.125]							)

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