



"""simple docstring"""






import copy

from ...configuration_utils import PretrainedConfig
from ...utils import logging
from ..auto import CONFIG_MAPPING


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

_lowercase				:				List[str]   		=		{
    "ut/deta": "https://huggingface.co/ut/deta/resolve/main/config.json",
}

class  __SCREAMING_SNAKE_CASE			(   lowerCAmelCase_     ):


					'''simple docstring'''





					_a         =							'deta'
					_a         =							{
					    'hidden_size': 'd_model',
					    'num_attention_heads': 'encoder_attention_heads',
					}



					def __init__( self							:						Dict,						lowerCamelCase							:						Optional[Any]=None,						lowerCamelCase							:						int=900,						lowerCamelCase							:						Dict=2048,						lowerCamelCase							:						Optional[Any]=6,						lowerCamelCase							:						Any=2048,						lowerCamelCase							:						Tuple=8,						lowerCamelCase							:						Optional[int]=6,						lowerCamelCase							:						Union[str, Any]=1024,						lowerCamelCase							:						str=8,						lowerCamelCase							:						int=0.0,						lowerCamelCase							:						Union[str, Any]=True,						lowerCamelCase							:						Tuple="relu",						lowerCamelCase							:						Optional[Any]=256,						lowerCamelCase							:						Union[str, Any]=0.1,						lowerCamelCase							:						Union[str, Any]=0.0,						lowerCamelCase							:						Optional[Any]=0.0,						lowerCamelCase							:						Union[str, Any]=0.02,						lowerCamelCase							:						List[str]=1.0,						lowerCamelCase							:						Dict=True,						lowerCamelCase							:						str=False,						lowerCamelCase							:						Any="sine",						lowerCamelCase							:						str=5,						lowerCamelCase							:						str=4,						lowerCamelCase							:						Dict=4,						lowerCamelCase							:						Dict=True,						lowerCamelCase							:						Dict=300,						lowerCamelCase							:						List[str]=True,						lowerCamelCase							:						Optional[Any]=True,						lowerCamelCase							:						Optional[Any]=1,						lowerCamelCase							:						Optional[int]=5,						lowerCamelCase							:						Optional[int]=2,						lowerCamelCase							:						Any=1,						lowerCamelCase							:						Tuple=1,						lowerCamelCase							:						Tuple=5,						lowerCamelCase							:						Union[str, Any]=2,						lowerCamelCase							:						Optional[int]=0.1,						lowerCamelCase							:						List[Any]=0.25,						**lowerCamelCase							:						int,						)->      int:
								if backbone_config is None:
											logger.info('''`backbone_config` is `None`. Initializing the config with the default `ResNet` backbone.'''  )
											lowerCamelCase__	:	Optional[int]				=CONFIG_MAPPING['''resnet'''](out_features=['''stage2''', '''stage3''', '''stage4''']  )
								else:
											if isinstance(lowerCamelCase,						lowerCamelCase  ):
														lowerCamelCase__	:	int				=backbone_config.pop('''model_type'''  )
														lowerCamelCase__	:	List[Any]				=CONFIG_MAPPING[backbone_model_type]
														lowerCamelCase__	:	Optional[Any]				=config_class.from_dict(lowerCamelCase  )

								lowerCamelCase__	:	Tuple				=backbone_config
								lowerCamelCase__	:	List[Any]				=num_queries
								lowerCamelCase__	:	Optional[Any]				=max_position_embeddings
								lowerCamelCase__	:	Union[str, Any]				=d_model
								lowerCamelCase__	:	Tuple				=encoder_ffn_dim
								lowerCamelCase__	:	List[Any]				=encoder_layers
								lowerCamelCase__	:	Union[str, Any]				=encoder_attention_heads
								lowerCamelCase__	:	List[str]				=decoder_ffn_dim
								lowerCamelCase__	:	Tuple				=decoder_layers
								lowerCamelCase__	:	str				=decoder_attention_heads
								lowerCamelCase__	:	Any				=dropout
								lowerCamelCase__	:	str				=attention_dropout
								lowerCamelCase__	:	List[Any]				=activation_dropout
								lowerCamelCase__	:	Any				=activation_function
								lowerCamelCase__	:	Any				=init_std
								lowerCamelCase__	:	int				=init_xavier_std
								lowerCamelCase__	:	Optional[int]				=encoder_layerdrop
								lowerCamelCase__	:	Dict				=auxiliary_loss
								lowerCamelCase__	:	Any				=position_embedding_type
								# deformable attributes
								lowerCamelCase__	:	Dict				=num_feature_levels
								lowerCamelCase__	:	Dict				=encoder_n_points
								lowerCamelCase__	:	List[str]				=decoder_n_points
								lowerCamelCase__	:	Optional[int]				=two_stage
								lowerCamelCase__	:	Optional[Any]				=two_stage_num_proposals
								lowerCamelCase__	:	str				=with_box_refine
								lowerCamelCase__	:	Tuple				=assign_first_stage
								if two_stage is True and with_box_refine is False:
											raise ValueError('''If two_stage is True, with_box_refine must be True.'''  )
								# Hungarian matcher
								lowerCamelCase__	:	Any				=class_cost
								lowerCamelCase__	:	Union[str, Any]				=bbox_cost
								lowerCamelCase__	:	Union[str, Any]				=giou_cost
								# Loss coefficients
								lowerCamelCase__	:	Tuple				=mask_loss_coefficient
								lowerCamelCase__	:	Optional[Any]				=dice_loss_coefficient
								lowerCamelCase__	:	Union[str, Any]				=bbox_loss_coefficient
								lowerCamelCase__	:	Tuple				=giou_loss_coefficient
								lowerCamelCase__	:	Optional[Any]				=eos_coefficient
								lowerCamelCase__	:	Dict				=focal_alpha
								super().__init__(is_encoder_decoder=lowerCamelCase,						**lowerCamelCase  )



					@property
					def 	snake_case ( self							:						Optional[int]  )->      int:
								return self.encoder_attention_heads



					@property
					def 	snake_case ( self							:						Any  )->      int:
								return self.d_model




					def 	snake_case ( self							:						Tuple  )->      Dict:
								lowerCamelCase__	:	Union[str, Any]				=copy.deepcopy(self.__dict__  )
								lowerCamelCase__	:	Dict				=self.backbone_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  )




