



"""simple docstring"""






from typing import List, Optional, Tuple, Union

import torch
from torch import nn
from torch.nn import CrossEntropyLoss

from ... import AutoBackbone
from ...modeling_outputs import SemanticSegmenterOutput
from ...modeling_utils import PreTrainedModel
from ...utils import add_start_docstrings, add_start_docstrings_to_model_forward, replace_return_docstrings
from ...utils.backbone_utils import BackboneMixin
from .configuration_upernet import UperNetConfig


_lowercase				:				List[str]   		=		[
    "openmmlab/upernet-convnext-tiny",
    # See all UperNet models at https://huggingface.co/models?filter=upernet
]

# General docstring
_lowercase				:				int   		=		"UperNetConfig"

class  __SCREAMING_SNAKE_CASE			(   nn.Module     ):


					'''simple docstring'''





					def __init__( self							:						List[Any],						lowerCamelCase							:						int,						lowerCamelCase							:						int,						lowerCamelCase							:						Union[int, Tuple[int, int]],						lowerCamelCase							:						Union[int, Tuple[int, int], str] = 0,						lowerCamelCase							:						bool = False,						lowerCamelCase							:						Union[int, Tuple[int, int]] = 1,						)->      None:
								super().__init__()
								lowerCamelCase__	:	Tuple				=nn.Convad(
								    in_channels=lowerCamelCase,						out_channels=lowerCamelCase,						kernel_size=lowerCamelCase,						padding=lowerCamelCase,						bias=lowerCamelCase,						dilation=lowerCamelCase,						)
								lowerCamelCase__	:	str				=nn.BatchNormad(lowerCamelCase  )
								lowerCamelCase__	:	Optional[Any]				=nn.ReLU()




					def 	snake_case ( self							:						List[Any],						lowerCamelCase							:						torch.Tensor  )->      torch.Tensor:
								lowerCamelCase__	:	List[Any]				=self.conv(lowerCamelCase  )
								lowerCamelCase__	:	Tuple				=self.batch_norm(lowerCamelCase  )
								lowerCamelCase__	:	Optional[int]				=self.activation(lowerCamelCase  )

								return output





class  __SCREAMING_SNAKE_CASE			(   nn.Module     ):


					'''simple docstring'''





					def __init__( self							:						List[Any],						lowerCamelCase							:						int,						lowerCamelCase							:						int,						lowerCamelCase							:						int  )->      None:
								super().__init__()
								lowerCamelCase__	:	Dict				=[
								    nn.AdaptiveAvgPoolad(lowerCamelCase  ),
								    UperNetConvModule(lowerCamelCase,						lowerCamelCase,						kernel_size=1  ),
								]
								for i, layer in enumerate(self.layers  ):
											self.add_module(str(lowerCamelCase  ),						lowerCamelCase  )




					def 	snake_case ( self							:						str,						lowerCamelCase							:						torch.Tensor  )->      torch.Tensor:
								lowerCamelCase__	:	Tuple				=input
								for layer in self.layers:
											lowerCamelCase__	:	Any				=layer(lowerCamelCase  )
								return hidden_state





class  __SCREAMING_SNAKE_CASE			(   nn.Module     ):


					'''simple docstring'''





					def __init__( self							:						Union[str, Any],						lowerCamelCase							:						Tuple[int, ...],						lowerCamelCase							:						int,						lowerCamelCase							:						int,						lowerCamelCase							:						bool  )->      None:
								super().__init__()
								lowerCamelCase__	:	Dict				=pool_scales
								lowerCamelCase__	:	List[str]				=align_corners
								lowerCamelCase__	:	str				=in_channels
								lowerCamelCase__	:	Optional[Any]				=channels
								lowerCamelCase__	:	Any				=[]
								for i, pool_scale in enumerate(lowerCamelCase  ):
											lowerCamelCase__	:	Any				=UperNetPyramidPoolingBlock(pool_scale=lowerCamelCase,						in_channels=lowerCamelCase,						channels=lowerCamelCase  )
											self.blocks.append(lowerCamelCase  )
											self.add_module(str(lowerCamelCase  ),						lowerCamelCase  )




					def 	snake_case ( self							:						Optional[int],						lowerCamelCase							:						torch.Tensor  )->      List[torch.Tensor]:
								lowerCamelCase__	:	Tuple				=[]
								for ppm in self.blocks:
											lowerCamelCase__	:	Optional[Any]				=ppm(lowerCamelCase  )
											lowerCamelCase__	:	Dict				=nn.functional.interpolate(
											    lowerCamelCase,						size=x.size()[2:],						mode='''bilinear''',						align_corners=self.align_corners  )
											ppm_outs.append(lowerCamelCase  )
								return ppm_outs





class  __SCREAMING_SNAKE_CASE			(   nn.Module     ):


					'''simple docstring'''





					def __init__( self							:						List[Any],						lowerCamelCase							:						Tuple,						lowerCamelCase							:						Any  )->      Dict:
								super().__init__()

								lowerCamelCase__	:	Dict				=config
								lowerCamelCase__	:	Optional[int]				=config.pool_scales  # e.g. (1, 2, 3, 6)
								lowerCamelCase__	:	List[str]				=in_channels
								lowerCamelCase__	:	Tuple				=config.hidden_size
								lowerCamelCase__	:	int				=False
								lowerCamelCase__	:	str				=nn.Convad(self.channels,						config.num_labels,						kernel_size=1  )

								# PSP Module
								lowerCamelCase__	:	Tuple				=UperNetPyramidPoolingModule(
								    self.pool_scales,						self.in_channels[-1],						self.channels,						align_corners=self.align_corners,						)
								lowerCamelCase__	:	List[Any]				=UperNetConvModule(
								    self.in_channels[-1] + len(self.pool_scales  ) * self.channels,						self.channels,						kernel_size=3,						padding=1,						)
								# FPN Module
								lowerCamelCase__	:	Optional[int]				=nn.ModuleList()
								lowerCamelCase__	:	Optional[int]				=nn.ModuleList()
								for in_channels in self.in_channels[:-1]:  # skip the top layer
											lowerCamelCase__	:	Optional[int]				=UperNetConvModule(lowerCamelCase,						self.channels,						kernel_size=1  )
											lowerCamelCase__	:	List[str]				=UperNetConvModule(self.channels,						self.channels,						kernel_size=3,						padding=1  )
											self.lateral_convs.append(lowerCamelCase  )
											self.fpn_convs.append(lowerCamelCase  )

								lowerCamelCase__	:	Optional[Any]				=UperNetConvModule(
								    len(self.in_channels  ) * self.channels,						self.channels,						kernel_size=3,						padding=1,						)



					def 	snake_case ( self							:						Union[str, Any]  )->      Any:
								self.apply(self._init_weights  )



					def 	snake_case ( self							:						str,						lowerCamelCase							:						Dict  )->      Any:
								if isinstance(lowerCamelCase,						nn.Convad  ):
											module.weight.data.normal_(mean=0.0,						std=self.config.initializer_range  )
											if module.bias is not None:
														module.bias.data.zero_()



					def 	snake_case ( self							:						List[str],						lowerCamelCase							:						Union[str, Any]  )->      Any:
								lowerCamelCase__	:	str				=inputs[-1]
								lowerCamelCase__	:	List[Any]				=[x]
								psp_outs.extend(self.psp_modules(lowerCamelCase  )  )
								lowerCamelCase__	:	str				=torch.cat(lowerCamelCase,						dim=1  )
								lowerCamelCase__	:	Union[str, Any]				=self.bottleneck(lowerCamelCase  )

								return output




					def 	snake_case ( self							:						Optional[int],						lowerCamelCase							:						torch.Tensor  )->      torch.Tensor:
								# build laterals
								lowerCamelCase__	:	Optional[Any]				=[lateral_conv(encoder_hidden_states[i]  ) for i, lateral_conv in enumerate(self.lateral_convs  )]

								laterals.append(self.psp_forward(lowerCamelCase  )  )

								# build top-down path
								lowerCamelCase__	:	int				=len(lowerCamelCase  )
								for i in range(used_backbone_levels - 1,						0,						-1  ):
											lowerCamelCase__	:	List[str]				=laterals[i - 1].shape[2:]
											lowerCamelCase__	:	Optional[Any]				=laterals[i - 1] + nn.functional.interpolate(
											    laterals[i],						size=lowerCamelCase,						mode='''bilinear''',						align_corners=self.align_corners  )

								# build outputs
								lowerCamelCase__	:	Any				=[self.fpn_convs[i](laterals[i]  ) for i in range(used_backbone_levels - 1  )]
								# append psp feature
								fpn_outs.append(laterals[-1]  )

								for i in range(used_backbone_levels - 1,						0,						-1  ):
											lowerCamelCase__	:	Optional[int]				=nn.functional.interpolate(
											    fpn_outs[i],						size=fpn_outs[0].shape[2:],						mode='''bilinear''',						align_corners=self.align_corners  )
								lowerCamelCase__	:	Union[str, Any]				=torch.cat(lowerCamelCase,						dim=1  )
								lowerCamelCase__	:	Optional[int]				=self.fpn_bottleneck(lowerCamelCase  )
								lowerCamelCase__	:	Optional[int]				=self.classifier(lowerCamelCase  )

								return output





class  __SCREAMING_SNAKE_CASE			(   nn.Module     ):


					'''simple docstring'''





					def __init__( self							:						Dict,						lowerCamelCase							:						Dict,						lowerCamelCase							:						int = 2,						lowerCamelCase							:						int = 3,						lowerCamelCase							:						Union[int, Tuple[int, int]] = 1  )->      None:
								super().__init__()

								lowerCamelCase__	:	Optional[int]				=config
								lowerCamelCase__	:	Dict				=config.auxiliary_in_channels
								lowerCamelCase__	:	Any				=config.auxiliary_channels
								lowerCamelCase__	:	int				=config.auxiliary_num_convs
								lowerCamelCase__	:	int				=config.auxiliary_concat_input
								lowerCamelCase__	:	List[str]				=in_index

								lowerCamelCase__	:	Optional[Any]				=(kernel_size // 2) * dilation
								lowerCamelCase__	:	List[Any]				=[]
								convs.append(
								    UperNetConvModule(
								        self.in_channels,						self.channels,						kernel_size=lowerCamelCase,						padding=lowerCamelCase,						dilation=lowerCamelCase  )  )
								for i in range(self.num_convs - 1  ):
											convs.append(
											    UperNetConvModule(
											        self.channels,						self.channels,						kernel_size=lowerCamelCase,						padding=lowerCamelCase,						dilation=lowerCamelCase  )  )
								if self.num_convs == 0:
											lowerCamelCase__	:	str				=nn.Identity()
								else:
											lowerCamelCase__	:	Union[str, Any]				=nn.Sequential(*lowerCamelCase  )
								if self.concat_input:
											lowerCamelCase__	:	Any				=UperNetConvModule(
											    self.in_channels + self.channels,						self.channels,						kernel_size=lowerCamelCase,						padding=kernel_size // 2  )

								lowerCamelCase__	:	List[str]				=nn.Convad(self.channels,						config.num_labels,						kernel_size=1  )



					def 	snake_case ( self							:						Any  )->      List[str]:
								self.apply(self._init_weights  )



					def 	snake_case ( self							:						Tuple,						lowerCamelCase							:						Tuple  )->      List[Any]:
								if isinstance(lowerCamelCase,						nn.Convad  ):
											module.weight.data.normal_(mean=0.0,						std=self.config.initializer_range  )
											if module.bias is not None:
														module.bias.data.zero_()




					def 	snake_case ( self							:						List[str],						lowerCamelCase							:						torch.Tensor  )->      torch.Tensor:
								# just take the relevant feature maps
								lowerCamelCase__	:	List[str]				=encoder_hidden_states[self.in_index]
								lowerCamelCase__	:	Tuple				=self.convs(lowerCamelCase  )
								if self.concat_input:
											lowerCamelCase__	:	Optional[Any]				=self.conv_cat(torch.cat([hidden_states, output],						dim=1  )  )
								lowerCamelCase__	:	List[str]				=self.classifier(lowerCamelCase  )
								return output





class  __SCREAMING_SNAKE_CASE			(   lowerCAmelCase_     ):


					'''simple docstring'''





					_a         =							UperNetConfig
					_a         =							'pixel_values'
					_a         =							True



					def 	snake_case ( self							:						Tuple,						lowerCamelCase							:						str  )->      Tuple:
								if isinstance(lowerCamelCase,						lowerCamelCase  ):
											module.backbone.init_weights()
											module.decode_head.init_weights()
											module.auxiliary_head.init_weights()



					def 	snake_case ( self							:						int  )->      Optional[int]:
								self.backbone.init_weights()
								self.decode_head.init_weights()
								self.auxiliary_head.init_weights()




					def 	snake_case ( self							:						Any,						lowerCamelCase							:						Optional[Any],						lowerCamelCase							:						Optional[int]=False  )->      Any:
								if isinstance(lowerCamelCase,						lowerCamelCase  ):
											lowerCamelCase__	:	int				=value





_lowercase				:				int   		=		r"\n    Parameters:\n    This model is a PyTorch [torch.nn.Module](https://pytorch.org/docs/stable/nn.html#torch.nn.Module) sub-class. Use\n    it as a regular PyTorch Module and refer to the PyTorch documentation for all matter related to general usage and\n    behavior.\n        config ([`UperNetConfig`]): Model configuration class with all the parameters of the model.\n            Initializing with a config file does not load the weights associated with the model, only the\n            configuration. Check out the [`~PreTrainedModel.from_pretrained`] method to load the model weights.\n"

_lowercase				:				Dict   		=		r"\n    Args:\n        pixel_values (`torch.FloatTensor` of shape `(batch_size, num_channels, height, width)`):\n            Pixel values. Padding will be ignored by default should you provide it. Pixel values can be obtained using\n            [`AutoImageProcessor`]. See [`SegformerImageProcessor.__call__`] for details.\n        output_attentions (`bool`, *optional*):\n            Whether or not to return the attentions tensors of all attention layers in case the backbone has them. See\n            `attentions` under returned tensors for more detail.\n        output_hidden_states (`bool`, *optional*):\n            Whether or not to return the hidden states of all layers of the backbone. See `hidden_states` under\n            returned tensors for more detail.\n        return_dict (`bool`, *optional*):\n            Whether or not to return a [`~utils.ModelOutput`] instead of a plain tuple.\n"

@add_start_docstrings(
    'UperNet framework leveraging any vision backbone e.g. for ADE20k, CityScapes.'	,     lowerCAmelCase_	,     )
class  __SCREAMING_SNAKE_CASE			(   lowerCAmelCase_     ):


					'''simple docstring'''





					def __init__( self							:						Tuple,						lowerCamelCase							:						List[Any]  )->      int:
								super().__init__(lowerCamelCase  )

								lowerCamelCase__	:	Tuple				=AutoBackbone.from_config(config.backbone_config  )

								# Semantic segmentation head(s)
								lowerCamelCase__	:	Any				=UperNetHead(lowerCamelCase,						in_channels=self.backbone.channels  )
								lowerCamelCase__	:	Union[str, Any]				=UperNetFCNHead(lowerCamelCase  ) if config.use_auxiliary_head else None

								# Initialize weights and apply final processing
								self.post_init()




					@add_start_docstrings_to_model_forward(UPERNET_INPUTS_DOCSTRING.format('''batch_size, sequence_length'''  )  )
					@replace_return_docstrings(output_type=lowerCamelCase,						config_class=_CONFIG_FOR_DOC  )
					def 	snake_case ( self							:						Optional[Any],						lowerCamelCase							:						Optional[torch.Tensor] = None,						lowerCamelCase							:						Optional[bool] = None,						lowerCamelCase							:						Optional[bool] = None,						lowerCamelCase							:						Optional[torch.Tensor] = None,						lowerCamelCase							:						Optional[bool] = None,						)->      Union[tuple, SemanticSegmenterOutput]:
								lowerCamelCase__	:	int				=return_dict if return_dict is not None else self.config.use_return_dict
								lowerCamelCase__	:	Any				=(
								    output_hidden_states if output_hidden_states is not None else self.config.output_hidden_states
								)
								lowerCamelCase__	:	str				=output_attentions if output_attentions is not None else self.config.output_attentions

								lowerCamelCase__	:	int				=self.backbone.forward_with_filtered_kwargs(
								    lowerCamelCase,						output_hidden_states=lowerCamelCase,						output_attentions=lowerCamelCase  )
								lowerCamelCase__	:	List[Any]				=outputs.feature_maps

								lowerCamelCase__	:	Tuple				=self.decode_head(lowerCamelCase  )
								lowerCamelCase__	:	Tuple				=nn.functional.interpolate(lowerCamelCase,						size=pixel_values.shape[2:],						mode='''bilinear''',						align_corners=lowerCamelCase  )

								lowerCamelCase__	:	int				=None
								if self.auxiliary_head is not None:
											lowerCamelCase__	:	int				=self.auxiliary_head(lowerCamelCase  )
											lowerCamelCase__	:	Any				=nn.functional.interpolate(
											    lowerCamelCase,						size=pixel_values.shape[2:],						mode='''bilinear''',						align_corners=lowerCamelCase  )

								lowerCamelCase__	:	str				=None
								if labels is not None:
											if self.config.num_labels == 1:
														raise ValueError('''The number of labels should be greater than one'''  )
											else:
														# compute weighted loss
														lowerCamelCase__	:	Union[str, Any]				=CrossEntropyLoss(ignore_index=self.config.loss_ignore_index  )
														lowerCamelCase__	:	Union[str, Any]				=loss_fct(lowerCamelCase,						lowerCamelCase  )
														lowerCamelCase__	:	Dict				=loss_fct(lowerCamelCase,						lowerCamelCase  )
														lowerCamelCase__	:	Dict				=main_loss + self.config.auxiliary_loss_weight * auxiliary_loss

								if not return_dict:
											if output_hidden_states:
														lowerCamelCase__	:	Optional[Any]				=(logits,) + outputs[1:]
											else:
														lowerCamelCase__	:	Tuple				=(logits,) + outputs[2:]
											return ((loss,) + output) if loss is not None else output

								return SemanticSegmenterOutput(
								    loss=lowerCamelCase,						logits=lowerCamelCase,						hidden_states=outputs.hidden_states,						attentions=outputs.attentions,						)









"""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  )




