



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 	lowerCamelCase      (						lowercase__  ):







     '''simple docstring'''







     lowerCAmelCase_				:    jnp.ndarray
     lowerCAmelCase_				:    jnp.ndarray





class 	lowerCamelCase      (						nn.Module  ):







     '''simple docstring'''







     lowerCAmelCase_				:    int
     lowerCAmelCase_				:    Tuple[int]									=  (16, 32, 96, 256)
     lowerCAmelCase_				:    jnp.dtype									=  jnp.floataa



     def    A__		(			self     ):
       UpperCAmelCase_						=				nn.Conv(
           self.block_out_channels[0]    ,	kernel_size=(3, 3)    ,	padding=((1, 1), (1, 1))    ,	dtype=self.dtype    ,	)

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

       UpperCAmelCase_						=				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    ,	lowerCAmelCase     ):
       UpperCAmelCase_						=				self.conv_in(lowerCAmelCase     )
       UpperCAmelCase_						=				nn.silu(lowerCAmelCase     )

       for block in self.blocks:
         UpperCAmelCase_						=				block(lowerCAmelCase     )
         UpperCAmelCase_						=				nn.silu(lowerCAmelCase     )

       UpperCAmelCase_						=				self.conv_out(lowerCAmelCase     )

       return embedding





@flax_register_to_config
class 	lowerCamelCase      (						nn.Module,     lowercase__,     lowercase__  ):







     '''simple docstring'''







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



     def    A__		(			self    ,	lowerCAmelCase     ):
       # init input tensors
       UpperCAmelCase_						=				(1, self.in_channels, self.sample_size, self.sample_size)
       UpperCAmelCase_						=				jnp.zeros(lowerCAmelCase    ,	dtype=jnp.floataa     )
       UpperCAmelCase_						=				jnp.ones((1,)    ,	dtype=jnp.intaa     )
       UpperCAmelCase_						=				jnp.zeros((1, 1, self.cross_attention_dim)    ,	dtype=jnp.floataa     )
       UpperCAmelCase_						=				(1, 3, self.sample_size * 8, self.sample_size * 8)
       UpperCAmelCase_						=				jnp.zeros(lowerCAmelCase    ,	dtype=jnp.floataa     )

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

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



     def    A__		(			self     ):
       UpperCAmelCase_						=				self.block_out_channels
       UpperCAmelCase_						=				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.
       UpperCAmelCase_						=				self.num_attention_heads or self.attention_head_dim

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

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

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

       UpperCAmelCase_						=				self.only_cross_attention
       if isinstance(lowerCAmelCase    ,	lowerCAmelCase     ):
         UpperCAmelCase_						=				(only_cross_attention,) * len(self.down_block_types     )

       if isinstance(lowerCAmelCase    ,	lowerCAmelCase     ):
         UpperCAmelCase_						=				(num_attention_heads,) * len(self.down_block_types     )

       # down
       UpperCAmelCase_						=				[]
       UpperCAmelCase_						=				[]

       UpperCAmelCase_						=				block_out_channels[0]

       UpperCAmelCase_						=				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     ):
         UpperCAmelCase_						=				output_channel
         UpperCAmelCase_						=				block_out_channels[i]
         UpperCAmelCase_						=				i == len(lowerCAmelCase     ) - 1

         if down_block_type == "CrossAttnDownBlock2D":
           UpperCAmelCase_						=				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:
           UpperCAmelCase_						=				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     ):
           UpperCAmelCase_						=				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:
           UpperCAmelCase_						=				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     )

       UpperCAmelCase_						=				down_blocks
       UpperCAmelCase_						=				controlnet_down_blocks

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

       UpperCAmelCase_						=				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    ,	lowerCAmelCase    ,	lowerCAmelCase    ,	lowerCAmelCase    ,	lowerCAmelCase    ,	lowerCAmelCase = 1.0    ,	lowerCAmelCase = True    ,	lowerCAmelCase = False    ,	):
       UpperCAmelCase_						=				self.controlnet_conditioning_channel_order
       if channel_order == "bgr":
         UpperCAmelCase_						=				jnp.flip(lowerCAmelCase    ,	axis=1     )

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

       UpperCAmelCase_						=				self.time_proj(lowerCAmelCase     )
       UpperCAmelCase_						=				self.time_embedding(lowerCAmelCase     )

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

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

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

       # 4. mid
       UpperCAmelCase_						=				self.mid_block(lowerCAmelCase    ,	lowerCAmelCase    ,	lowerCAmelCase    ,	deterministic=not train     )

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

       UpperCAmelCase_						=				controlnet_down_block_res_samples

       UpperCAmelCase_						=				self.controlnet_mid_block(lowerCAmelCase     )

       # 6. scaling
       UpperCAmelCase_						=				[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     )






def snake_case__  (			__SCREAMING_SNAKE_CASE			,     __SCREAMING_SNAKE_CASE )		->							Union[str, Any]:
		UpperCAmelCase_						=				0
		while b > 0:
				if b & 1:
						res += a

				a += a
				b >>= 1

		return res







def snake_case__  (			__SCREAMING_SNAKE_CASE			,     __SCREAMING_SNAKE_CASE			,     __SCREAMING_SNAKE_CASE )		->							Tuple:
		UpperCAmelCase_						=				0
		while b > 0:
				if b & 1:
						UpperCAmelCase_						=				((res % c) + (a % c)) % c

				a += a
				b >>= 1

		return res

