



"""simple docstring"""






import copy
import os
from typing import Union

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


_lowercase				:				List[Any]   		=		logging.get_logger(__name__)

_lowercase				:				str   		=		{
    "BridgeTower/bridgetower-base": "https://huggingface.co/BridgeTower/bridgetower-base/blob/main/config.json",
    "BridgeTower/bridgetower-base-itm-mlm": (
        "https://huggingface.co/BridgeTower/bridgetower-base-itm-mlm/blob/main/config.json"
    ),
}

class  __SCREAMING_SNAKE_CASE			(   lowerCAmelCase_     ):


					'''simple docstring'''





					_a         =							'bridgetower_vision_model'



					def __init__( self							:						int,						lowerCamelCase							:						str=768,						lowerCamelCase							:						Union[str, Any]=12,						lowerCamelCase							:						List[Any]=3,						lowerCamelCase							:						Tuple=16,						lowerCamelCase							:						Tuple=288,						lowerCamelCase							:						str=1,						lowerCamelCase							:						Optional[Any]=1E-05,						lowerCamelCase							:						Any=False,						lowerCamelCase							:						Any=True,						lowerCamelCase							:						List[Any]=False,						**lowerCamelCase							:						List[Any],						)->      Dict:
								super().__init__(**lowerCamelCase  )
								lowerCamelCase__	:	Tuple				=hidden_size
								lowerCamelCase__	:	Optional[Any]				=num_hidden_layers
								lowerCamelCase__	:	Optional[Any]				=num_channels
								lowerCamelCase__	:	Tuple				=patch_size
								lowerCamelCase__	:	Dict				=image_size
								lowerCamelCase__	:	Optional[int]				=initializer_factor
								lowerCamelCase__	:	Optional[Any]				=layer_norm_eps
								lowerCamelCase__	:	List[Any]				=stop_gradient
								lowerCamelCase__	:	Any				=share_layernorm
								lowerCamelCase__	:	Optional[int]				=remove_last_layer




					@classmethod
					def 	snake_case ( cls							:						Dict,						lowerCamelCase							:						Union[str, os.PathLike],						**lowerCamelCase							:						Union[str, Any]  )->      "PretrainedConfig":
								lowerCamelCase__			,     lowerCamelCase__	:	int				=cls.get_config_dict(lowerCamelCase,						**lowerCamelCase  )

								if config_dict.get('''model_type'''  ) == "bridgetower":
											lowerCamelCase__	:	Optional[Any]				=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(lowerCamelCase,						**lowerCamelCase  )





class  __SCREAMING_SNAKE_CASE			(   lowerCAmelCase_     ):


					'''simple docstring'''





					_a         =							'bridgetower_text_model'



					def __init__( self							:						List[str],						lowerCamelCase							:						Union[str, Any]=5_0265,						lowerCamelCase							:						Dict=768,						lowerCamelCase							:						Any=12,						lowerCamelCase							:						Any=12,						lowerCamelCase							:						Optional[int]=1,						lowerCamelCase							:						int=3072,						lowerCamelCase							:						Optional[int]="gelu",						lowerCamelCase							:						Union[str, Any]=0.1,						lowerCamelCase							:						List[str]=0.1,						lowerCamelCase							:						Dict=514,						lowerCamelCase							:						Tuple=1,						lowerCamelCase							:						Union[str, Any]=1E-05,						lowerCamelCase							:						Dict=1,						lowerCamelCase							:						Optional[int]=0,						lowerCamelCase							:						str=2,						lowerCamelCase							:						Any="absolute",						lowerCamelCase							:						List[str]=True,						**lowerCamelCase							:						Optional[Any],						)->      str:
								super().__init__(**lowerCamelCase  )

								lowerCamelCase__	:	Optional[int]				=vocab_size
								lowerCamelCase__	:	List[str]				=hidden_size
								lowerCamelCase__	:	Any				=num_hidden_layers
								lowerCamelCase__	:	Tuple				=num_attention_heads
								lowerCamelCase__	:	List[str]				=hidden_act
								lowerCamelCase__	:	Any				=initializer_factor
								lowerCamelCase__	:	int				=intermediate_size
								lowerCamelCase__	:	Tuple				=hidden_dropout_prob
								lowerCamelCase__	:	int				=attention_probs_dropout_prob
								lowerCamelCase__	:	Optional[Any]				=max_position_embeddings
								lowerCamelCase__	:	Optional[Any]				=type_vocab_size
								lowerCamelCase__	:	Union[str, Any]				=layer_norm_eps
								lowerCamelCase__	:	List[Any]				=position_embedding_type
								lowerCamelCase__	:	Union[str, Any]				=use_cache
								lowerCamelCase__	:	List[str]				=pad_token_id
								lowerCamelCase__	:	int				=bos_token_id
								lowerCamelCase__	:	Optional[Any]				=eos_token_id




					@classmethod
					def 	snake_case ( cls							:						int,						lowerCamelCase							:						Union[str, os.PathLike],						**lowerCamelCase							:						int  )->      "PretrainedConfig":
								lowerCamelCase__			,     lowerCamelCase__	:	int				=cls.get_config_dict(lowerCamelCase,						**lowerCamelCase  )

								if config_dict.get('''model_type'''  ) == "bridgetower":
											lowerCamelCase__	:	Any				=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(lowerCamelCase,						**lowerCamelCase  )





class  __SCREAMING_SNAKE_CASE			(   lowerCAmelCase_     ):


					'''simple docstring'''





					_a         =							'bridgetower'



					def __init__( self							:						str,						lowerCamelCase							:						str=True,						lowerCamelCase							:						str="gelu",						lowerCamelCase							:						Tuple=768,						lowerCamelCase							:						Dict=1,						lowerCamelCase							:						Any=1E-05,						lowerCamelCase							:						List[Any]=False,						lowerCamelCase							:						List[Any]="add",						lowerCamelCase							:						Any=12,						lowerCamelCase							:						int=6,						lowerCamelCase							:						Any=False,						lowerCamelCase							:						Union[str, Any]=False,						lowerCamelCase							:						Optional[int]=None,						lowerCamelCase							:						int=None,						**lowerCamelCase							:						List[str],						)->      Union[str, Any]:
								# TODO: remove this once the Hub files are updated.
								lowerCamelCase__	:	Any				=kwargs.pop('''text_config_dict''',						lowerCamelCase  )
								lowerCamelCase__	:	Optional[Any]				=kwargs.pop('''vision_config_dict''',						lowerCamelCase  )

								super().__init__(**lowerCamelCase  )
								lowerCamelCase__	:	List[Any]				=share_cross_modal_transformer_layers
								lowerCamelCase__	:	Optional[int]				=hidden_act
								lowerCamelCase__	:	Optional[Any]				=hidden_size
								lowerCamelCase__	:	Optional[Any]				=initializer_factor
								lowerCamelCase__	:	Tuple				=layer_norm_eps
								lowerCamelCase__	:	Tuple				=share_link_tower_layers
								lowerCamelCase__	:	Optional[int]				=link_tower_type
								lowerCamelCase__	:	Dict				=num_attention_heads
								lowerCamelCase__	:	List[Any]				=num_hidden_layers
								lowerCamelCase__	:	List[str]				=tie_word_embeddings
								lowerCamelCase__	:	Optional[Any]				=init_layernorm_from_vision_encoder

								if text_config is None:
											lowerCamelCase__	:	str				={}
											logger.info('''`text_config` is `None`. Initializing the `BridgeTowerTextConfig` with default values.'''  )

								if vision_config is None:
											lowerCamelCase__	:	Tuple				={}
											logger.info('''`vision_config` is `None`. Initializing the `BridgeTowerVisionConfig` with default values.'''  )

								lowerCamelCase__	:	int				=BridgeTowerTextConfig(**lowerCamelCase  )
								lowerCamelCase__	:	int				=BridgeTowerVisionConfig(**lowerCamelCase  )



					@classmethod
					def 	snake_case ( cls							:						Optional[int],						lowerCamelCase							:						BridgeTowerTextConfig,						lowerCamelCase							:						BridgeTowerVisionConfig,						**lowerCamelCase							:						Dict  )->      Optional[Any]:
								return cls(text_config=text_config.to_dict(),						vision_config=vision_config.to_dict(),						**lowerCamelCase  )




					def 	snake_case ( self							:						Union[str, Any]  )->      Optional[int]:
								lowerCamelCase__	:	Any				=copy.deepcopy(self.__dict__  )
								lowerCamelCase__	:	int				=self.text_config.to_dict()
								lowerCamelCase__	:	List[str]				=self.vision_config.to_dict()
								lowerCamelCase__	:	Optional[int]				=self.__class__.model_type
								return output









"""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,
    FlaxDownBlockaD,
    FlaxUNetMidBlockaDCrossAttn,
)

@flax.struct.dataclass
class  __SCREAMING_SNAKE_CASE			(   lowerCAmelCase_     ):


					'''simple docstring'''





					_a         =							42
					_a         =							42





class  __SCREAMING_SNAKE_CASE			(   nn.Module     ):


					'''simple docstring'''





					_a         =							42
					_a         =							(1_6, 3_2, 9_6, 2_5_6)
					_a         =							jnp.floataa



					def 	snake_case ( self							:						Tuple  )->      int:
								lowerCamelCase__	:	Tuple				=nn.Conv(
								    self.block_out_channels[0],						kernel_size=(3, 3),						padding=((1, 1), (1, 1)),						dtype=self.dtype,						)

								lowerCamelCase__	:	Dict				=[]
								for i in range(len(self.block_out_channels  ) - 1  ):
											lowerCamelCase__	:	Dict				=self.block_out_channels[i]
											lowerCamelCase__	:	Dict				=self.block_out_channels[i + 1]
											lowerCamelCase__	:	List[str]				=nn.Conv(
											    lowerCamelCase,						kernel_size=(3, 3),						padding=((1, 1), (1, 1)),						dtype=self.dtype,						)
											blocks.append(lowerCamelCase  )
											lowerCamelCase__	:	Optional[int]				=nn.Conv(
											    lowerCamelCase,						kernel_size=(3, 3),						strides=(2, 2),						padding=((1, 1), (1, 1)),						dtype=self.dtype,						)
											blocks.append(lowerCamelCase  )
								lowerCamelCase__	:	Any				=blocks

								lowerCamelCase__	:	Optional[int]				=nn.Conv(
								    self.conditioning_embedding_channels,						kernel_size=(3, 3),						padding=((1, 1), (1, 1)),						kernel_init=nn.initializers.zeros_init(),						bias_init=nn.initializers.zeros_init(),						dtype=self.dtype,						)




					def __call__( self							:						Any,						lowerCamelCase							:						int  )->      List[str]:
								lowerCamelCase__	:	Tuple				=self.conv_in(lowerCamelCase  )
								lowerCamelCase__	:	Dict				=nn.silu(lowerCamelCase  )

								for block in self.blocks:
											lowerCamelCase__	:	str				=block(lowerCamelCase  )
											lowerCamelCase__	:	List[str]				=nn.silu(lowerCamelCase  )

								lowerCamelCase__	:	Any				=self.conv_out(lowerCamelCase  )

								return embedding





@flax_register_to_config
class  __SCREAMING_SNAKE_CASE			(   nn.Module	,     lowerCAmelCase_	,     lowerCAmelCase_     ):


					'''simple docstring'''





					_a         =							3_2
					_a         =							4
					_a         =							(
					    "CrossAttnDownBlock2D",
					    "CrossAttnDownBlock2D",
					    "CrossAttnDownBlock2D",
					    "DownBlock2D",
					)
					_a         =							False
					_a         =							(3_2_0, 6_4_0, 1_2_8_0, 1_2_8_0)
					_a         =							2
					_a         =							8
					_a         =							None
					_a         =							1_2_8_0
					_a         =							0.0
					_a         =							False
					_a         =							jnp.floataa
					_a         =							True
					_a         =							0
					_a         =							"rgb"
					_a         =							(1_6, 3_2, 9_6, 2_5_6)



					def 	snake_case ( self							:						str,						lowerCamelCase							:						jax.random.KeyArray  )->      FrozenDict:
								# init input tensors
								lowerCamelCase__	:	int				=(1, self.in_channels, self.sample_size, self.sample_size)
								lowerCamelCase__	:	int				=jnp.zeros(lowerCamelCase,						dtype=jnp.floataa  )
								lowerCamelCase__	:	Union[str, Any]				=jnp.ones((1,),						dtype=jnp.intaa  )
								lowerCamelCase__	:	str				=jnp.zeros((1, 1, self.cross_attention_dim),						dtype=jnp.floataa  )
								lowerCamelCase__	:	Any				=(1, 3, self.sample_size * 8, self.sample_size * 8)
								lowerCamelCase__	:	Optional[Any]				=jnp.zeros(lowerCamelCase,						dtype=jnp.floataa  )

								lowerCamelCase__			,     lowerCamelCase__	:	List[Any]				=jax.random.split(lowerCamelCase  )
								lowerCamelCase__	:	Dict				={'''params''': params_rng, '''dropout''': dropout_rng}

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



					def 	snake_case ( self							:						Any  )->      Tuple:
								lowerCamelCase__	:	Optional[int]				=self.block_out_channels
								lowerCamelCase__	:	Tuple				=block_out_channels[0] * 4

								# 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__	:	List[Any]				=self.num_attention_heads or self.attention_head_dim

								# input
								lowerCamelCase__	:	int				=nn.Conv(
								    block_out_channels[0],						kernel_size=(3, 3),						strides=(1, 1),						padding=((1, 1), (1, 1)),						dtype=self.dtype,						)

								# time
								lowerCamelCase__	:	str				=FlaxTimesteps(
								    block_out_channels[0],						flip_sin_to_cos=self.flip_sin_to_cos,						freq_shift=self.config.freq_shift  )
								lowerCamelCase__	:	Dict				=FlaxTimestepEmbedding(lowerCamelCase,						dtype=self.dtype  )

								lowerCamelCase__	:	List[Any]				=FlaxControlNetConditioningEmbedding(
								    conditioning_embedding_channels=block_out_channels[0],						block_out_channels=self.conditioning_embedding_out_channels,						)

								lowerCamelCase__	:	Dict				=self.only_cross_attention
								if isinstance(lowerCamelCase,						lowerCamelCase  ):
											lowerCamelCase__	:	int				=(only_cross_attention,) * len(self.down_block_types  )

								if isinstance(lowerCamelCase,						lowerCamelCase  ):
											lowerCamelCase__	:	List[str]				=(num_attention_heads,) * len(self.down_block_types  )

								# down
								lowerCamelCase__	:	Union[str, Any]				=[]
								lowerCamelCase__	:	Dict				=[]

								lowerCamelCase__	:	List[Any]				=block_out_channels[0]

								lowerCamelCase__	:	List[Any]				=nn.Conv(
								    lowerCamelCase,						kernel_size=(1, 1),						padding='''VALID''',						kernel_init=nn.initializers.zeros_init(),						bias_init=nn.initializers.zeros_init(),						dtype=self.dtype,						)
								controlnet_down_blocks.append(lowerCamelCase  )

								for i, down_block_type in enumerate(self.down_block_types  ):
											lowerCamelCase__	:	List[Any]				=output_channel
											lowerCamelCase__	:	str				=block_out_channels[i]
											lowerCamelCase__	:	Dict				=i == len(lowerCamelCase  ) - 1

											if down_block_type == "CrossAttnDownBlock2D":
														lowerCamelCase__	:	str				=FlaxCrossAttnDownBlockaD(
														    in_channels=lowerCamelCase,						out_channels=lowerCamelCase,						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],						dtype=self.dtype,						)
											else:
														lowerCamelCase__	:	List[Any]				=FlaxDownBlockaD(
														    in_channels=lowerCamelCase,						out_channels=lowerCamelCase,						dropout=self.dropout,						num_layers=self.layers_per_block,						add_downsample=not is_final_block,						dtype=self.dtype,						)

											down_blocks.append(lowerCamelCase  )

											for _ in range(self.layers_per_block  ):
														lowerCamelCase__	:	Any				=nn.Conv(
														    lowerCamelCase,						kernel_size=(1, 1),						padding='''VALID''',						kernel_init=nn.initializers.zeros_init(),						bias_init=nn.initializers.zeros_init(),						dtype=self.dtype,						)
														controlnet_down_blocks.append(lowerCamelCase  )

											if not is_final_block:
														lowerCamelCase__	:	Any				=nn.Conv(
														    lowerCamelCase,						kernel_size=(1, 1),						padding='''VALID''',						kernel_init=nn.initializers.zeros_init(),						bias_init=nn.initializers.zeros_init(),						dtype=self.dtype,						)
														controlnet_down_blocks.append(lowerCamelCase  )

								lowerCamelCase__	:	int				=down_blocks
								lowerCamelCase__	:	List[str]				=controlnet_down_blocks

								# mid
								lowerCamelCase__	:	Tuple				=block_out_channels[-1]
								lowerCamelCase__	:	List[Any]				=FlaxUNetMidBlockaDCrossAttn(
								    in_channels=lowerCamelCase,						dropout=self.dropout,						num_attention_heads=num_attention_heads[-1],						use_linear_projection=self.use_linear_projection,						dtype=self.dtype,						)

								lowerCamelCase__	:	List[str]				=nn.Conv(
								    lowerCamelCase,						kernel_size=(1, 1),						padding='''VALID''',						kernel_init=nn.initializers.zeros_init(),						bias_init=nn.initializers.zeros_init(),						dtype=self.dtype,						)




					def __call__( self							:						int,						lowerCamelCase							:						List[Any],						lowerCamelCase							:						Tuple,						lowerCamelCase							:						Union[str, Any],						lowerCamelCase							:						str,						lowerCamelCase							:						float = 1.0,						lowerCamelCase							:						bool = True,						lowerCamelCase							:						bool = False,						)->      Union[FlaxControlNetOutput, Tuple]:
								lowerCamelCase__	:	int				=self.controlnet_conditioning_channel_order
								if channel_order == "bgr":
											lowerCamelCase__	:	int				=jnp.flip(lowerCamelCase,						axis=1  )

								# 1. time
								if not isinstance(lowerCamelCase,						jnp.ndarray  ):
											lowerCamelCase__	:	Any				=jnp.array([timesteps],						dtype=jnp.intaa  )
								elif isinstance(lowerCamelCase,						jnp.ndarray  ) and len(timesteps.shape  ) == 0:
											lowerCamelCase__	:	List[str]				=timesteps.astype(dtype=jnp.floataa  )
											lowerCamelCase__	:	int				=jnp.expand_dims(lowerCamelCase,						0  )

								lowerCamelCase__	:	Optional[Any]				=self.time_proj(lowerCamelCase  )
								lowerCamelCase__	:	Optional[Any]				=self.time_embedding(lowerCamelCase  )

								# 2. pre-process
								lowerCamelCase__	:	Optional[int]				=jnp.transpose(lowerCamelCase,						(0, 2, 3, 1)  )
								lowerCamelCase__	:	Dict				=self.conv_in(lowerCamelCase  )

								lowerCamelCase__	:	List[str]				=jnp.transpose(lowerCamelCase,						(0, 2, 3, 1)  )
								lowerCamelCase__	:	int				=self.controlnet_cond_embedding(lowerCamelCase  )
								sample += controlnet_cond

								# 3. down
								lowerCamelCase__	:	Union[str, Any]				=(sample,)
								for down_block in self.down_blocks:
											if isinstance(lowerCamelCase,						lowerCamelCase  ):
														lowerCamelCase__			,     lowerCamelCase__	:	Dict				=down_block(lowerCamelCase,						lowerCamelCase,						lowerCamelCase,						deterministic=not train  )
											else:
														lowerCamelCase__			,     lowerCamelCase__	:	Tuple				=down_block(lowerCamelCase,						lowerCamelCase,						deterministic=not train  )
											down_block_res_samples += res_samples

								# 4. mid
								lowerCamelCase__	:	Optional[int]				=self.mid_block(lowerCamelCase,						lowerCamelCase,						lowerCamelCase,						deterministic=not train  )

								# 5. contronet blocks
								lowerCamelCase__	:	Optional[Any]				=()
								for down_block_res_sample, controlnet_block in zip(lowerCamelCase,						self.controlnet_down_blocks  ):
											lowerCamelCase__	:	Union[str, Any]				=controlnet_block(lowerCamelCase  )
											controlnet_down_block_res_samples += (down_block_res_sample,)

								lowerCamelCase__	:	List[str]				=controlnet_down_block_res_samples

								lowerCamelCase__	:	List[str]				=self.controlnet_mid_block(lowerCamelCase  )

								# 6. scaling
								lowerCamelCase__	:	Union[str, Any]				=[sample * conditioning_scale for sample in down_block_res_samples]
								mid_block_res_sample *= conditioning_scale

								if not return_dict:
											return (down_block_res_samples, mid_block_res_sample)

								return FlaxControlNetOutput(
								    down_block_res_samples=lowerCamelCase,						mid_block_res_sample=lowerCamelCase  )




