def 	lowerCamelCase					(	UpperCamelCase     :				str							)   ->    bool:
		_lowerCamelCase				   =  0
		for ch in input_str:
				_lowerCamelCase				   =  ord(UpperCamelCase							)
				_lowerCamelCase				   =  pow(2			,       UpperCamelCase							)

				# If we already turned on bit for current character's unicode
				if bitmap >> ch_unicode & 1 == 1:
						return False
				bitmap |= ch_bit_index_on
		return True


if __name__ == "__main__":
				import doctest

				doctest.testmod()
from typing import Any, Dict, Optional

import torch
import torch.nn.functional as F
from torch import nn

from ..utils import maybe_allow_in_graph
from .activations import get_activation
from .attention_processor import Attention
from .embeddings import CombinedTimestepLabelEmbeddings





@maybe_allow_in_graph
class     lowerCAmelCase__     (				nn.Module			):


		'''simple docstring'''






		def __init__(       self     :     Dict     ,  snake_case__     :     int     ,  snake_case__     :     int     ,  snake_case__     :     int     ,  snake_case__     :     Tuple=0.0     ,  snake_case__     :     Optional[int] = None     ,  snake_case__     :     str = "geglu"     ,  snake_case__     :     Optional[int] = None     ,  snake_case__     :     bool = False     ,  snake_case__     :     bool = False     ,  snake_case__     :     bool = False     ,  snake_case__     :     bool = False     ,  snake_case__     :     bool = True     ,  snake_case__     :     str = "layer_norm"     ,  snake_case__     :     bool = False     ,  )      ->	Dict:
				super().__init__()
				_lowerCamelCase				   =  only_cross_attention

				_lowerCamelCase				   =  (num_embeds_ada_norm is not None) and norm_type == 'ada_norm_zero'
				_lowerCamelCase				   =  (num_embeds_ada_norm is not None) and norm_type == 'ada_norm'

				if norm_type in ("ada_norm", "ada_norm_zero") and num_embeds_ada_norm is None:
						raise ValueError(
						    f"""`norm_type` is set to {norm_type}, but `num_embeds_ada_norm` is not defined. Please make sure to"""
						    f""" define `num_embeds_ada_norm` if setting `norm_type` to {norm_type}."""		)

				# Define 3 blocks. Each block has its own normalization layer.
				# 1. Self-Attn
				if self.use_ada_layer_norm:
						_lowerCamelCase				   =  AdaLayerNorm(snake_case__     ,  snake_case__		)
				elif self.use_ada_layer_norm_zero:
						_lowerCamelCase				   =  AdaLayerNormZero(snake_case__     ,  snake_case__		)
				else:
						_lowerCamelCase				   =  nn.LayerNorm(snake_case__     ,  elementwise_affine=snake_case__		)
				_lowerCamelCase				   =  Attention(
				    query_dim=snake_case__     ,  heads=snake_case__     ,  dim_head=snake_case__     ,  dropout=snake_case__     ,  bias=snake_case__     ,  cross_attention_dim=cross_attention_dim if only_cross_attention else None     ,  upcast_attention=snake_case__     ,  )

				# 2. Cross-Attn
				if cross_attention_dim is not None or double_self_attention:
						# We currently only use AdaLayerNormZero for self attention where there will only be one attention block.
						# I.e. the number of returned modulation chunks from AdaLayerZero would not make sense if returned during
						# the second cross attention block.
						_lowerCamelCase				   =  (
						    AdaLayerNorm(snake_case__     ,  snake_case__		)
						    if self.use_ada_layer_norm
						    else nn.LayerNorm(snake_case__     ,  elementwise_affine=snake_case__		)
						)
						_lowerCamelCase				   =  Attention(
						    query_dim=snake_case__     ,  cross_attention_dim=cross_attention_dim if not double_self_attention else None     ,  heads=snake_case__     ,  dim_head=snake_case__     ,  dropout=snake_case__     ,  bias=snake_case__     ,  upcast_attention=snake_case__     ,  )  # is self-attn if encoder_hidden_states is none
				else:
						_lowerCamelCase				   =  None
						_lowerCamelCase				   =  None

				# 3. Feed-forward
				_lowerCamelCase				   =  nn.LayerNorm(snake_case__     ,  elementwise_affine=snake_case__		)
				_lowerCamelCase				   =  FeedForward(snake_case__     ,  dropout=snake_case__     ,  activation_fn=snake_case__     ,  final_dropout=snake_case__		)

				# let chunk size default to None
				_lowerCamelCase				   =  None
				_lowerCamelCase				   =  0
		def   _snake_case       (       self     :     str     ,  snake_case__     :     Optional[int]     ,  snake_case__     :     int		)      ->	Optional[Any]:
				# Sets chunk feed-forward
				_lowerCamelCase				   =  chunk_size
				_lowerCamelCase				   =  dim



		def   _snake_case       (       self     :     Union[str, Any]     ,  snake_case__     :     torch.FloatTensor     ,  snake_case__     :     Optional[torch.FloatTensor] = None     ,  snake_case__     :     Optional[torch.FloatTensor] = None     ,  snake_case__     :     Optional[torch.FloatTensor] = None     ,  snake_case__     :     Optional[torch.LongTensor] = None     ,  snake_case__     :     Dict[str, Any] = None     ,  snake_case__     :     Optional[torch.LongTensor] = None     ,  )      ->	List[Any]:
				# Notice that normalization is always applied before the real computation in the following blocks.
				# 1. Self-Attention
				if self.use_ada_layer_norm:
						_lowerCamelCase				   =  self.norma(snake_case__     ,  snake_case__		)
				elif self.use_ada_layer_norm_zero:
						_lowerCamelCase   ,							_lowerCamelCase   ,							_lowerCamelCase   ,							_lowerCamelCase   ,							_lowerCamelCase				   =  self.norma(
						    snake_case__     ,  snake_case__     ,  snake_case__     ,  hidden_dtype=hidden_states.dtype		)
				else:
						_lowerCamelCase				   =  self.norma(snake_case__		)

				_lowerCamelCase				   =  cross_attention_kwargs if cross_attention_kwargs is not None else {}

				_lowerCamelCase				   =  self.attna(
				    snake_case__     ,  encoder_hidden_states=encoder_hidden_states if self.only_cross_attention else None     ,  attention_mask=snake_case__     ,  **snake_case__     ,  )
				if self.use_ada_layer_norm_zero:
						_lowerCamelCase				   =  gate_msa.unsqueeze(1		) * attn_output
				_lowerCamelCase				   =  attn_output + hidden_states

				# 2. Cross-Attention
				if self.attna is not None:
						_lowerCamelCase				   =  (
						    self.norma(snake_case__     ,  snake_case__		) if self.use_ada_layer_norm else self.norma(snake_case__		)
						)

						_lowerCamelCase				   =  self.attna(
						    snake_case__     ,  encoder_hidden_states=snake_case__     ,  attention_mask=snake_case__     ,  **snake_case__     ,  )
						_lowerCamelCase				   =  attn_output + hidden_states

				# 3. Feed-forward
				_lowerCamelCase				   =  self.norma(snake_case__		)

				if self.use_ada_layer_norm_zero:
						_lowerCamelCase				   =  norm_hidden_states * (1 + scale_mlp[:, None]) + shift_mlp[:, None]

				if self._chunk_size is not None:
						# "feed_forward_chunk_size" can be used to save memory
						if norm_hidden_states.shape[self._chunk_dim] % self._chunk_size != 0:
								raise ValueError(
								    f"""`hidden_states` dimension to be chunked: {norm_hidden_states.shape[self._chunk_dim]} has to be divisible by chunk size: {self._chunk_size}. Make sure to set an appropriate `chunk_size` when calling `unet.enable_forward_chunking`."""		)

						_lowerCamelCase				   =  norm_hidden_states.shape[self._chunk_dim] // self._chunk_size
						_lowerCamelCase				   =  torch.cat(
						    [self.ff(snake_case__		) for hid_slice in norm_hidden_states.chunk(snake_case__     ,  dim=self._chunk_dim		)]     ,  dim=self._chunk_dim     ,  )
				else:
						_lowerCamelCase				   =  self.ff(snake_case__		)

				if self.use_ada_layer_norm_zero:
						_lowerCamelCase				   =  gate_mlp.unsqueeze(1		) * ff_output

				_lowerCamelCase				   =  ff_output + hidden_states

				return hidden_states





class     lowerCAmelCase__     (				nn.Module			):


		'''simple docstring'''






		def __init__(       self     :     Union[str, Any]     ,  snake_case__     :     int     ,  snake_case__     :     Optional[int] = None     ,  snake_case__     :     int = 4     ,  snake_case__     :     float = 0.0     ,  snake_case__     :     str = "geglu"     ,  snake_case__     :     bool = False     ,  )      ->	Optional[int]:
				super().__init__()
				_lowerCamelCase				   =  int(dim * mult		)
				_lowerCamelCase				   =  dim_out if dim_out is not None else dim

				if activation_fn == "gelu":
						_lowerCamelCase				   =  GELU(snake_case__     ,  snake_case__		)
				if activation_fn == "gelu-approximate":
						_lowerCamelCase				   =  GELU(snake_case__     ,  snake_case__     ,  approximate='tanh'		)
				elif activation_fn == "geglu":
						_lowerCamelCase				   =  GEGLU(snake_case__     ,  snake_case__		)
				elif activation_fn == "geglu-approximate":
						_lowerCamelCase				   =  ApproximateGELU(snake_case__     ,  snake_case__		)

				_lowerCamelCase				   =  nn.ModuleList([]		)
				# project in
				self.net.append(snake_case__		)
				# project dropout
				self.net.append(nn.Dropout(snake_case__		)		)
				# project out
				self.net.append(nn.Linear(snake_case__     ,  snake_case__		)		)
				# FF as used in Vision Transformer, MLP-Mixer, etc. have a final dropout
				if final_dropout:
						self.net.append(nn.Dropout(snake_case__		)		)



		def   _snake_case       (       self     :     Tuple     ,  snake_case__     :     List[Any]		)      ->	Optional[int]:
				for module in self.net:
						_lowerCamelCase				   =  module(snake_case__		)
				return hidden_states





class     lowerCAmelCase__     (				nn.Module			):


		'''simple docstring'''






		def __init__(       self     :     str     ,  snake_case__     :     int     ,  snake_case__     :     int     ,  snake_case__     :     str = "none"		)      ->	Any:
				super().__init__()
				_lowerCamelCase				   =  nn.Linear(snake_case__     ,  snake_case__		)
				_lowerCamelCase				   =  approximate
		def   _snake_case       (       self     :     List[Any]     ,  snake_case__     :     List[Any]		)      ->	int:
				if gate.device.type != "mps":
						return F.gelu(snake_case__     ,  approximate=self.approximate		)
				# mps: gelu is not implemented for float16
				return F.gelu(gate.to(dtype=torch.floataa		)     ,  approximate=self.approximate		).to(dtype=gate.dtype		)



		def   _snake_case       (       self     :     Optional[int]     ,  snake_case__     :     Union[str, Any]		)      ->	str:
				_lowerCamelCase				   =  self.proj(snake_case__		)
				_lowerCamelCase				   =  self.gelu(snake_case__		)
				return hidden_states





class     lowerCAmelCase__     (				nn.Module			):


		'''simple docstring'''






		def __init__(       self     :     Dict     ,  snake_case__     :     int     ,  snake_case__     :     int		)      ->	List[Any]:
				super().__init__()
				_lowerCamelCase				   =  nn.Linear(snake_case__     ,  dim_out * 2		)
		def   _snake_case       (       self     :     Optional[Any]     ,  snake_case__     :     Optional[int]		)      ->	Optional[Any]:
				if gate.device.type != "mps":
						return F.gelu(snake_case__		)
				# mps: gelu is not implemented for float16
				return F.gelu(gate.to(dtype=torch.floataa		)		).to(dtype=gate.dtype		)



		def   _snake_case       (       self     :     List[str]     ,  snake_case__     :     Optional[Any]		)      ->	Optional[int]:
				_lowerCamelCase   ,							_lowerCamelCase				   =  self.proj(snake_case__		).chunk(2     ,  dim=-1		)
				return hidden_states * self.gelu(snake_case__		)





class     lowerCAmelCase__     (				nn.Module			):


		'''simple docstring'''






		def __init__(       self     :     Dict     ,  snake_case__     :     int     ,  snake_case__     :     int		)      ->	Tuple:
				super().__init__()
				_lowerCamelCase				   =  nn.Linear(snake_case__     ,  snake_case__		)



		def   _snake_case       (       self     :     Optional[Any]     ,  snake_case__     :     List[Any]		)      ->	Optional[int]:
				_lowerCamelCase				   =  self.proj(snake_case__		)
				return x * torch.sigmoid(1.702 * x		)





class     lowerCAmelCase__     (				nn.Module			):


		'''simple docstring'''






		def __init__(       self     :     Optional[Any]     ,  snake_case__     :     Tuple     ,  snake_case__     :     Any		)      ->	Dict:
				super().__init__()
				_lowerCamelCase				   =  nn.Embedding(snake_case__     ,  snake_case__		)
				_lowerCamelCase				   =  nn.SiLU()
				_lowerCamelCase				   =  nn.Linear(snake_case__     ,  embedding_dim * 2		)
				_lowerCamelCase				   =  nn.LayerNorm(snake_case__     ,  elementwise_affine=snake_case__		)



		def   _snake_case       (       self     :     Tuple     ,  snake_case__     :     str     ,  snake_case__     :     Dict		)      ->	Optional[int]:
				_lowerCamelCase				   =  self.linear(self.silu(self.emb(snake_case__		)		)		)
				_lowerCamelCase   ,							_lowerCamelCase				   =  torch.chunk(snake_case__     ,  2		)
				_lowerCamelCase				   =  self.norm(snake_case__		) * (1 + scale) + shift
				return x





class     lowerCAmelCase__     (				nn.Module			):


		'''simple docstring'''






		def __init__(       self     :     Any     ,  snake_case__     :     Optional[Any]     ,  snake_case__     :     Union[str, Any]		)      ->	Dict:
				super().__init__()

				_lowerCamelCase				   =  CombinedTimestepLabelEmbeddings(snake_case__     ,  snake_case__		)

				_lowerCamelCase				   =  nn.SiLU()
				_lowerCamelCase				   =  nn.Linear(snake_case__     ,  6 * embedding_dim     ,  bias=snake_case__		)
				_lowerCamelCase				   =  nn.LayerNorm(snake_case__     ,  elementwise_affine=snake_case__     ,  eps=1e-6		)



		def   _snake_case       (       self     :     Dict     ,  snake_case__     :     Tuple     ,  snake_case__     :     str     ,  snake_case__     :     str     ,  snake_case__     :     List[Any]=None		)      ->	int:
				_lowerCamelCase				   =  self.linear(self.silu(self.emb(snake_case__     ,  snake_case__     ,  hidden_dtype=snake_case__		)		)		)
				_lowerCamelCase   ,							_lowerCamelCase   ,							_lowerCamelCase   ,							_lowerCamelCase   ,							_lowerCamelCase   ,							_lowerCamelCase				   =  emb.chunk(6     ,  dim=1		)
				_lowerCamelCase				   =  self.norm(snake_case__		) * (1 + scale_msa[:, None]) + shift_msa[:, None]
				return x, gate_msa, shift_mlp, scale_mlp, gate_mlp





class     lowerCAmelCase__     (				nn.Module			):


		'''simple docstring'''






		def __init__(       self     :     Tuple     ,  snake_case__     :     int     ,  snake_case__     :     int     ,  snake_case__     :     int     ,  snake_case__     :     Optional[str] = None     ,  snake_case__     :     float = 1e-5		)      ->	int:
				super().__init__()
				_lowerCamelCase				   =  num_groups
				_lowerCamelCase				   =  eps

				if act_fn is None:
						_lowerCamelCase				   =  None
				else:
						_lowerCamelCase				   =  get_activation(snake_case__		)

				_lowerCamelCase				   =  nn.Linear(snake_case__     ,  out_dim * 2		)



		def   _snake_case       (       self     :     Union[str, Any]     ,  snake_case__     :     int     ,  snake_case__     :     Optional[Any]		)      ->	Union[str, Any]:
				if self.act:
						_lowerCamelCase				   =  self.act(snake_case__		)
				_lowerCamelCase				   =  self.linear(snake_case__		)
				_lowerCamelCase				   =  emb[:, :, None, None]
				_lowerCamelCase   ,							_lowerCamelCase				   =  emb.chunk(2     ,  dim=1		)

				_lowerCamelCase				   =  F.group_norm(snake_case__     ,  self.num_groups     ,  eps=self.eps		)
				_lowerCamelCase				   =  x * (1 + scale) + shift
				return x