


'''simple docstring'''

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

 def __init__(			self			:						Any,       a_			:						Optional[Any],       a_			:						Any=12,       a_			:						Union[str, Any]=7,       a_			:						int=True,       a_			:						Dict=True,       a_			:						Any=True,       a_			:						Tuple=99,       a_			:						Tuple=32,       a_			:						Any=32,       a_			:						Optional[Any]=5,       a_			:						Tuple=4,       a_			:						List[str]=37,       a_			:						Optional[Any]=0.1,       a_			:						List[str]=0.1,       a_			:						List[str]=512,       a_			:						List[Any]=0.02,       a_			:						List[str]=0,       a_			:						int=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 		lowercase_    (			self			:						List[str]       ):





    """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(a_       ):
          UpperCamelCase__			    =    1
          UpperCamelCase__			    =    0

    UpperCamelCase__			    =    self.get_config()

    return config, input_ids, input_mask

 def 		lowercase_    (			self			:						List[str]       ):





    """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 		lowercase_    (			self			:						Any,       a_			:						Optional[int],       a_			:						Union[str, Any],       a_			:						Union[str, Any]       ):





    """simple docstring"""



    UpperCamelCase__			    =    BlipTextModel(config=a_       )
    model.to(a_       )
    model.eval()
    with torch.no_grad():
       UpperCamelCase__			    =    model(a_,       attention_mask=a_       )
       UpperCamelCase__			    =    model(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 		lowercase_    (			self			:						Tuple       ):





    """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 			UpperCAmelCase			(							SCREAMING_SNAKE_CASE__		,      unittest.TestCase):
 _lowerCamelCase			:       Union[str, Any]            =       (BlipTextModel,) if is_torch_available() else ()
 _lowerCamelCase			:       int            =       False
 _lowerCamelCase			:       int            =       False
 _lowerCamelCase			:       Optional[int]            =       False

 def 		lowercase_    (			self			:						List[str]       ):





    """simple docstring"""



    UpperCamelCase__			    =    BlipTextModelTester(self       )
    UpperCamelCase__			    =    ConfigTester(self,       config_class=a_,       hidden_size=37       )

 def 		lowercase_    (			self			:						Tuple       ):





    """simple docstring"""



    self.config_tester.run_common_tests()

 def 		lowercase_    (			self			:						Optional[Any]       ):





    """simple docstring"""



    UpperCamelCase__			    =    self.model_tester.prepare_config_and_inputs()
    self.model_tester.create_and_check_model(*a_       )

 def 		lowercase_    (			self			:						Any       ):





    """simple docstring"""



    pass

 def 		lowercase_    (			self			:						Optional[Any]       ):





    """simple docstring"""



    pass

 @unittest.skip(reason="Blip does not use inputs_embeds"       )
 def 		lowercase_    (			self			:						List[str]       ):





    """simple docstring"""



    pass

 @unittest.skip(reason="BlipTextModel has no base class and is not available in MODEL_MAPPING"       )
 def 		lowercase_    (			self			:						List[str]       ):





    """simple docstring"""



    pass

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





    """simple docstring"""



    pass

 @slow
 def 		lowercase_    (			self			:						List[str]       ):





    """simple docstring"""



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

 def 		lowercase_    (			self			:						Dict       ):





    """simple docstring"""



    super().test_pt_tf_model_equivalence(allow_missing_keys=a_       )



'''simple docstring'''

import random
import unittest

import numpy as np
import torch
from PIL import Image
from torch import nn
from transformers import (
    CLIPImageProcessor,
    CLIPTextConfig,
    CLIPTextModelWithProjection,
    CLIPTokenizer,
    CLIPVisionConfig,
    CLIPVisionModelWithProjection,
)

from diffusers import KandinskyVaaPriorEmbaEmbPipeline, PriorTransformer, UnCLIPScheduler
from diffusers.utils import floats_tensor, torch_device
from diffusers.utils.testing_utils import enable_full_determinism, skip_mps

from ..test_pipelines_common import PipelineTesterMixin


enable_full_determinism()







class 			UpperCAmelCase			(							SCREAMING_SNAKE_CASE__		,      unittest.TestCase):
 _lowerCamelCase			:       List[Any]            =       KandinskyVaaPriorEmbaEmbPipeline
 _lowerCamelCase			:       Tuple            =       ['prompt', 'image']
 _lowerCamelCase			:       List[str]            =       ['prompt', 'image']
 _lowerCamelCase			:       List[str]            =       [
     'num_images_per_prompt',
     'strength',
     'generator',
     'num_inference_steps',
     'latents',
     'negative_prompt',
     'guidance_scale',
     'output_type',
     'return_dict',
 ]
 _lowerCamelCase			:       List[str]            =       False

 @property
 def 		lowercase_    (			self			:						int       ):





    """simple docstring"""



    return 32

 @property
 def 		lowercase_    (			self			:						Union[str, Any]       ):





    """simple docstring"""



    return 32

 @property
 def 		lowercase_    (			self			:						Any       ):





    """simple docstring"""



    return self.time_input_dim

 @property
 def 		lowercase_    (			self			:						Dict       ):





    """simple docstring"""



    return self.time_input_dim * 4

 @property
 def 		lowercase_    (			self			:						str       ):





    """simple docstring"""



    return 100

 @property
 def 		lowercase_    (			self			:						Any       ):





    """simple docstring"""



    UpperCamelCase__			    =    CLIPTokenizer.from_pretrained("hf-internal-testing/tiny-random-clip"       )
    return tokenizer

 @property
 def 		lowercase_    (			self			:						Optional[int]       ):





    """simple docstring"""



    torch.manual_seed(0       )
    UpperCamelCase__			    =    CLIPTextConfig(
        bos_token_id=0,       eos_token_id=2,       hidden_size=self.text_embedder_hidden_size,       projection_dim=self.text_embedder_hidden_size,       intermediate_size=37,       layer_norm_eps=1e-0_5,       num_attention_heads=4,       num_hidden_layers=5,       pad_token_id=1,       vocab_size=1000,       )
    return CLIPTextModelWithProjection(a_       )

 @property
 def 		lowercase_    (			self			:						str       ):





    """simple docstring"""



    torch.manual_seed(0       )

    UpperCamelCase__			    =    {
        "num_attention_heads": 2,
        "attention_head_dim": 12,
        "embedding_dim": self.text_embedder_hidden_size,
        "num_layers": 1,
    }

    UpperCamelCase__			    =    PriorTransformer(**a_       )
    # clip_std and clip_mean is initialized to be 0 so PriorTransformer.post_process_latents will always return 0 - set clip_std to be 1 so it won't return 0
    UpperCamelCase__			    =    nn.Parameter(torch.ones(model.clip_std.shape       )       )
    return model

 @property
 def 		lowercase_    (			self			:						Any       ):





    """simple docstring"""



    torch.manual_seed(0       )
    UpperCamelCase__			    =    CLIPVisionConfig(
        hidden_size=self.text_embedder_hidden_size,       image_size=224,       projection_dim=self.text_embedder_hidden_size,       intermediate_size=37,       num_attention_heads=4,       num_channels=3,       num_hidden_layers=5,       patch_size=14,       )

    UpperCamelCase__			    =    CLIPVisionModelWithProjection(a_       )
    return model

 @property
 def 		lowercase_    (			self			:						Dict       ):





    """simple docstring"""



    UpperCamelCase__			    =    CLIPImageProcessor(
        crop_size=224,       do_center_crop=a_,       do_normalize=a_,       do_resize=a_,       image_mean=[0.48_145_466, 0.4_578_275, 0.40_821_073],       image_std=[0.26_862_954, 0.26_130_258, 0.27_577_711],       resample=3,       size=224,       )

    return image_processor

 def 		lowercase_    (			self			:						Optional[int]       ):





    """simple docstring"""



    UpperCamelCase__			    =    self.dummy_prior
    UpperCamelCase__			    =    self.dummy_image_encoder
    UpperCamelCase__			    =    self.dummy_text_encoder
    UpperCamelCase__			    =    self.dummy_tokenizer
    UpperCamelCase__			    =    self.dummy_image_processor

    UpperCamelCase__			    =    UnCLIPScheduler(
        variance_type="fixed_small_log",       prediction_type="sample",       num_train_timesteps=1000,       clip_sample=a_,       clip_sample_range=10.0,       )

    UpperCamelCase__			    =    {
        "prior": prior,
        "image_encoder": image_encoder,
        "text_encoder": text_encoder,
        "tokenizer": tokenizer,
        "scheduler": scheduler,
        "image_processor": image_processor,
    }

    return components

 def 		lowercase_    (			self			:						Union[str, Any],       a_			:						List[str],       a_			:						Union[str, Any]=0       ):





    """simple docstring"""



    if str(a_       ).startswith("mps"       ):
       UpperCamelCase__			    =    torch.manual_seed(a_       )
    else:
       UpperCamelCase__			    =    torch.Generator(device=a_       ).manual_seed(a_       )

    UpperCamelCase__			    =    floats_tensor((1, 3, 64, 64),       rng=random.Random(a_       )       ).to(a_       )
    UpperCamelCase__			    =    image.cpu().permute(0,       2,       3,       1       )[0]
    UpperCamelCase__			    =    Image.fromarray(np.uinta(a_       )       ).convert("RGB"       ).resize((256, 256)       )

    UpperCamelCase__			    =    {
        "prompt": "horse",
        "image": init_image,
        "strength": 0.5,
        "generator": generator,
        "guidance_scale": 4.0,
        "num_inference_steps": 2,
        "output_type": "np",
    }
    return inputs

 def 		lowercase_    (			self			:						Union[str, Any]       ):





    """simple docstring"""



    UpperCamelCase__			    =    "cpu"

    UpperCamelCase__			    =    self.get_dummy_components()

    UpperCamelCase__			    =    self.pipeline_class(**a_       )
    UpperCamelCase__			    =    pipe.to(a_       )

    pipe.set_progress_bar_config(disable=a_       )

    UpperCamelCase__			    =    pipe(**self.get_dummy_inputs(a_       )       )
    UpperCamelCase__			    =    output.image_embeds

    UpperCamelCase__			    =    pipe(
        **self.get_dummy_inputs(a_       ),       return_dict=a_,       )[0]

    UpperCamelCase__			    =    image[0, -10:]
    UpperCamelCase__			    =    image_from_tuple[0, -10:]

    assert image.shape == (1, 32)

    UpperCamelCase__			    =    np.array(
        [
            0.1_071_284,
            1.3_330_271,
            0.61_260_223,
            -0.6_691_065,
            -0.3_846_852,
            -1.0_303_661,
            0.22_716_111,
            0.03_348_901,
            0.30_040_675,
            -0.24_805_029,
        ]       )

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

 @skip_mps
 def 		lowercase_    (			self			:						Optional[int]       ):





    """simple docstring"""



    UpperCamelCase__			    =    torch_device == "cpu"
    UpperCamelCase__			    =    True
    UpperCamelCase__			    =    False

    self._test_inference_batch_single_identical(
        test_max_difference=a_,       relax_max_difference=a_,       test_mean_pixel_difference=a_,       )

 @skip_mps
 def 		lowercase_    (			self			:						Optional[int]       ):





    """simple docstring"""



    UpperCamelCase__			    =    torch_device == "cpu"
    UpperCamelCase__			    =    False

    self._test_attention_slicing_forward_pass(
        test_max_difference=a_,       test_mean_pixel_difference=a_,       )