
'''simple docstring'''







import copy
import os
from typing import Union

from ...configuration_utils import PretrainedConfig
from ...utils import logging


__lowerCAmelCase         =    logging.get_logger(__name__)

__lowerCAmelCase         =    {
    """Salesforce/blip-vqa-base""": """https://huggingface.co/Salesforce/blip-vqa-base/resolve/main/config.json""",
    """Salesforce/blip-vqa-capfit-large""": (
        """https://huggingface.co/Salesforce/blip-vqa-base-capfit/resolve/main/config.json"""
    ),
    """Salesforce/blip-image-captioning-base""": (
        """https://huggingface.co/Salesforce/blip-image-captioning-base/resolve/main/config.json"""
    ),
    """Salesforce/blip-image-captioning-large""": (
        """https://huggingface.co/Salesforce/blip-image-captioning-large/resolve/main/config.json"""
    ),
    """Salesforce/blip-itm-base-coco""": """https://huggingface.co/Salesforce/blip-itm-base-coco/resolve/main/config.json""",
    """Salesforce/blip-itm-large-coco""": """https://huggingface.co/Salesforce/blip-itm-large-coco/resolve/main/config.json""",
    """Salesforce/blip-itm-base-flikr""": """https://huggingface.co/Salesforce/blip-itm-base-flikr/resolve/main/config.json""",
    """Salesforce/blip-itm-large-flikr""": (
        """https://huggingface.co/Salesforce/blip-itm-large-flikr/resolve/main/config.json"""
    ),
}







class UpperCAmelCase__	( lowercase__	):





  """simple docstring"""

  __UpperCAmelCase				:				Any   =					'''blip_text_model'''


  def __init__(		self      :     Any							,_a      :     List[Any]=3_0524							,_a      :     Optional[Any]=768							,_a      :     Dict=768							,_a      :     Optional[int]=3072							,_a      :     str=768							,_a      :     Union[str, Any]=12							,_a      :     List[str]=8							,_a      :     str=512							,_a      :     List[Any]="gelu"							,_a      :     Any=1E-12							,_a      :     Tuple=0.0							,_a      :     Union[str, Any]=0.0							,_a      :     Tuple=0.02							,_a      :     Union[str, Any]=3_0522							,_a      :     str=2							,_a      :     List[str]=0							,_a      :     Tuple=102							,_a      :     List[Any]=True							,_a      :     Any=True							,**_a      :     List[Any]							,):


     '''simple docstring'''






     super().__init__(
         pad_token_id=_a							,bos_token_id=_a							,eos_token_id=_a							,sep_token_id=_a							,**_a							,)

     _a				:	Any			=   vocab_size
     _a				:	str			=   hidden_size
     _a				:	Any			=   encoder_hidden_size
     _a				:	Optional[int]			=   intermediate_size
     _a				:	Any			=   projection_dim
     _a				:	Any			=   hidden_dropout_prob
     _a				:	Union[str, Any]			=   num_hidden_layers
     _a				:	List[str]			=   num_attention_heads
     _a				:	int			=   max_position_embeddings
     _a				:	Dict			=   layer_norm_eps
     _a				:	Tuple			=   hidden_act
     _a				:	Tuple			=   initializer_range
     _a				:	List[str]			=   attention_probs_dropout_prob
     _a				:	str			=   is_decoder
     _a				:	Tuple			=   use_cache


  @classmethod
  def   __lowercase		(		cls      :     int							,_a      :     Union[str, os.PathLike]							,**_a      :     Tuple       ):


     '''simple docstring'''






     cls._set_token_in_kwargs(_a       )

     _a,  _a				:	Any			=   cls.get_config_dict(_a							,**_a       )

     # get the text config dict if we are loading from BlipConfig
     if config_dict.get('model_type'       ) == "blip":
        _a				:	Tuple			=   config_dict['text_config']

     if "model_type" in config_dict and hasattr(cls							,'model_type'       ) and config_dict["model_type"] != cls.model_type:
        logger.warning(
            F"""You are using a model of type {config_dict['model_type']} to instantiate a model of type """
            F"""{cls.model_type}. This is not supported for all configurations of models and can yield errors."""       )

     return cls.from_dict(_a							,**_a       )







class UpperCAmelCase__	( lowercase__	):





  """simple docstring"""

  __UpperCAmelCase				:				List[Any]   =					'''blip_vision_model'''


  def __init__(		self      :     Tuple							,_a      :     List[Any]=768							,_a      :     List[str]=3072							,_a      :     Union[str, Any]=512							,_a      :     Any=12							,_a      :     Tuple=12							,_a      :     Any=384							,_a      :     Tuple=16							,_a      :     Any="gelu"							,_a      :     Dict=1E-5							,_a      :     int=0.0							,_a      :     Union[str, Any]=1E-10							,**_a      :     List[Any]							,):


     '''simple docstring'''






     super().__init__(**_a       )

     _a				:	Tuple			=   hidden_size
     _a				:	str			=   intermediate_size
     _a				:	Tuple			=   projection_dim
     _a				:	Union[str, Any]			=   num_hidden_layers
     _a				:	Optional[Any]			=   num_attention_heads
     _a				:	int			=   patch_size
     _a				:	List[Any]			=   image_size
     _a				:	int			=   initializer_range
     _a				:	str			=   attention_dropout
     _a				:	Union[str, Any]			=   layer_norm_eps
     _a				:	List[str]			=   hidden_act


  @classmethod
  def   __lowercase		(		cls      :     Tuple							,_a      :     Union[str, os.PathLike]							,**_a      :     int       ):


     '''simple docstring'''






     cls._set_token_in_kwargs(_a       )

     _a,  _a				:	List[str]			=   cls.get_config_dict(_a							,**_a       )

     # get the vision config dict if we are loading from BlipConfig
     if config_dict.get('model_type'       ) == "blip":
        _a				:	List[Any]			=   config_dict['vision_config']

     if "model_type" in config_dict and hasattr(cls							,'model_type'       ) and config_dict["model_type"] != cls.model_type:
        logger.warning(
            F"""You are using a model of type {config_dict['model_type']} to instantiate a model of type """
            F"""{cls.model_type}. This is not supported for all configurations of models and can yield errors."""       )

     return cls.from_dict(_a							,**_a       )







class UpperCAmelCase__	( lowercase__	):





  """simple docstring"""

  __UpperCAmelCase				:				List[Any]   =					'''blip'''
  __UpperCAmelCase				:				Dict   =					True


  def __init__(		self      :     Dict							,_a      :     Optional[Any]=None							,_a      :     List[str]=None							,_a      :     Any=512							,_a      :     Optional[Any]=2.6592							,_a      :     Optional[int]=256							,**_a      :     Optional[int]							,):


     '''simple docstring'''






     super().__init__(**_a       )

     if text_config is None:
        _a				:	Dict			=   {}
        logger.info('`text_config` is `None`. Initializing the `BlipTextConfig` with default values.'       )

     if vision_config is None:
        _a				:	Any			=   {}
        logger.info('`vision_config` is `None`. Initializing the `BlipVisionConfig` with default values.'       )

     _a				:	Union[str, Any]			=   BlipTextConfig(**_a       )
     _a				:	Union[str, Any]			=   BlipVisionConfig(**_a       )

     _a				:	int			=   self.vision_config.hidden_size

     _a				:	Tuple			=   projection_dim
     _a				:	int			=   logit_scale_init_value
     _a				:	List[Any]			=   1.0
     _a				:	Any			=   0.02
     _a				:	Optional[int]			=   image_text_hidden_size


  @classmethod
  def   __lowercase		(		cls      :     str							,_a      :     BlipTextConfig							,_a      :     BlipVisionConfig							,**_a      :     Optional[int]       ):


     '''simple docstring'''






     return cls(text_config=text_config.to_dict()							,vision_config=vision_config.to_dict()							,**_a       )


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


     '''simple docstring'''






     _a				:	Dict			=   copy.deepcopy(self.__dict__       )
     _a				:	int			=   self.text_config.to_dict()
     _a				:	Tuple			=   self.vision_config.to_dict()
     _a				:	int			=   self.__class__.model_type
     return output





'''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 UpperCAmelCase__	( unittest.TestCase	):





  """simple docstring"""

  @property
  def   __lowercase		(		self      :     List[str]       ):


     '''simple docstring'''






     torch.manual_seed(0       )
     _a				:	int			=   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   __lowercase		(		self      :     Optional[Any]       ):


     '''simple docstring'''






     _a				:	str			=   self.dummy_uncond_unet
     _a				:	int			=   PNDMScheduler()

     _a				:	str			=   PNDMPipeline(unet=_a							,scheduler=_a       )
     pndm.to(_a       )
     pndm.set_progress_bar_config(disable=_a       )

     _a				:	Optional[int]			=   torch.manual_seed(0       )
     _a				:	Optional[Any]			=   pndm(generator=_a							,num_inference_steps=20							,output_type='numpy'       ).images

     _a				:	List[str]			=   torch.manual_seed(0       )
     _a				:	Any			=   pndm(generator=_a							,num_inference_steps=20							,output_type='numpy'							,return_dict=_a       )[0]

     _a				:	List[Any]			=   image[0, -3:, -3:, -1]
     _a				:	Any			=   image_from_tuple[0, -3:, -3:, -1]

     assert image.shape == (1, 32, 32, 3)
     _a				:	List[Any]			=   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 UpperCAmelCase__	( unittest.TestCase	):





  """simple docstring"""

  def   __lowercase		(		self      :     Tuple       ):


     '''simple docstring'''






     _a				:	List[str]			=   'google/ddpm-cifar10-32'

     _a				:	str			=   UNetaDModel.from_pretrained(_a       )
     _a				:	Union[str, Any]			=   PNDMScheduler()

     _a				:	Tuple			=   PNDMPipeline(unet=_a							,scheduler=_a       )
     pndm.to(_a       )
     pndm.set_progress_bar_config(disable=_a       )
     _a				:	str			=   torch.manual_seed(0       )
     _a				:	Optional[Any]			=   pndm(generator=_a							,output_type='numpy'       ).images

     _a				:	Dict			=   image[0, -3:, -3:, -1]

     assert image.shape == (1, 32, 32, 3)
     _a				:	Tuple			=   np.array([0.1564, 0.1_4645, 0.1406, 0.1_4715, 0.1_2425, 0.1_4045, 0.1_3115, 0.1_2175, 0.125]       )

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



