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




  '''simple docstring'''
  SCREAMING_SNAKE_CASE__			:						jnp.ndarray
  SCREAMING_SNAKE_CASE__			:						jnp.ndarray




class A_	(nn.Module      ):




  '''simple docstring'''
  SCREAMING_SNAKE_CASE__			:						int
  SCREAMING_SNAKE_CASE__			:						Tuple[int]       =		(16, 32, 96, 256)
  SCREAMING_SNAKE_CASE__			:						jnp.dtype       =		jnp.floataa







  def        UpperCamelCase__					(		self  ):

     """simple docstring"""
     UpperCAmelCase_					:					Optional[int]			     =    nn.Conv(
         self.block_out_channels[0]				,   kernel_size=(3, 3)				,   padding=((1, 1), (1, 1))				,   dtype=self.dtype				,   )

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

     UpperCAmelCase_					:					List[Any]			     =    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				,   lowercase_  ):

     """simple docstring"""
     UpperCAmelCase_					:					List[Any]			     =    self.conv_in(lowercase_  )
     UpperCAmelCase_					:					List[str]			     =    nn.silu(lowercase_  )

     for block in self.blocks:
        UpperCAmelCase_					:					Optional[Any]			     =    block(lowercase_  )
        UpperCAmelCase_					:					Optional[Any]			     =    nn.silu(lowercase_  )

     UpperCAmelCase_					:					Tuple			     =    self.conv_out(lowercase_  )

     return embedding




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




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







  def        UpperCamelCase__					(		self				,   lowercase_  ):

     """simple docstring"""
     # init input tensors
     UpperCAmelCase_					:					Tuple			     =    (1, self.in_channels, self.sample_size, self.sample_size)
     UpperCAmelCase_					:					int			     =    jnp.zeros(lowercase_				,   dtype=jnp.floataa  )
     UpperCAmelCase_					:					Any			     =    jnp.ones((1,)				,   dtype=jnp.intaa  )
     UpperCAmelCase_					:					Dict			     =    jnp.zeros((1, 1, self.cross_attention_dim)				,   dtype=jnp.floataa  )
     UpperCAmelCase_					:					Union[str, Any]			     =    (1, 3, self.sample_size * 8, self.sample_size * 8)
     UpperCAmelCase_					:					Tuple			     =    jnp.zeros(lowercase_				,   dtype=jnp.floataa  )

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

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







  def        UpperCamelCase__					(		self  ):

     """simple docstring"""
     UpperCAmelCase_					:					Union[str, Any]			     =    self.block_out_channels
     UpperCAmelCase_					:					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_					:					Any			     =    self.num_attention_heads or self.attention_head_dim

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

     # time
     UpperCAmelCase_					:					str			     =    FlaxTimesteps(
         block_out_channels[0]				,   flip_sin_to_cos=self.flip_sin_to_cos				,   freq_shift=self.config.freq_shift  )
     UpperCAmelCase_					:					int			     =    FlaxTimestepEmbedding(lowercase_				,   dtype=self.dtype  )

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

     UpperCAmelCase_					:					Optional[Any]			     =    self.only_cross_attention
     if isinstance(lowercase_				,   lowercase_  ):
        UpperCAmelCase_					:					int			     =    (only_cross_attention,) * len(self.down_block_types  )

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

     # down
     UpperCAmelCase_					:					Union[str, Any]			     =    []
     UpperCAmelCase_					:					Tuple			     =    []

     UpperCAmelCase_					:					str			     =    block_out_channels[0]

     UpperCAmelCase_					:					Optional[int]			     =    nn.Conv(
         lowercase_				,   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(lowercase_  )

     for i, down_block_type in enumerate(self.down_block_types  ):
        UpperCAmelCase_					:					Tuple			     =    output_channel
        UpperCAmelCase_					:					Tuple			     =    block_out_channels[i]
        UpperCAmelCase_					:					str			     =    i == len(lowercase_  ) - 1

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

        down_blocks.append(lowercase_  )

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

        if not is_final_block:
           UpperCAmelCase_					:					str			     =    nn.Conv(
               lowercase_				,   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(lowercase_  )

     UpperCAmelCase_					:					List[Any]			     =    down_blocks
     UpperCAmelCase_					:					Tuple			     =    controlnet_down_blocks

     # mid
     UpperCAmelCase_					:					Any			     =    block_out_channels[-1]
     UpperCAmelCase_					:					Union[str, Any]			     =    FlaxUNetMidBlockaDCrossAttn(
         in_channels=lowercase_				,   dropout=self.dropout				,   num_attention_heads=num_attention_heads[-1]				,   use_linear_projection=self.use_linear_projection				,   dtype=self.dtype				,   )

     UpperCAmelCase_					:					List[str]			     =    nn.Conv(
         lowercase_				,   kernel_size=(1, 1)				,   padding="VALID"				,   kernel_init=nn.initializers.zeros_init()				,   bias_init=nn.initializers.zeros_init()				,   dtype=self.dtype				,   )







  def __call__(		self				,   lowercase_				,   lowercase_				,   lowercase_				,   lowercase_				,   lowercase_ = 1.0				,   lowercase_ = True				,   lowercase_ = False				,   ):

     """simple docstring"""
     UpperCAmelCase_					:					Any			     =    self.controlnet_conditioning_channel_order
     if channel_order == "bgr":
        UpperCAmelCase_					:					List[str]			     =    jnp.flip(lowercase_				,   axis=1  )

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

     UpperCAmelCase_					:					Optional[int]			     =    self.time_proj(lowercase_  )
     UpperCAmelCase_					:					str			     =    self.time_embedding(lowercase_  )

     # 2. pre-process
     UpperCAmelCase_					:					str			     =    jnp.transpose(lowercase_				,   (0, 2, 3, 1)  )
     UpperCAmelCase_					:					Tuple			     =    self.conv_in(lowercase_  )

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

     # 3. down
     UpperCAmelCase_					:					Optional[int]			     =    (sample,)
     for down_block in self.down_blocks:
        if isinstance(lowercase_				,   lowercase_  ):
           UpperCAmelCase_     ,   UpperCAmelCase_					:					Dict			     =    down_block(lowercase_				,   lowercase_				,   lowercase_				,   deterministic=not train  )
        else:
           UpperCAmelCase_     ,   UpperCAmelCase_					:					str			     =    down_block(lowercase_				,   lowercase_				,   deterministic=not train  )
        down_block_res_samples += res_samples

     # 4. mid
     UpperCAmelCase_					:					Union[str, Any]			     =    self.mid_block(lowercase_				,   lowercase_				,   lowercase_				,   deterministic=not train  )

     # 5. contronet blocks
     UpperCAmelCase_					:					Tuple			     =    ()
     for down_block_res_sample, controlnet_block in zip(lowercase_				,   self.controlnet_down_blocks  ):
        UpperCAmelCase_					:					List[Any]			     =    controlnet_block(lowercase_  )
        controlnet_down_block_res_samples += (down_block_res_sample,)

     UpperCAmelCase_					:					List[str]			     =    controlnet_down_block_res_samples

     UpperCAmelCase_					:					List[str]			     =    self.controlnet_mid_block(lowercase_  )

     # 6. scaling
     UpperCAmelCase_					:					Optional[int]			     =    [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=lowercase_				,   mid_block_res_sample=lowercase_  )





import torch
import torch.nn as nn
from transformers.modeling_utils import ModuleUtilsMixin
from transformers.models.ta.modeling_ta import TaBlock, TaConfig, TaLayerNorm

from ...configuration_utils import ConfigMixin, register_to_config
from ...models import ModelMixin





class  __lowerCAmelCase     (					SCREAMING_SNAKE_CASE			,			SCREAMING_SNAKE_CASE			,			SCREAMING_SNAKE_CASE							):




  @register_to_config
  def __init__(				self							,   lowerCAmelCase							,   lowerCAmelCase							,   lowerCAmelCase							,   lowerCAmelCase							,   lowerCAmelCase							,   lowerCAmelCase							,   lowerCAmelCase							,   lowerCAmelCase							,   lowerCAmelCase							,   lowerCAmelCase = False							,   )  -> Tuple:
        '''simple docstring'''






        super().__init__()

        _lowercase	       =nn.Embedding(lowerCAmelCase							,   lowerCAmelCase					)

        _lowercase	       =nn.Embedding(lowerCAmelCase							,   lowerCAmelCase					)
        _lowercase	       =False

        _lowercase	       =nn.Dropout(p=lowerCAmelCase					)

        _lowercase	       =TaConfig(
            vocab_size=lowerCAmelCase							,   d_model=lowerCAmelCase							,   num_heads=lowerCAmelCase							,   d_kv=lowerCAmelCase							,   d_ff=lowerCAmelCase							,   dropout_rate=lowerCAmelCase							,   feed_forward_proj=lowerCAmelCase							,   is_decoder=lowerCAmelCase							,   is_encoder_decoder=lowerCAmelCase							,   )

        _lowercase	       =nn.ModuleList()
        for lyr_num in range(lowerCAmelCase					):
              _lowercase	       =TaBlock(lowerCAmelCase					)
              self.encoders.append(lowerCAmelCase					)

        _lowercase	       =TaLayerNorm(lowerCAmelCase					)
        _lowercase	       =nn.Dropout(p=lowerCAmelCase					)




  def   A__     (				self							,   lowerCAmelCase							,   lowerCAmelCase					)  -> Dict:
        '''simple docstring'''






        _lowercase	       =self.token_embedder(lowerCAmelCase					)

        _lowercase	       =encoder_input_tokens.shape[1]
        _lowercase	       =torch.arange(lowerCAmelCase							,   device=encoder_input_tokens.device					)
        x += self.position_encoding(lowerCAmelCase					)

        _lowercase	       =self.dropout_pre(lowerCAmelCase					)

        # inverted the attention mask
        _lowercase	       =encoder_input_tokens.size()
        _lowercase	       =self.get_extended_attention_mask(lowerCAmelCase							,   lowerCAmelCase					)

        for lyr in self.encoders:
              _lowercase	       =lyr(lowerCAmelCase							,   lowerCAmelCase					)[0]
        _lowercase	       =self.layer_norm(lowerCAmelCase					)

        return self.dropout_post(lowerCAmelCase					), encoder_inputs_mask


