






"""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        UpperCamelCase__ (				a_):







    """simple docstring"""
    __UpperCAmelCase           = 42
    __UpperCAmelCase           = 42



class        UpperCamelCase__ (				nn.Module):







    """simple docstring"""
    __UpperCAmelCase           = 42
    __UpperCAmelCase           = (16, 32, 96, 2_56)
    __UpperCAmelCase           = jnp.floataa







    def 				a__			(		self :	List[Any] ):





           '''simple docstring'''

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

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

           __magic_name__      				=    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 :	Optional[int]				,    UpperCamelCase_ :	str ):





           '''simple docstring'''

           __magic_name__      				=    self.conv_in(_lowerCAmelCase )
           __magic_name__      				=    nn.silu(_lowerCAmelCase )

           for block in self.blocks:
                  __magic_name__      				=    block(_lowerCAmelCase )
                  __magic_name__      				=    nn.silu(_lowerCAmelCase )

           __magic_name__      				=    self.conv_out(_lowerCAmelCase )

           return embedding



@flax_register_to_config
class        UpperCamelCase__ (				nn.Module							,	a_							,	a_):







    """simple docstring"""
    __UpperCAmelCase           = 32
    __UpperCAmelCase           = 4
    __UpperCAmelCase           = (
        """CrossAttnDownBlock2D""",
        """CrossAttnDownBlock2D""",
        """CrossAttnDownBlock2D""",
        """DownBlock2D""",
    )
    __UpperCAmelCase           = False
    __UpperCAmelCase           = (3_20, 6_40, 12_80, 12_80)
    __UpperCAmelCase           = 2
    __UpperCAmelCase           = 8
    __UpperCAmelCase           = None
    __UpperCAmelCase           = 12_80
    __UpperCAmelCase           = 0.0
    __UpperCAmelCase           = False
    __UpperCAmelCase           = jnp.floataa
    __UpperCAmelCase           = True
    __UpperCAmelCase           = 0
    __UpperCAmelCase           = """rgb"""
    __UpperCAmelCase           = (16, 32, 96, 2_56)







    def 				a__			(		self :	List[Any]				,    UpperCamelCase_ :	jax.random.KeyArray ):





           '''simple docstring'''

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

           __magic_name__				,  __magic_name__      				=    jax.random.split(_lowerCAmelCase )
           __magic_name__      				=    {'params': params_rng, 'dropout': dropout_rng}

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







    def 				a__			(		self :	Tuple ):





           '''simple docstring'''

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

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

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

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

           __magic_name__      				=    self.only_cross_attention
           if isinstance(_lowerCAmelCase				,    _lowerCAmelCase ):
                  __magic_name__      				=    (only_cross_attention,) * len(self.down_block_types )

           if isinstance(_lowerCAmelCase				,    _lowerCAmelCase ):
                  __magic_name__      				=    (num_attention_heads,) * len(self.down_block_types )

           # down
           __magic_name__      				=    []
           __magic_name__      				=    []

           __magic_name__      				=    block_out_channels[0]

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

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

           __magic_name__      				=    down_blocks
           __magic_name__      				=    controlnet_down_blocks

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

           __magic_name__      				=    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 :	Optional[Any]				,    UpperCamelCase_ :	List[Any]				,    UpperCamelCase_ :	int				,    UpperCamelCase_ :	Optional[Any]				,    UpperCamelCase_ :	Optional[int]				,    UpperCamelCase_ :	float = 1.0				,    UpperCamelCase_ :	bool = True				,    UpperCamelCase_ :	bool = False				,    ):





           '''simple docstring'''

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

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

           __magic_name__      				=    self.time_proj(_lowerCAmelCase )
           __magic_name__      				=    self.time_embedding(_lowerCAmelCase )

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

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

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

           # 4. mid
           __magic_name__      				=    self.mid_block(_lowerCAmelCase				,    _lowerCAmelCase				,    _lowerCAmelCase				,    deterministic=not train )

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

           __magic_name__      				=    controlnet_down_block_res_samples

           __magic_name__      				=    self.controlnet_mid_block(_lowerCAmelCase )

           # 6. scaling
           __magic_name__      				=    [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       _lowerCAmelCase    (				lowerCAmelCase_				:int		,    lowerCAmelCase_				:int				)->int:
   '''simple docstring'''






   return int((input_a, input_a).count(0				) == 0				)



def       _lowerCAmelCase    (				)->None:
   '''simple docstring'''






   assert and_gate(0		,    0				) == 0
   assert and_gate(0		,    1				) == 0
   assert and_gate(1		,    0				) == 0
   assert and_gate(1		,    1				) == 1


if __name__ == "__main__":
   test_and_gate()
   print(and_gate(1, 0))
   print(and_gate(0, 0))
   print(and_gate(0, 1))
   print(and_gate(1, 1))




