






'''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     A    (      SCREAMING_SNAKE_CASE__						):






 """simple docstring"""





 __a			:						jnp.ndarray
 __a			:						jnp.ndarray






class     A    (      nn.Module						):






 """simple docstring"""





 __a			:						int
 __a			:						Tuple[int]      =						(16, 32, 96, 256)
 __a			:						jnp.dtype      =						jnp.floataa
 def   _UpperCAmelCase       (							self ):
       UpperCamelCase_				:   Optional[Any]					    =							nn.Conv(
           self.block_out_channels[0]			,     kernel_size=(3, 3)			,     padding=((1, 1), (1, 1))			,     dtype=self.dtype			,     )

       UpperCamelCase_				:   Optional[Any]					    =							[]
       for i in range(len(self.block_out_channels ) - 1 ):
             UpperCamelCase_				:   Tuple					    =							self.block_out_channels[i]
             UpperCamelCase_				:   List[Any]					    =							self.block_out_channels[i + 1]
             UpperCamelCase_				:   Optional[int]					    =							nn.Conv(
                 __lowerCAmelCase			,     kernel_size=(3, 3)			,     padding=((1, 1), (1, 1))			,     dtype=self.dtype			,     )
             blocks.append(__lowerCAmelCase )
             UpperCamelCase_				:   Optional[int]					    =							nn.Conv(
                 __lowerCAmelCase			,     kernel_size=(3, 3)			,     strides=(2, 2)			,     padding=((1, 1), (1, 1))			,     dtype=self.dtype			,     )
             blocks.append(__lowerCAmelCase )
       UpperCamelCase_				:   str					    =							blocks

       UpperCamelCase_				:   str					    =							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_				:   Any					    =							self.conv_in(__lowerCAmelCase )
       UpperCamelCase_				:   List[str]					    =							nn.silu(__lowerCAmelCase )

       for block in self.blocks:
             UpperCamelCase_				:   List[Any]					    =							block(__lowerCAmelCase )
             UpperCamelCase_				:   str					    =							nn.silu(__lowerCAmelCase )

       UpperCamelCase_				:   Dict					    =							self.conv_out(__lowerCAmelCase )

       return embedding






@flax_register_to_config
class     A    (      nn.Module,   SCREAMING_SNAKE_CASE__,   SCREAMING_SNAKE_CASE__						):






 """simple docstring"""





 __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   _UpperCAmelCase       (							self			,     __lowerCAmelCase ):
       # init input tensors
       UpperCamelCase_				:   Optional[Any]					    =							(1, self.in_channels, self.sample_size, self.sample_size)
       UpperCamelCase_				:   str					    =							jnp.zeros(__lowerCAmelCase			,     dtype=jnp.floataa )
       UpperCamelCase_				:   Union[str, Any]					    =							jnp.ones((1,)			,     dtype=jnp.intaa )
       UpperCamelCase_				:   Union[str, Any]					    =							jnp.zeros((1, 1, self.cross_attention_dim)			,     dtype=jnp.floataa )
       UpperCamelCase_				:   Optional[int]					    =							(1, 3, self.sample_size * 8, self.sample_size * 8)
       UpperCamelCase_				:   int					    =							jnp.zeros(__lowerCAmelCase			,     dtype=jnp.floataa )

       UpperCamelCase_    ,			UpperCamelCase_				:   Tuple					    =							jax.random.split(__lowerCAmelCase )
       UpperCamelCase_				:   Union[str, Any]					    =							{"""params""": params_rng, """dropout""": dropout_rng}

       return self.init(__lowerCAmelCase			,     __lowerCAmelCase			,     __lowerCAmelCase			,     __lowerCAmelCase			,     __lowerCAmelCase )["params"]
 def   _UpperCAmelCase       (							self ):
       UpperCamelCase_				:   int					    =							self.block_out_channels
       UpperCamelCase_				:   List[Any]					    =							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_				:   Optional[Any]					    =							self.num_attention_heads or self.attention_head_dim

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

       # time
       UpperCamelCase_				:   Union[str, Any]					    =							FlaxTimesteps(
           block_out_channels[0]			,     flip_sin_to_cos=self.flip_sin_to_cos			,     freq_shift=self.config.freq_shift )
       UpperCamelCase_				:   str					    =							FlaxTimestepEmbedding(__lowerCAmelCase			,     dtype=self.dtype )

       UpperCamelCase_				:   Optional[int]					    =							FlaxControlNetConditioningEmbedding(
           conditioning_embedding_channels=block_out_channels[0]			,     block_out_channels=self.conditioning_embedding_out_channels			,     )

       UpperCamelCase_				:   Tuple					    =							self.only_cross_attention
       if isinstance(__lowerCAmelCase			,     __lowerCAmelCase ):
             UpperCamelCase_				:   List[Any]					    =							(only_cross_attention,) * len(self.down_block_types )

       if isinstance(__lowerCAmelCase			,     __lowerCAmelCase ):
             UpperCamelCase_				:   Dict					    =							(num_attention_heads,) * len(self.down_block_types )

       # down
       UpperCamelCase_				:   str					    =							[]
       UpperCamelCase_				:   str					    =							[]

       UpperCamelCase_				:   Optional[Any]					    =							block_out_channels[0]

       UpperCamelCase_				:   Optional[int]					    =							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_				:   Optional[int]					    =							output_channel
             UpperCamelCase_				:   Optional[Any]					    =							block_out_channels[i]
             UpperCamelCase_				:   Optional[Any]					    =							i == len(__lowerCAmelCase ) - 1

             if down_block_type == "CrossAttnDownBlock2D":
                   UpperCamelCase_				:   Any					    =							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_				:   Optional[int]					    =							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_				:   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 )

             if not is_final_block:
                   UpperCamelCase_				:   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			,     )
                   controlnet_down_blocks.append(__lowerCAmelCase )

       UpperCamelCase_				:   str					    =							down_blocks
       UpperCamelCase_				:   Optional[int]					    =							controlnet_down_blocks

       # mid
       UpperCamelCase_				:   Any					    =							block_out_channels[-1]
       UpperCamelCase_				:   Optional[int]					    =							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_				:   Union[str, 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			,     )





 def __call__(							self			,     __lowerCAmelCase			,     __lowerCAmelCase			,     __lowerCAmelCase			,     __lowerCAmelCase			,     __lowerCAmelCase = 1.0			,     __lowerCAmelCase = True			,     __lowerCAmelCase = False			,     ):
       UpperCamelCase_				:   Dict					    =							self.controlnet_conditioning_channel_order
       if channel_order == "bgr":
             UpperCamelCase_				:   List[str]					    =							jnp.flip(__lowerCAmelCase			,     axis=1 )

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

       UpperCamelCase_				:   List[str]					    =							self.time_proj(__lowerCAmelCase )
       UpperCamelCase_				:   str					    =							self.time_embedding(__lowerCAmelCase )

       # 2. pre-process
       UpperCamelCase_				:   Dict					    =							jnp.transpose(__lowerCAmelCase			,     (0, 2, 3, 1) )
       UpperCamelCase_				:   List[str]					    =							self.conv_in(__lowerCAmelCase )

       UpperCamelCase_				:   Optional[Any]					    =							jnp.transpose(__lowerCAmelCase			,     (0, 2, 3, 1) )
       UpperCamelCase_				:   Union[str, Any]					    =							self.controlnet_cond_embedding(__lowerCAmelCase )
       sample += controlnet_cond

       # 3. down
       UpperCamelCase_				:   Optional[Any]					    =							(sample,)
       for down_block in self.down_blocks:
             if isinstance(__lowerCAmelCase			,     __lowerCAmelCase ):
                   UpperCamelCase_    ,			UpperCamelCase_				:   List[str]					    =							down_block(__lowerCAmelCase			,     __lowerCAmelCase			,     __lowerCAmelCase			,     deterministic=not train )
             else:
                   UpperCamelCase_    ,			UpperCamelCase_				:   List[Any]					    =							down_block(__lowerCAmelCase			,     __lowerCAmelCase			,     deterministic=not train )
             down_block_res_samples += res_samples

       # 4. mid
       UpperCamelCase_				:   int					    =							self.mid_block(__lowerCAmelCase			,     __lowerCAmelCase			,     __lowerCAmelCase			,     deterministic=not train )

       # 5. contronet blocks
       UpperCamelCase_				:   Dict					    =							()
       for down_block_res_sample, controlnet_block in zip(__lowerCAmelCase			,     self.controlnet_down_blocks ):
             UpperCamelCase_				:   str					    =							controlnet_block(__lowerCAmelCase )
             controlnet_down_block_res_samples += (down_block_res_sample,)

       UpperCamelCase_				:   Dict					    =							controlnet_down_block_res_samples

       UpperCamelCase_				:   Union[str, Any]					    =							self.controlnet_mid_block(__lowerCAmelCase )

       # 6. scaling
       UpperCamelCase_				:   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 )














'''simple docstring'''

import random



def 							snake_case					(     a_							: int    ,   a_							: float    ,   a_							: bool = False	)       ->				dict:





      """simple docstring"""

      UpperCamelCase_				:   dict					    =							{i: [] for i in range(a_	)}

      # if probability is greater or equal than 1, then generate a complete graph
      if probability >= 1:
            return complete_graph(a_	)
      # if probability is lower or equal than 0, then return a graph without edges
      if probability <= 0:
            return graph

      # for each couple of nodes, add an edge from u to v
      # if the number randomly generated is greater than probability probability
      for i in range(a_	):
            for j in range(i + 1    ,   a_	):
                  if random.random() < probability:
                        graph[i].append(a_	)
                        if not directed:
                              # if the graph is undirected, add an edge in from j to i, either
                              graph[j].append(a_	)
      return graph



def 							snake_case					(     a_							: int	)       ->				dict:





      """simple docstring"""

      return {
          i: [j for j in range(a_	) if i != j] for i in range(a_	)
      }


if __name__ == "__main__":
      import doctest

      doctest.testmod()






