




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       a__	( UpperCamelCase__				):
     a		:      jnp.ndarray
     a		:      jnp.ndarray







class       a__	( nn.Module				):
     a		:      int
     a		:      Tuple[int]		 =     (16, 32, 96, 256)
     a		:      jnp.dtype		 =     jnp.floataa







     def       lowerCAmelCase_    (     self			)  ->   List[Any]:



          '''simple docstring'''



          a     =				nn.Conv(
              self.block_out_channels[0]  ,		kernel_size=(3, 3)  ,		padding=((1, 1), (1, 1))  ,		dtype=self.dtype  ,		)

          a     =				[]
          for i in range(len(self.block_out_channels			) - 1			):
               a     =				self.block_out_channels[i]
               a     =				self.block_out_channels[i + 1]
               a     =				nn.Conv(
                   A  ,		kernel_size=(3, 3)  ,		padding=((1, 1), (1, 1))  ,		dtype=self.dtype  ,		)
               blocks.append(A			)
               a     =				nn.Conv(
                   A  ,		kernel_size=(3, 3)  ,		strides=(2, 2)  ,		padding=((1, 1), (1, 1))  ,		dtype=self.dtype  ,		)
               blocks.append(A			)
          a     =				blocks

          a     =				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  ,		A			)  ->   Optional[Any]:



          '''simple docstring'''



          a     =				self.conv_in(A			)
          a     =				nn.silu(A			)

          for block in self.blocks:
               a     =				block(A			)
               a     =				nn.silu(A			)

          a     =				self.conv_out(A			)

          return embedding







@flax_register_to_config
class       a__	( nn.Module       , UpperCamelCase__       , UpperCamelCase__				):
     a		:      int		 =     32
     a		:      int		 =     4
     a		:      Tuple[str]		 =     (
         "CrossAttnDownBlock2D",
         "CrossAttnDownBlock2D",
         "CrossAttnDownBlock2D",
         "DownBlock2D",
     )
     a		:      Union[bool, Tuple[bool]]		 =     False
     a		:      Tuple[int]		 =     (320, 640, 1280, 1280)
     a		:      int		 =     2
     a		:      Union[int, Tuple[int]]		 =     8
     a		:      Optional[Union[int, Tuple[int]]]		 =     None
     a		:      int		 =     1280
     a		:      float		 =     0.0
     a		:      bool		 =     False
     a		:      jnp.dtype		 =     jnp.floataa
     a		:      bool		 =     True
     a		:      int		 =     0
     a		:      str		 =     "rgb"
     a		:      Tuple[int]		 =     (16, 32, 96, 256)







     def       lowerCAmelCase_    (     self  ,		A			)  ->   FrozenDict:



          '''simple docstring'''



          a     =				(1, self.in_channels, self.sample_size, self.sample_size)
          a     =				jnp.zeros(A  ,		dtype=jnp.floataa			)
          a     =				jnp.ones((1,)  ,		dtype=jnp.intaa			)
          a     =				jnp.zeros((1, 1, self.cross_attention_dim)  ,		dtype=jnp.floataa			)
          a     =				(1, 3, self.sample_size * 8, self.sample_size * 8)
          a     =				jnp.zeros(A  ,		dtype=jnp.floataa			)

          a  ,				a     =				jax.random.split(A			)
          a     =				{"params": params_rng, "dropout": dropout_rng}

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







     def       lowerCAmelCase_    (     self			)  ->   int:



          '''simple docstring'''



          a     =				self.block_out_channels
          a     =				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.
          a     =				self.num_attention_heads or self.attention_head_dim

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

          # time
          a     =				FlaxTimesteps(
              block_out_channels[0]  ,		flip_sin_to_cos=self.flip_sin_to_cos  ,		freq_shift=self.config.freq_shift			)
          a     =				FlaxTimestepEmbedding(A  ,		dtype=self.dtype			)

          a     =				FlaxControlNetConditioningEmbedding(
              conditioning_embedding_channels=block_out_channels[0]  ,		block_out_channels=self.conditioning_embedding_out_channels  ,		)

          a     =				self.only_cross_attention
          if isinstance(A  ,		A			):
               a     =				(only_cross_attention,) * len(self.down_block_types			)

          if isinstance(A  ,		A			):
               a     =				(num_attention_heads,) * len(self.down_block_types			)

          # down
          a     =				[]
          a     =				[]

          a     =				block_out_channels[0]

          a     =				nn.Conv(
              A  ,		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(A			)

          for i, down_block_type in enumerate(self.down_block_types			):
               a     =				output_channel
               a     =				block_out_channels[i]
               a     =				i == len(A			) - 1

               if down_block_type == "CrossAttnDownBlock2D":
                    a     =				FlaxCrossAttnDownBlockaD(
                        in_channels=A  ,		out_channels=A  ,		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:
                    a     =				FlaxDownBlockaD(
                        in_channels=A  ,		out_channels=A  ,		dropout=self.dropout  ,		num_layers=self.layers_per_block  ,		add_downsample=not is_final_block  ,		dtype=self.dtype  ,		)

               down_blocks.append(A			)

               for _ in range(self.layers_per_block			):
                    a     =				nn.Conv(
                        A  ,		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(A			)

               if not is_final_block:
                    a     =				nn.Conv(
                        A  ,		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(A			)

          a     =				down_blocks
          a     =				controlnet_down_blocks

          # mid
          a     =				block_out_channels[-1]
          a     =				FlaxUNetMidBlockaDCrossAttn(
              in_channels=A  ,		dropout=self.dropout  ,		num_attention_heads=num_attention_heads[-1]  ,		use_linear_projection=self.use_linear_projection  ,		dtype=self.dtype  ,		)

          a     =				nn.Conv(
              A  ,		kernel_size=(1, 1)  ,		padding="VALID"  ,		kernel_init=nn.initializers.zeros_init()  ,		bias_init=nn.initializers.zeros_init()  ,		dtype=self.dtype  ,		)







     def __call__(     self  ,		A  ,		A  ,		A  ,		A  ,		A = 1.0  ,		A = True  ,		A = False  ,		)  ->   Union[FlaxControlNetOutput, Tuple]:



          '''simple docstring'''



          a     =				self.controlnet_conditioning_channel_order
          if channel_order == "bgr":
               a     =				jnp.flip(A  ,		axis=1			)

          # 1. time
          if not isinstance(A  ,		jnp.ndarray			):
               a     =				jnp.array([timesteps]  ,		dtype=jnp.intaa			)
          elif isinstance(A  ,		jnp.ndarray			) and len(timesteps.shape			) == 0:
               a     =				timesteps.astype(dtype=jnp.floataa			)
               a     =				jnp.expand_dims(A  ,		0			)

          a     =				self.time_proj(A			)
          a     =				self.time_embedding(A			)

          # 2. pre-process
          a     =				jnp.transpose(A  ,		(0, 2, 3, 1)			)
          a     =				self.conv_in(A			)

          a     =				jnp.transpose(A  ,		(0, 2, 3, 1)			)
          a     =				self.controlnet_cond_embedding(A			)
          sample += controlnet_cond

          # 3. down
          a     =				(sample,)
          for down_block in self.down_blocks:
               if isinstance(A  ,		A			):
                    a  ,				a     =				down_block(A  ,		A  ,		A  ,		deterministic=not train			)
               else:
                    a  ,				a     =				down_block(A  ,		A  ,		deterministic=not train			)
               down_block_res_samples += res_samples

          # 4. mid
          a     =				self.mid_block(A  ,		A  ,		A  ,		deterministic=not train			)

          # 5. contronet blocks
          a     =				()
          for down_block_res_sample, controlnet_block in zip(A  ,		self.controlnet_down_blocks			):
               a     =				controlnet_block(A			)
               controlnet_down_block_res_samples += (down_block_res_sample,)

          a     =				controlnet_down_block_res_samples

          a     =				self.controlnet_mid_block(A			)

          # 6. scaling
          a     =				[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=A  ,		mid_block_res_sample=A			)







from collections import OrderedDict
from typing import Mapping

from packaging import version

from ...configuration_utils import PretrainedConfig
from ...onnx import OnnxConfig
from ...utils import logging
from ...utils.backbone_utils import BackboneConfigMixin, get_aligned_output_features_output_indices


lowercase__				:      Tuple	   = logging.get_logger(__name__)

lowercase__				:      int	   = {
    "microsoft/resnet-50": "https://huggingface.co/microsoft/resnet-50/blob/main/config.json",
}




class       a__	( UpperCamelCase__       , UpperCamelCase__				):
     a		:      Any		 =     """resnet"""
     a		:      Tuple		 =     ["""basic""", """bottleneck"""]







     def __init__(     self  ,		A=3  ,		A=64  ,		A=[256, 512, 1024, 2048]  ,		A=[3, 4, 6, 3]  ,		A="bottleneck"  ,		A="relu"  ,		A=False  ,		A=None  ,		A=None  ,		**A  ,		)  ->   Any:



          '''simple docstring'''



          super().__init__(**A			)
          if layer_type not in self.layer_types:
               raise ValueError(F'''layer_type={layer_type} is not one of {",".join(self.layer_types			)}'''			)
          a     =				num_channels
          a     =				embedding_size
          a     =				hidden_sizes
          a     =				depths
          a     =				layer_type
          a     =				hidden_act
          a     =				downsample_in_first_stage
          a     =				["stem"] + [F'''stage{idx}''' for idx in range(1  ,		len(A			) + 1			)]
          a  ,				a     =				get_aligned_output_features_output_indices(
              out_features=A  ,		out_indices=A  ,		stage_names=self.stage_names			)







class       a__	( UpperCamelCase__				):
     a		:      Optional[int]		 =     version.parse("""1.11"""				)







     @property
     def       lowerCAmelCase_    (     self			)  ->   Mapping[str, Mapping[int, str]]:



          '''simple docstring'''



          return OrderedDict(
              [
                  ("pixel_values", {0: "batch", 1: "num_channels", 2: "height", 3: "width"}),
              ]			)







     @property
     def       lowerCAmelCase_    (     self			)  ->   float:



          '''simple docstring'''



          return 1e-3

