'''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 			__lowercase		(						_lowerCamelCase						):







     """simple docstring"""






     SCREAMING_SNAKE_CASE__		   =						42
     SCREAMING_SNAKE_CASE__		   =						42






class 			__lowercase		(						nn.Module						):







     """simple docstring"""






     SCREAMING_SNAKE_CASE__		   =						42
     SCREAMING_SNAKE_CASE__		   =						(16, 32, 96, 256)
     SCREAMING_SNAKE_CASE__		   =						jnp.floataa







     def lowerCAmelCase     (		self    ):
         __UpperCamelCase	:	str		    =  nn.Conv(
             self.block_out_channels[0]     ,			kernel_size=(3, 3)     ,			padding=((1, 1), (1, 1))     ,			dtype=self.dtype     ,			)

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

         __UpperCamelCase	:	Union[str, 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     ,			_lowerCamelCase    ):
         __UpperCamelCase	:	str		    =  self.conv_in(_lowerCamelCase    )
         __UpperCamelCase	:	Union[str, Any]		    =  nn.silu(_lowerCamelCase    )

         for block in self.blocks:
             __UpperCamelCase	:	Optional[int]		    =  block(_lowerCamelCase    )
             __UpperCamelCase	:	Optional[Any]		    =  nn.silu(_lowerCamelCase    )

         __UpperCamelCase	:	Tuple		    =  self.conv_out(_lowerCamelCase    )

         return embedding






@flax_register_to_config
class 			__lowercase		(						nn.Module			,							_lowerCamelCase			,							_lowerCamelCase						):







     """simple docstring"""






     SCREAMING_SNAKE_CASE__		   =						32
     SCREAMING_SNAKE_CASE__		   =						4
     SCREAMING_SNAKE_CASE__		   =						(
         "CrossAttnDownBlock2D",
         "CrossAttnDownBlock2D",
         "CrossAttnDownBlock2D",
         "DownBlock2D",
     )
     SCREAMING_SNAKE_CASE__		   =						False
     SCREAMING_SNAKE_CASE__		   =						(320, 640, 1280, 1280)
     SCREAMING_SNAKE_CASE__		   =						2
     SCREAMING_SNAKE_CASE__		   =						8
     SCREAMING_SNAKE_CASE__		   =						None
     SCREAMING_SNAKE_CASE__		   =						1280
     SCREAMING_SNAKE_CASE__		   =						0.0
     SCREAMING_SNAKE_CASE__		   =						False
     SCREAMING_SNAKE_CASE__		   =						jnp.floataa
     SCREAMING_SNAKE_CASE__		   =						True
     SCREAMING_SNAKE_CASE__		   =						0
     SCREAMING_SNAKE_CASE__		   =						"rgb"
     SCREAMING_SNAKE_CASE__		   =						(16, 32, 96, 256)







     def lowerCAmelCase     (		self     ,			_lowerCamelCase    ):
         # init input tensors
         __UpperCamelCase	:	Union[str, Any]		    =  (1, self.in_channels, self.sample_size, self.sample_size)
         __UpperCamelCase	:	int		    =  jnp.zeros(_lowerCamelCase     ,			dtype=jnp.floataa    )
         __UpperCamelCase	:	Union[str, Any]		    =  jnp.ones((1,)     ,			dtype=jnp.intaa    )
         __UpperCamelCase	:	int		    =  jnp.zeros((1, 1, self.cross_attention_dim)     ,			dtype=jnp.floataa    )
         __UpperCamelCase	:	List[str]		    =  (1, 3, self.sample_size * 8, self.sample_size * 8)
         __UpperCamelCase	:	List[Any]		    =  jnp.zeros(_lowerCamelCase     ,			dtype=jnp.floataa    )

         __UpperCamelCase    ,					__UpperCamelCase	:	str		    =  jax.random.split(_lowerCamelCase    )
         __UpperCamelCase	:	List[Any]		    =  {'params': params_rng, 'dropout': dropout_rng}

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







     def lowerCAmelCase     (		self    ):
         __UpperCamelCase	:	Any		    =  self.block_out_channels
         __UpperCamelCase	:	Optional[int]		    =  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	:	Dict		    =  self.num_attention_heads or self.attention_head_dim

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

         # time
         __UpperCamelCase	:	Any		    =  FlaxTimesteps(
             block_out_channels[0]     ,			flip_sin_to_cos=self.flip_sin_to_cos     ,			freq_shift=self.config.freq_shift    )
         __UpperCamelCase	:	List[Any]		    =  FlaxTimestepEmbedding(_lowerCamelCase     ,			dtype=self.dtype    )

         __UpperCamelCase	:	str		    =  FlaxControlNetConditioningEmbedding(
             conditioning_embedding_channels=block_out_channels[0]     ,			block_out_channels=self.conditioning_embedding_out_channels     ,			)

         __UpperCamelCase	:	Union[str, Any]		    =  self.only_cross_attention
         if isinstance(_lowerCamelCase     ,			_lowerCamelCase    ):
             __UpperCamelCase	:	int		    =  (only_cross_attention,) * len(self.down_block_types    )

         if isinstance(_lowerCamelCase     ,			_lowerCamelCase    ):
             __UpperCamelCase	:	Optional[Any]		    =  (num_attention_heads,) * len(self.down_block_types    )

         # down
         __UpperCamelCase	:	Union[str, Any]		    =  []
         __UpperCamelCase	:	Optional[int]		    =  []

         __UpperCamelCase	:	Union[str, Any]		    =  block_out_channels[0]

         __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    )

         for i, down_block_type in enumerate(self.down_block_types    ):
             __UpperCamelCase	:	Any		    =  output_channel
             __UpperCamelCase	:	int		    =  block_out_channels[i]
             __UpperCamelCase	:	Union[str, Any]		    =  i == len(_lowerCamelCase    ) - 1

             if down_block_type == "CrossAttnDownBlock2D":
                 __UpperCamelCase	:	Union[str, 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	:	List[Any]		    =  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	:	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    )

             if not is_final_block:
                 __UpperCamelCase	:	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    )

         __UpperCamelCase	:	Dict		    =  down_blocks
         __UpperCamelCase	:	Any		    =  controlnet_down_blocks

         # mid
         __UpperCamelCase	:	Tuple		    =  block_out_channels[-1]
         __UpperCamelCase	:	List[str]		    =  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	:	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     ,			)







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

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

         __UpperCamelCase	:	Optional[int]		    =  self.time_proj(_lowerCamelCase    )
         __UpperCamelCase	:	Tuple		    =  self.time_embedding(_lowerCamelCase    )

         # 2. pre-process
         __UpperCamelCase	:	str		    =  jnp.transpose(_lowerCamelCase     ,			(0, 2, 3, 1)    )
         __UpperCamelCase	:	Dict		    =  self.conv_in(_lowerCamelCase    )

         __UpperCamelCase	:	Optional[int]		    =  jnp.transpose(_lowerCamelCase     ,			(0, 2, 3, 1)    )
         __UpperCamelCase	:	Optional[Any]		    =  self.controlnet_cond_embedding(_lowerCamelCase    )
         sample += controlnet_cond

         # 3. down
         __UpperCamelCase	:	List[Any]		    =  (sample,)
         for down_block in self.down_blocks:
             if isinstance(_lowerCamelCase     ,			_lowerCamelCase    ):
                 __UpperCamelCase    ,					__UpperCamelCase	:	int		    =  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	:	List[str]		    =  self.mid_block(_lowerCamelCase     ,			_lowerCamelCase     ,			_lowerCamelCase     ,			deterministic=not train    )

         # 5. contronet blocks
         __UpperCamelCase	:	str		    =  ()
         for down_block_res_sample, controlnet_block in zip(_lowerCamelCase     ,			self.controlnet_down_blocks    ):
             __UpperCamelCase	:	Optional[Any]		    =  controlnet_block(_lowerCamelCase    )
             controlnet_down_block_res_samples += (down_block_res_sample,)

         __UpperCamelCase	:	Dict		    =  controlnet_down_block_res_samples

         __UpperCamelCase	:	List[str]		    =  self.controlnet_mid_block(_lowerCamelCase    )

         # 6. scaling
         __UpperCamelCase	:	str		    =  [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'''
from timeit import timeit

a=  {
    '''MALAYALAM''': True,
    '''String''': False,
    '''rotor''': True,
    '''level''': True,
    '''A''': True,
    '''BB''': True,
    '''ABC''': False,
    '''amanaplanacanalpanama''': True,  # "a man a plan a canal panama"
}
# Ensure our test data is valid
assert all((key == key[::-1]) is value for key, value in test_data.items())







def  _UpperCamelCase (     _a	:	str			):




    """simple docstring"""



    __UpperCamelCase	:	int		    =  0
    __UpperCamelCase	:	str		    =  len(_a			) - 1
    while start_i < end_i:
        if s[start_i] == s[end_i]:
            start_i += 1
            end_i -= 1
        else:
            return False
    return True







def  _UpperCamelCase (     _a	:	str			):




    """simple docstring"""



    __UpperCamelCase	:	Optional[Any]		    =  len(_a			) // 2
    __UpperCamelCase	:	Tuple		    =  len(_a			)

    # We need to traverse till half of the length of string
    # as we can get access of the i'th last element from
    # i'th index.
    # eg: [0,1,2,3,4,5] => 4th index can be accessed
    # with the help of 1st index (i==n-i-1)
    # where n is length of string
    return all(s[i] == s[n - i - 1] for i in range(_a			)			)







def  _UpperCamelCase (     _a	:	str			):




    """simple docstring"""



    if len(_a			) <= 2:
        return True
    if s[0] == s[len(_a			) - 1]:
        return is_palindrome_recursive(s[1:-1]			)
    else:
        return False







def  _UpperCamelCase (     _a	:	str			):




    """simple docstring"""



    return s == s[::-1]







def  _UpperCamelCase (     _a	:	str			):




    """simple docstring"""



    __UpperCamelCase	:	int		    =  f"""all({name}(key) is value for key, value in test_data.items())"""
    __UpperCamelCase	:	Union[str, Any]		    =  f"""from __main__ import test_data, {name}"""
    __UpperCamelCase	:	Any		    =  5_0_0_0_0_0
    __UpperCamelCase	:	Tuple		    =  timeit(stmt=_a				,     setup=_a				,     number=_a			)
    print(f"""{name:<35} finished {number:,} runs in {result:.5f} seconds"""			)


if __name__ == "__main__":
  for key, value in test_data.items():
    assert is_palindrome(key) is is_palindrome_recursive(key)
    assert is_palindrome(key) is is_palindrome_slice(key)
    print(F"""{key:21} {value}""")
  print('''a man a plan a canal panama''')

  # finished 500,000 runs in 0.46793 seconds
  benchmark_function('''is_palindrome_slice''')
  # finished 500,000 runs in 0.85234 seconds
  benchmark_function('''is_palindrome''')
  # finished 500,000 runs in 1.32028 seconds
  benchmark_function('''is_palindrome_recursive''')
  # finished 500,000 runs in 2.08679 seconds
  benchmark_function('''is_palindrome_traversal''')



