
"""simple docstring"""







from typing import Optional, Tuple, Union

import flax
import flax.linen as nn
import jax
import jax.numpy as jnp
from flax.core.frozen_dict import FrozenDict

from ..configuration_utils import ConfigMixin, flax_register_to_config
from ..utils import BaseOutput
from .embeddings_flax import FlaxTimestepEmbedding, FlaxTimesteps
from .modeling_flax_utils import FlaxModelMixin
from .unet_ad_blocks_flax import (
    FlaxCrossAttnDownBlockaD,
    FlaxCrossAttnUpBlockaD,
    FlaxDownBlockaD,
    FlaxUNetMidBlockaDCrossAttn,
    FlaxUpBlockaD,
)




@flax.struct.dataclass
class  A__       (	_lowerCamelCase):
		A_						:       jnp.ndarray




@flax_register_to_config
class  A__       (	nn.Module       ,     _lowerCamelCase       ,     _lowerCamelCase):
		A_						:       int				   =	3_2
		A_						:       int				   =	4
		A_						:       int				   =	4
		A_						:       Tuple[str]				   =	(
		    "CrossAttnDownBlock2D",
		    "CrossAttnDownBlock2D",
		    "CrossAttnDownBlock2D",
		    "DownBlock2D",
		)
		A_						:       Tuple[str]				   =	("UpBlock2D", "CrossAttnUpBlock2D", "CrossAttnUpBlock2D", "CrossAttnUpBlock2D")
		A_						:       Union[bool, Tuple[bool]]				   =	False
		A_						:       Tuple[int]				   =	(3_2_0, 6_4_0, 1_2_8_0, 1_2_8_0)
		A_						:       int				   =	2
		A_						:       Union[int, Tuple[int]]				   =	8
		A_						:       Optional[Union[int, Tuple[int]]]				   =	None
		A_						:       int				   =	1_2_8_0
		A_						:       float				   =	0.0
		A_						:       bool				   =	False
		A_						:       jnp.dtype				   =	jnp.floataa
		A_						:       bool				   =	True
		A_						:       int				   =	0
		A_						:       bool				   =	False

		def 							__lowerCamelCase							(      self       ,		_SCREAMING_SNAKE_CASE ):
			# init input tensors
			__lowerCAmelCase			:						Optional[Any]									=      (1, self.in_channels, self.sample_size, self.sample_size)
			__lowerCAmelCase			:						int									=      jnp.zeros(_SCREAMING_SNAKE_CASE       ,		dtype=jnp.floataa )
			__lowerCAmelCase			:						str									=      jnp.ones((1,)       ,		dtype=jnp.intaa )
			__lowerCAmelCase			:						Any									=      jnp.zeros((1, 1, self.cross_attention_dim)       ,		dtype=jnp.floataa )

			__lowerCAmelCase			,   __lowerCAmelCase			:						List[str]									=      jax.random.split(_SCREAMING_SNAKE_CASE )
			__lowerCAmelCase			:						Dict									=      {'params': params_rng, 'dropout': dropout_rng}

			return self.init(_SCREAMING_SNAKE_CASE       ,		_SCREAMING_SNAKE_CASE       ,		_SCREAMING_SNAKE_CASE       ,		_SCREAMING_SNAKE_CASE )["params"]

		def 							__lowerCamelCase							(      self ):
			__lowerCAmelCase			:						Optional[int]									=      self.block_out_channels
			__lowerCAmelCase			:						List[str]									=      block_out_channels[0] * 4

			if self.num_attention_heads is not None:
				raise ValueError(
				    'At the moment it is not possible to define the number of attention heads via `num_attention_heads` because of a naming issue as described in https://github.com/huggingface/diffusers/issues/2011#issuecomment-1547958131. Passing `num_attention_heads` will only be supported in diffusers v0.19.' )

			# If `num_attention_heads` is not defined (which is the case for most models)
			# it will default to `attention_head_dim`. This looks weird upon first reading it and it is.
			# The reason for this behavior is to correct for incorrectly named variables that were introduced
			# when this library was created. The incorrect naming was only discovered much later in https://github.com/huggingface/diffusers/issues/2011#issuecomment-1547958131
			# Changing `attention_head_dim` to `num_attention_heads` for 40,000+ configurations is too backwards breaking
			# which is why we correct for the naming here.
			__lowerCAmelCase			:						Dict									=      self.num_attention_heads or self.attention_head_dim

			# input
			__lowerCAmelCase			:						Union[str, Any]									=      nn.Conv(
			    block_out_channels[0]       ,		kernel_size=(3, 3)       ,		strides=(1, 1)       ,		padding=((1, 1), (1, 1))       ,		dtype=self.dtype       ,		)

			# time
			__lowerCAmelCase			:						Union[str, Any]									=      FlaxTimesteps(
			    block_out_channels[0]       ,		flip_sin_to_cos=self.flip_sin_to_cos       ,		freq_shift=self.config.freq_shift )
			__lowerCAmelCase			:						Optional[int]									=      FlaxTimestepEmbedding(_SCREAMING_SNAKE_CASE       ,		dtype=self.dtype )

			__lowerCAmelCase			:						Optional[Any]									=      self.only_cross_attention
			if isinstance(_SCREAMING_SNAKE_CASE       ,		_SCREAMING_SNAKE_CASE ):
				__lowerCAmelCase			:						Union[str, Any]									=      (only_cross_attention,) * len(self.down_block_types )

			if isinstance(_SCREAMING_SNAKE_CASE       ,		_SCREAMING_SNAKE_CASE ):
				__lowerCAmelCase			:						Tuple									=      (num_attention_heads,) * len(self.down_block_types )

			# down
			__lowerCAmelCase			:						str									=      []
			__lowerCAmelCase			:						Optional[int]									=      block_out_channels[0]
			for i, down_block_type in enumerate(self.down_block_types ):
				__lowerCAmelCase			:						Optional[Any]									=      output_channel
				__lowerCAmelCase			:						Dict									=      block_out_channels[i]
				__lowerCAmelCase			:						Optional[int]									=      i == len(_SCREAMING_SNAKE_CASE ) - 1

				if down_block_type == "CrossAttnDownBlock2D":
					__lowerCAmelCase			:						Any									=      FlaxCrossAttnDownBlockaD(
					    in_channels=_SCREAMING_SNAKE_CASE       ,		out_channels=_SCREAMING_SNAKE_CASE       ,		dropout=self.dropout       ,		num_layers=self.layers_per_block       ,		num_attention_heads=num_attention_heads[i]       ,		add_downsample=not is_final_block       ,		use_linear_projection=self.use_linear_projection       ,		only_cross_attention=only_cross_attention[i]       ,		use_memory_efficient_attention=self.use_memory_efficient_attention       ,		dtype=self.dtype       ,		)
				else:
					__lowerCAmelCase			:						List[Any]									=      FlaxDownBlockaD(
					    in_channels=_SCREAMING_SNAKE_CASE       ,		out_channels=_SCREAMING_SNAKE_CASE       ,		dropout=self.dropout       ,		num_layers=self.layers_per_block       ,		add_downsample=not is_final_block       ,		dtype=self.dtype       ,		)

				down_blocks.append(_SCREAMING_SNAKE_CASE )
			__lowerCAmelCase			:						Optional[Any]									=      down_blocks

			# mid
			__lowerCAmelCase			:						List[str]									=      FlaxUNetMidBlockaDCrossAttn(
			    in_channels=block_out_channels[-1]       ,		dropout=self.dropout       ,		num_attention_heads=num_attention_heads[-1]       ,		use_linear_projection=self.use_linear_projection       ,		use_memory_efficient_attention=self.use_memory_efficient_attention       ,		dtype=self.dtype       ,		)

			# up
			__lowerCAmelCase			:						Union[str, Any]									=      []
			__lowerCAmelCase			:						int									=      list(reversed(_SCREAMING_SNAKE_CASE ) )
			__lowerCAmelCase			:						Dict									=      list(reversed(_SCREAMING_SNAKE_CASE ) )
			__lowerCAmelCase			:						Any									=      list(reversed(_SCREAMING_SNAKE_CASE ) )
			__lowerCAmelCase			:						Optional[int]									=      reversed_block_out_channels[0]
			for i, up_block_type in enumerate(self.up_block_types ):
				__lowerCAmelCase			:						Optional[int]									=      output_channel
				__lowerCAmelCase			:						Any									=      reversed_block_out_channels[i]
				__lowerCAmelCase			:						Optional[Any]									=      reversed_block_out_channels[min(i + 1       ,		len(_SCREAMING_SNAKE_CASE ) - 1 )]

				__lowerCAmelCase			:						Optional[int]									=      i == len(_SCREAMING_SNAKE_CASE ) - 1

				if up_block_type == "CrossAttnUpBlock2D":
					__lowerCAmelCase			:						Union[str, Any]									=      FlaxCrossAttnUpBlockaD(
					    in_channels=_SCREAMING_SNAKE_CASE       ,		out_channels=_SCREAMING_SNAKE_CASE       ,		prev_output_channel=_SCREAMING_SNAKE_CASE       ,		num_layers=self.layers_per_block + 1       ,		num_attention_heads=reversed_num_attention_heads[i]       ,		add_upsample=not is_final_block       ,		dropout=self.dropout       ,		use_linear_projection=self.use_linear_projection       ,		only_cross_attention=only_cross_attention[i]       ,		use_memory_efficient_attention=self.use_memory_efficient_attention       ,		dtype=self.dtype       ,		)
				else:
					__lowerCAmelCase			:						Tuple									=      FlaxUpBlockaD(
					    in_channels=_SCREAMING_SNAKE_CASE       ,		out_channels=_SCREAMING_SNAKE_CASE       ,		prev_output_channel=_SCREAMING_SNAKE_CASE       ,		num_layers=self.layers_per_block + 1       ,		add_upsample=not is_final_block       ,		dropout=self.dropout       ,		dtype=self.dtype       ,		)

				up_blocks.append(_SCREAMING_SNAKE_CASE )
				__lowerCAmelCase			:						str									=      output_channel
			__lowerCAmelCase			:						int									=      up_blocks

			# out
			__lowerCAmelCase			:						Tuple									=      nn.GroupNorm(num_groups=32       ,		epsilon=1E-5 )
			__lowerCAmelCase			:						Optional[Any]									=      nn.Conv(
			    self.out_channels       ,		kernel_size=(3, 3)       ,		strides=(1, 1)       ,		padding=((1, 1), (1, 1))       ,		dtype=self.dtype       ,		)







		def __call__(      self       ,		_SCREAMING_SNAKE_CASE       ,		_SCREAMING_SNAKE_CASE       ,		_SCREAMING_SNAKE_CASE       ,		_SCREAMING_SNAKE_CASE=None       ,		_SCREAMING_SNAKE_CASE=None       ,		_SCREAMING_SNAKE_CASE = True       ,		_SCREAMING_SNAKE_CASE = False       ,		):
			# 1. time
			if not isinstance(_SCREAMING_SNAKE_CASE       ,		jnp.ndarray ):
				__lowerCAmelCase			:						Optional[Any]									=      jnp.array([timesteps]       ,		dtype=jnp.intaa )
			elif isinstance(_SCREAMING_SNAKE_CASE       ,		jnp.ndarray ) and len(timesteps.shape ) == 0:
				__lowerCAmelCase			:						Optional[int]									=      timesteps.astype(dtype=jnp.floataa )
				__lowerCAmelCase			:						List[str]									=      jnp.expand_dims(_SCREAMING_SNAKE_CASE       ,		0 )

			__lowerCAmelCase			:						Dict									=      self.time_proj(_SCREAMING_SNAKE_CASE )
			__lowerCAmelCase			:						Union[str, Any]									=      self.time_embedding(_SCREAMING_SNAKE_CASE )

			# 2. pre-process
			__lowerCAmelCase			:						Union[str, Any]									=      jnp.transpose(_SCREAMING_SNAKE_CASE       ,		(0, 2, 3, 1) )
			__lowerCAmelCase			:						Union[str, Any]									=      self.conv_in(_SCREAMING_SNAKE_CASE )

			# 3. down
			__lowerCAmelCase			:						str									=      (sample,)
			for down_block in self.down_blocks:
				if isinstance(_SCREAMING_SNAKE_CASE       ,		_SCREAMING_SNAKE_CASE ):
					__lowerCAmelCase			,   __lowerCAmelCase			:						Optional[int]									=      down_block(_SCREAMING_SNAKE_CASE       ,		_SCREAMING_SNAKE_CASE       ,		_SCREAMING_SNAKE_CASE       ,		deterministic=not train )
				else:
					__lowerCAmelCase			,   __lowerCAmelCase			:						Tuple									=      down_block(_SCREAMING_SNAKE_CASE       ,		_SCREAMING_SNAKE_CASE       ,		deterministic=not train )
				down_block_res_samples += res_samples

			if down_block_additional_residuals is not None:
				__lowerCAmelCase			:						str									=      ()

				for down_block_res_sample, down_block_additional_residual in zip(
				    _SCREAMING_SNAKE_CASE       ,		_SCREAMING_SNAKE_CASE ):
					down_block_res_sample += down_block_additional_residual
					new_down_block_res_samples += (down_block_res_sample,)

				__lowerCAmelCase			:						Any									=      new_down_block_res_samples

			# 4. mid
			__lowerCAmelCase			:						Union[str, Any]									=      self.mid_block(_SCREAMING_SNAKE_CASE       ,		_SCREAMING_SNAKE_CASE       ,		_SCREAMING_SNAKE_CASE       ,		deterministic=not train )

			if mid_block_additional_residual is not None:
				sample += mid_block_additional_residual

			# 5. up
			for up_block in self.up_blocks:
				__lowerCAmelCase			:						Dict									=      down_block_res_samples[-(self.layers_per_block + 1) :]
				__lowerCAmelCase			:						str									=      down_block_res_samples[: -(self.layers_per_block + 1)]
				if isinstance(_SCREAMING_SNAKE_CASE       ,		_SCREAMING_SNAKE_CASE ):
					__lowerCAmelCase			:						int									=      up_block(
					    _SCREAMING_SNAKE_CASE       ,		temb=_SCREAMING_SNAKE_CASE       ,		encoder_hidden_states=_SCREAMING_SNAKE_CASE       ,		res_hidden_states_tuple=_SCREAMING_SNAKE_CASE       ,		deterministic=not train       ,		)
				else:
					__lowerCAmelCase			:						Dict									=      up_block(_SCREAMING_SNAKE_CASE       ,		temb=_SCREAMING_SNAKE_CASE       ,		res_hidden_states_tuple=_SCREAMING_SNAKE_CASE       ,		deterministic=not train )

        # 6. post-process
			__lowerCAmelCase			:						str									=      self.conv_norm_out(_SCREAMING_SNAKE_CASE )
			__lowerCAmelCase			:						List[Any]									=      nn.silu(_SCREAMING_SNAKE_CASE )
			__lowerCAmelCase			:						Tuple									=      self.conv_out(_SCREAMING_SNAKE_CASE )
			__lowerCAmelCase			:						int									=      jnp.transpose(_SCREAMING_SNAKE_CASE       ,		(0, 3, 1, 2) )

			if not return_dict:
				return (sample,)

			return FlaxUNetaDConditionOutput(sample=_SCREAMING_SNAKE_CASE )

"""simple docstring"""





import copy
import os
from typing import Union

from ...configuration_utils import PretrainedConfig
from ...models.auto.modeling_auto import MODEL_FOR_CAUSAL_LM_MAPPING_NAMES
from ...utils import logging
from ..auto import CONFIG_MAPPING


__magic_name__       =			logging.get_logger(__name__)

__magic_name__       =			{
    "salesforce/blip2-opt-2.7b": "https://huggingface.co/salesforce/blip2-opt-2.7b/resolve/main/config.json",
}
class 						SCREAMING_SNAKE_CASE_ (						__a ):




		"""simple docstring"""





		__lowercase							:  Optional[Any]						   =		'''blip_2_vision_model'''




		def __init__(     self							,  lowerCAmelCase__=1_4_0_8							,  lowerCAmelCase__=6_1_4_4							,  lowerCAmelCase__=3_9							,  lowerCAmelCase__=1_6							,  lowerCAmelCase__=2_2_4							,  lowerCAmelCase__=1_4							,  lowerCAmelCase__="gelu"							,  lowerCAmelCase__=0.0_00_01							,  lowerCAmelCase__=0.0							,  lowerCAmelCase__=1E-10							,  lowerCAmelCase__=True							,  **lowerCAmelCase__							,  ):
				super().__init__(**lowerCAmelCase__)

				__SCREAMING_SNAKE_CASE            = hidden_size
				__SCREAMING_SNAKE_CASE            = intermediate_size
				__SCREAMING_SNAKE_CASE            = num_hidden_layers
				__SCREAMING_SNAKE_CASE            = num_attention_heads
				__SCREAMING_SNAKE_CASE            = patch_size
				__SCREAMING_SNAKE_CASE            = image_size
				__SCREAMING_SNAKE_CASE            = initializer_range
				__SCREAMING_SNAKE_CASE            = attention_dropout
				__SCREAMING_SNAKE_CASE            = layer_norm_eps
				__SCREAMING_SNAKE_CASE            = hidden_act
				__SCREAMING_SNAKE_CASE            = qkv_bias




		@classmethod
		def 	snake_case_     (     cls							,  lowerCAmelCase__							,  **lowerCAmelCase__):
				cls._set_token_in_kwargs(lowerCAmelCase__)

				__SCREAMING_SNAKE_CASE       ,__SCREAMING_SNAKE_CASE            = cls.get_config_dict(lowerCAmelCase__							,  **lowerCAmelCase__)

				# get the vision config dict if we are loading from Blip2Config
				if config_dict.get("""model_type""") == "blip-2":
						__SCREAMING_SNAKE_CASE            = 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(lowerCAmelCase__							,  **lowerCAmelCase__)



class 						SCREAMING_SNAKE_CASE_ (						__a ):




		"""simple docstring"""





		__lowercase							:  Tuple						   =		'''blip_2_qformer'''




		def __init__(     self							,  lowerCAmelCase__=3_0_5_2_2							,  lowerCAmelCase__=7_6_8							,  lowerCAmelCase__=1_2							,  lowerCAmelCase__=1_2							,  lowerCAmelCase__=3_0_7_2							,  lowerCAmelCase__="gelu"							,  lowerCAmelCase__=0.1							,  lowerCAmelCase__=0.1							,  lowerCAmelCase__=5_1_2							,  lowerCAmelCase__=0.02							,  lowerCAmelCase__=1E-12							,  lowerCAmelCase__=0							,  lowerCAmelCase__="absolute"							,  lowerCAmelCase__=2							,  lowerCAmelCase__=1_4_0_8							,  **lowerCAmelCase__							,  ):
				super().__init__(pad_token_id=lowerCAmelCase__							,  **lowerCAmelCase__)

				__SCREAMING_SNAKE_CASE            = vocab_size
				__SCREAMING_SNAKE_CASE            = hidden_size
				__SCREAMING_SNAKE_CASE            = num_hidden_layers
				__SCREAMING_SNAKE_CASE            = num_attention_heads
				__SCREAMING_SNAKE_CASE            = hidden_act
				__SCREAMING_SNAKE_CASE            = intermediate_size
				__SCREAMING_SNAKE_CASE            = hidden_dropout_prob
				__SCREAMING_SNAKE_CASE            = attention_probs_dropout_prob
				__SCREAMING_SNAKE_CASE            = max_position_embeddings
				__SCREAMING_SNAKE_CASE            = initializer_range
				__SCREAMING_SNAKE_CASE            = layer_norm_eps
				__SCREAMING_SNAKE_CASE            = position_embedding_type
				__SCREAMING_SNAKE_CASE            = cross_attention_frequency
				__SCREAMING_SNAKE_CASE            = encoder_hidden_size




		@classmethod
		def 	snake_case_     (     cls							,  lowerCAmelCase__							,  **lowerCAmelCase__):
				cls._set_token_in_kwargs(lowerCAmelCase__)

				__SCREAMING_SNAKE_CASE       ,__SCREAMING_SNAKE_CASE            = cls.get_config_dict(lowerCAmelCase__							,  **lowerCAmelCase__)

				# get the qformer config dict if we are loading from Blip2Config
				if config_dict.get("""model_type""") == "blip-2":
						__SCREAMING_SNAKE_CASE            = config_dict["""qformer_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(lowerCAmelCase__							,  **lowerCAmelCase__)



class 						SCREAMING_SNAKE_CASE_ (						__a ):




		"""simple docstring"""





		__lowercase							:  Optional[Any]						   =		'''blip-2'''
		__lowercase							:  Any						   =		True




		def __init__(     self							,  lowerCAmelCase__=None							,  lowerCAmelCase__=None							,  lowerCAmelCase__=None							,  lowerCAmelCase__=3_2							,  **lowerCAmelCase__):
				super().__init__(**lowerCAmelCase__)

				if vision_config is None:
						__SCREAMING_SNAKE_CASE            = {}
						logger.info("""vision_config is None. initializing the Blip2VisionConfig with default values.""")

				if qformer_config is None:
						__SCREAMING_SNAKE_CASE            = {}
						logger.info("""qformer_config is None. Initializing the Blip2QFormerConfig with default values.""")

				if text_config is None:
						__SCREAMING_SNAKE_CASE            = {}
						logger.info("""text_config is None. Initializing the text config with default values (`OPTConfig`).""")

				__SCREAMING_SNAKE_CASE            = BlipaVisionConfig(**lowerCAmelCase__)
				__SCREAMING_SNAKE_CASE            = BlipaQFormerConfig(**lowerCAmelCase__)
				__SCREAMING_SNAKE_CASE            = text_config["""model_type"""] if """model_type""" in text_config else """opt"""
				__SCREAMING_SNAKE_CASE            = CONFIG_MAPPING[text_model_type](**lowerCAmelCase__)

				__SCREAMING_SNAKE_CASE            = self.text_config.tie_word_embeddings
				__SCREAMING_SNAKE_CASE            = self.text_config.is_encoder_decoder

				__SCREAMING_SNAKE_CASE            = num_query_tokens
				__SCREAMING_SNAKE_CASE            = self.vision_config.hidden_size
				__SCREAMING_SNAKE_CASE            = self.text_config.model_type in MODEL_FOR_CAUSAL_LM_MAPPING_NAMES
				__SCREAMING_SNAKE_CASE            = 1.0
				__SCREAMING_SNAKE_CASE            = 0.02




		@classmethod
		def 	snake_case_     (     cls							,  lowerCAmelCase__							,  lowerCAmelCase__							,  lowerCAmelCase__							,  **lowerCAmelCase__							,  ):
				return cls(
				    vision_config=vision_config.to_dict()							,  qformer_config=qformer_config.to_dict()							,  text_config=text_config.to_dict()							,  **lowerCAmelCase__							,  )




		def 	snake_case_     (     self):
				__SCREAMING_SNAKE_CASE            = copy.deepcopy(self.__dict__)
				__SCREAMING_SNAKE_CASE            = self.vision_config.to_dict()
				__SCREAMING_SNAKE_CASE            = self.qformer_config.to_dict()
				__SCREAMING_SNAKE_CASE            = self.text_config.to_dict()
				__SCREAMING_SNAKE_CASE            = self.__class__.model_type
				return output




