



"""simple docstring"""







from dataclasses import dataclass
from typing import Any, Dict, Optional

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

from ..configuration_utils import ConfigMixin, register_to_config
from ..models.embeddings import ImagePositionalEmbeddings
from ..utils import BaseOutput, deprecate
from .attention import BasicTransformerBlock
from .embeddings import PatchEmbed
from .modeling_utils import ModelMixin





@dataclass
class   UpperCamelCase	(     snake_case       ):




	"""simple docstring"""
	SCREAMING_SNAKE_CASE_							:       torch.FloatTensor







class   UpperCamelCase	(     snake_case					,   snake_case       ):




	"""simple docstring"""






	@register_to_config
	def __init__(     self				,UpperCAmelCase_ = 16				,UpperCAmelCase_ = 88				,UpperCAmelCase_ = None				,UpperCAmelCase_ = None				,UpperCAmelCase_ = 1				,UpperCAmelCase_ = 0.0				,UpperCAmelCase_ = 32				,UpperCAmelCase_ = None				,UpperCAmelCase_ = False				,UpperCAmelCase_ = None				,UpperCAmelCase_ = None				,UpperCAmelCase_ = None				,UpperCAmelCase_ = "geglu"				,UpperCAmelCase_ = None				,UpperCAmelCase_ = False				,UpperCAmelCase_ = False				,UpperCAmelCase_ = False				,UpperCAmelCase_ = "layer_norm"				,UpperCAmelCase_ = True				,):
			super().__init__()
			_lowercase				: Tuple     =   use_linear_projection
			_lowercase				: Union[str, Any]     =   num_attention_heads
			_lowercase				: str     =   attention_head_dim
			_lowercase				: Optional[Any]     =   num_attention_heads * attention_head_dim

			# 1. Transformer2DModel can process both standard continuous images of shape `(batch_size, num_channels, width, height)` as well as quantized image embeddings of shape `(batch_size, num_image_vectors)`
			# Define whether input is continuous or discrete depending on configuration
			_lowercase				: List[str]     =   (in_channels is not None) and (patch_size is None)
			_lowercase				: Any     =   num_vector_embeds is not None
			_lowercase				: Optional[Any]     =   in_channels is not None and patch_size is not None

			if norm_type == "layer_norm" and num_embeds_ada_norm is not None:
					_lowercase				: Any     =   (
					    f"""The configuration file of this model: {self.__class__} is outdated. `norm_type` is either not set or"""
					    """ incorrectly set to `'layer_norm'`.Make sure to set `norm_type` to `'ada_norm'` in the config."""
					    """ Please make sure to update the config accordingly as leaving `norm_type` might led to incorrect"""
					    """ results in future versions. If you have downloaded this checkpoint from the Hugging Face Hub, it"""
					    """ would be very nice if you could open a Pull request for the `transformer/config.json` file"""
					)
					deprecate("""norm_type!=num_embeds_ada_norm"""				,"""1.0.0"""				,UpperCAmelCase_				,standard_warn=UpperCAmelCase_   )
					_lowercase				: Optional[int]     =   """ada_norm"""

			if self.is_input_continuous and self.is_input_vectorized:
					raise ValueError(
					    f"""Cannot define both `in_channels`: {in_channels} and `num_vector_embeds`: {num_vector_embeds}. Make"""
					    """ sure that either `in_channels` or `num_vector_embeds` is None."""   )
			elif self.is_input_vectorized and self.is_input_patches:
					raise ValueError(
					    f"""Cannot define both `num_vector_embeds`: {num_vector_embeds} and `patch_size`: {patch_size}. Make"""
					    """ sure that either `num_vector_embeds` or `num_patches` is None."""   )
			elif not self.is_input_continuous and not self.is_input_vectorized and not self.is_input_patches:
					raise ValueError(
					    f"""Has to define `in_channels`: {in_channels}, `num_vector_embeds`: {num_vector_embeds}, or patch_size:"""
					    f""" {patch_size}. Make sure that `in_channels`, `num_vector_embeds` or `num_patches` is not None."""   )

			# 2. Define input layers
			if self.is_input_continuous:
					_lowercase				: int     =   in_channels

					_lowercase				: int     =   torch.nn.GroupNorm(num_groups=UpperCAmelCase_				,num_channels=UpperCAmelCase_				,eps=1E-6				,affine=UpperCAmelCase_   )
					if use_linear_projection:
							_lowercase				: Tuple     =   nn.Linear(UpperCAmelCase_				,UpperCAmelCase_   )
					else:
							_lowercase				: Tuple     =   nn.Convad(UpperCAmelCase_				,UpperCAmelCase_				,kernel_size=1				,stride=1				,padding=0   )
			elif self.is_input_vectorized:
					assert sample_size is not None, "Transformer2DModel over discrete input must provide sample_size"
					assert num_vector_embeds is not None, "Transformer2DModel over discrete input must provide num_embed"

					_lowercase				: int     =   sample_size
					_lowercase				: Dict     =   sample_size
					_lowercase				: List[str]     =   num_vector_embeds
					_lowercase				: str     =   self.height * self.width

					_lowercase				: Any     =   ImagePositionalEmbeddings(
					    num_embed=UpperCAmelCase_				,embed_dim=UpperCAmelCase_				,height=self.height				,width=self.width   )
			elif self.is_input_patches:
					assert sample_size is not None, "Transformer2DModel over patched input must provide sample_size"

					_lowercase				: List[str]     =   sample_size
					_lowercase				: str     =   sample_size

					_lowercase				: Tuple     =   patch_size
					_lowercase				: List[str]     =   PatchEmbed(
					    height=UpperCAmelCase_				,width=UpperCAmelCase_				,patch_size=UpperCAmelCase_				,in_channels=UpperCAmelCase_				,embed_dim=UpperCAmelCase_				,)

			# 3. Define transformers blocks
			_lowercase				: Tuple     =   nn.ModuleList(
			    [
			        BasicTransformerBlock(
			            UpperCAmelCase_				,UpperCAmelCase_				,UpperCAmelCase_				,dropout=UpperCAmelCase_				,cross_attention_dim=UpperCAmelCase_				,activation_fn=UpperCAmelCase_				,num_embeds_ada_norm=UpperCAmelCase_				,attention_bias=UpperCAmelCase_				,only_cross_attention=UpperCAmelCase_				,upcast_attention=UpperCAmelCase_				,norm_type=UpperCAmelCase_				,norm_elementwise_affine=UpperCAmelCase_				,)
			        for d in range(UpperCAmelCase_   )
			    ]   )

			# 4. Define output layers
			_lowercase				: Optional[Any]     =   in_channels if out_channels is None else out_channels
			if self.is_input_continuous:
					# TODO: should use out_channels for continuous projections
					if use_linear_projection:
							_lowercase				: Optional[Any]     =   nn.Linear(UpperCAmelCase_				,UpperCAmelCase_   )
					else:
							_lowercase				: List[str]     =   nn.Convad(UpperCAmelCase_				,UpperCAmelCase_				,kernel_size=1				,stride=1				,padding=0   )
			elif self.is_input_vectorized:
					_lowercase				: Tuple     =   nn.LayerNorm(UpperCAmelCase_   )
					_lowercase				: Optional[Any]     =   nn.Linear(UpperCAmelCase_				,self.num_vector_embeds - 1   )
			elif self.is_input_patches:
					_lowercase				: str     =   nn.LayerNorm(UpperCAmelCase_				,elementwise_affine=UpperCAmelCase_				,eps=1E-6   )
					_lowercase				: str     =   nn.Linear(UpperCAmelCase_				,2 * inner_dim   )
					_lowercase				: str     =   nn.Linear(UpperCAmelCase_				,patch_size * patch_size * self.out_channels   )






	def    lowerCamelCase__					(     self				,UpperCAmelCase_				,UpperCAmelCase_ = None				,UpperCAmelCase_ = None				,UpperCAmelCase_ = None				,UpperCAmelCase_ = None				,UpperCAmelCase_ = None				,UpperCAmelCase_ = None				,UpperCAmelCase_ = True				,):
			# ensure attention_mask is a bias, and give it a singleton query_tokens dimension.
			#   we may have done this conversion already, e.g. if we came here via UNet2DConditionModel#forward.
			#   we can tell by counting dims; if ndim == 2: it's a mask rather than a bias.
			# expects mask of shape:
			#   [batch, key_tokens]
			# adds singleton query_tokens dimension:
			#   [batch,                    1, key_tokens]
			# this helps to broadcast it as a bias over attention scores, which will be in one of the following shapes:
			#   [batch,  heads, query_tokens, key_tokens] (e.g. torch sdp attn)
			#   [batch * heads, query_tokens, key_tokens] (e.g. xformers or classic attn)
			if attention_mask is not None and attention_mask.ndim == 2:
					# assume that mask is expressed as:
					#   (1 = keep,      0 = discard)
					# convert mask into a bias that can be added to attention scores:
					#       (keep = +0,     discard = -10000.0)
					_lowercase				: Dict     =   (1 - attention_mask.to(hidden_states.dtype   )) * -10000.0
					_lowercase				: Any     =   attention_mask.unsqueeze(1   )

			# convert encoder_attention_mask to a bias the same way we do for attention_mask
			if encoder_attention_mask is not None and encoder_attention_mask.ndim == 2:
					_lowercase				: List[str]     =   (1 - encoder_attention_mask.to(hidden_states.dtype   )) * -10000.0
					_lowercase				: List[Any]     =   encoder_attention_mask.unsqueeze(1   )

			# 1. Input
			if self.is_input_continuous:
					_lowercase     ,  _lowercase     ,  _lowercase     ,  _lowercase				: Optional[int]     =   hidden_states.shape
					_lowercase				: str     =   hidden_states

					_lowercase				: Tuple     =   self.norm(UpperCAmelCase_   )
					if not self.use_linear_projection:
							_lowercase				: Tuple     =   self.proj_in(UpperCAmelCase_   )
							_lowercase				: Any     =   hidden_states.shape[1]
							_lowercase				: Tuple     =   hidden_states.permute(0				,2				,3				,1   ).reshape(UpperCAmelCase_				,height * width				,UpperCAmelCase_   )
					else:
							_lowercase				: List[str]     =   hidden_states.shape[1]
							_lowercase				: Optional[int]     =   hidden_states.permute(0				,2				,3				,1   ).reshape(UpperCAmelCase_				,height * width				,UpperCAmelCase_   )
							_lowercase				: Union[str, Any]     =   self.proj_in(UpperCAmelCase_   )
			elif self.is_input_vectorized:
					_lowercase				: Dict     =   self.latent_image_embedding(UpperCAmelCase_   )
			elif self.is_input_patches:
					_lowercase				: int     =   self.pos_embed(UpperCAmelCase_   )

			# 2. Blocks
			for block in self.transformer_blocks:
					_lowercase				: Any     =   block(
					    UpperCAmelCase_				,attention_mask=UpperCAmelCase_				,encoder_hidden_states=UpperCAmelCase_				,encoder_attention_mask=UpperCAmelCase_				,timestep=UpperCAmelCase_				,cross_attention_kwargs=UpperCAmelCase_				,class_labels=UpperCAmelCase_				,)

			# 3. Output
			if self.is_input_continuous:
					if not self.use_linear_projection:
							_lowercase				: Optional[Any]     =   hidden_states.reshape(UpperCAmelCase_				,UpperCAmelCase_				,UpperCAmelCase_				,UpperCAmelCase_   ).permute(0				,3				,1				,2   ).contiguous()
							_lowercase				: Optional[Any]     =   self.proj_out(UpperCAmelCase_   )
					else:
							_lowercase				: List[str]     =   self.proj_out(UpperCAmelCase_   )
							_lowercase				: Optional[int]     =   hidden_states.reshape(UpperCAmelCase_				,UpperCAmelCase_				,UpperCAmelCase_				,UpperCAmelCase_   ).permute(0				,3				,1				,2   ).contiguous()

					_lowercase				: List[str]     =   hidden_states + residual
			elif self.is_input_vectorized:
					_lowercase				: int     =   self.norm_out(UpperCAmelCase_   )
					_lowercase				: List[str]     =   self.out(UpperCAmelCase_   )
					# (batch, self.num_vector_embeds - 1, self.num_latent_pixels)
					_lowercase				: List[Any]     =   logits.permute(0				,2				,1   )

					# log(p(x_0))
					_lowercase				: List[Any]     =   F.log_softmax(logits.double()				,dim=1   ).float()
			elif self.is_input_patches:
					# TODO: cleanup!
					_lowercase				: List[Any]     =   self.transformer_blocks[0].norma.emb(
					    UpperCAmelCase_				,UpperCAmelCase_				,hidden_dtype=hidden_states.dtype   )
					_lowercase     ,  _lowercase				: Dict     =   self.proj_out_a(F.silu(UpperCAmelCase_   )   ).chunk(2				,dim=1   )
					_lowercase				: int     =   self.norm_out(UpperCAmelCase_   ) * (1 + scale[:, None]) + shift[:, None]
					_lowercase				: int     =   self.proj_out_a(UpperCAmelCase_   )

					# unpatchify
					_lowercase				: Optional[Any]     =   int(hidden_states.shape[1] ** 0.5   )
					_lowercase				: Union[str, Any]     =   hidden_states.reshape(
					    shape=(-1, height, width, self.patch_size, self.patch_size, self.out_channels)   )
					_lowercase				: List[Any]     =   torch.einsum("""nhwpqc->nchpwq"""				,UpperCAmelCase_   )
					_lowercase				: Optional[Any]     =   hidden_states.reshape(
					    shape=(-1, self.out_channels, height * self.patch_size, width * self.patch_size)   )

			if not return_dict:
					return (output,)

			return TransformeraDModelOutput(sample=UpperCAmelCase_   )











from __future__ import annotations







def 						_UpperCamelCase (     UpperCamelCase_							:       list[int]		)	-> list[int]:

						"""simple docstring"""



						if not list_of_ints:
												return []

						if min(UpperCamelCase_		) < 0:
												raise ValueError('All numbers must be positive'		)

						lowerCAmelCase__         =    max(len(bin(UpperCamelCase_		)[2:]		) for x in list_of_ints		)
						return _msd_radix_sort(UpperCamelCase_     ,							UpperCamelCase_		)







def 						_UpperCamelCase (     UpperCamelCase_							:       list[int]     ,							UpperCamelCase_							:       int		)	-> list[int]:

						"""simple docstring"""



						if bit_position == 0 or len(UpperCamelCase_		) in [0, 1]:
												return list_of_ints

						lowerCAmelCase__         =    []
						lowerCAmelCase__         =    []
						# Split numbers based on bit at bit_position from the right
						for number in list_of_ints:
												if (number >> (bit_position - 1)) & 1:
																		# number has a one at bit bit_position
																		ones.append(UpperCamelCase_		)
												else:
																		# number has a zero at bit bit_position
																		zeros.append(UpperCamelCase_		)

    # recursively split both lists further
						lowerCAmelCase__         =    _msd_radix_sort(UpperCamelCase_     ,							bit_position - 1		)
						lowerCAmelCase__         =    _msd_radix_sort(UpperCamelCase_     ,							bit_position - 1		)

						# recombine lists
						lowerCAmelCase__         =    zeros
						res.extend(UpperCamelCase_		)

						return res







def 						_UpperCamelCase (     UpperCamelCase_							:       list[int]		)	-> Any:

						"""simple docstring"""



						lowerCAmelCase__         =    len(UpperCamelCase_		)
						if not list_of_ints or length == 1:
												return

						if min(UpperCamelCase_		) < 0:
												raise ValueError('All numbers must be positive'		)

						lowerCAmelCase__         =    max(len(bin(UpperCamelCase_		)[2:]		) for x in list_of_ints		)
						_msd_radix_sort_inplace(UpperCamelCase_     ,							UpperCamelCase_     ,							0     ,							UpperCamelCase_		)







def 						_UpperCamelCase (     UpperCamelCase_							:       list[int]     ,							UpperCamelCase_							:       int     ,							UpperCamelCase_							:       int     ,							UpperCamelCase_							:       int		)	-> int:

						"""simple docstring"""



						if bit_position == 0 or end_index - begin_index <= 1:
												return

						bit_position -= 1

						lowerCAmelCase__         =    begin_index
						lowerCAmelCase__         =    end_index - 1
						while i <= j:
												lowerCAmelCase__         =    False
												if not (list_of_ints[i] >> bit_position) & 1:
																		# found zero at the beginning
																		i += 1
																		lowerCAmelCase__         =    True
												if (list_of_ints[j] >> bit_position) & 1:
																		# found one at the end
																		j -= 1
																		lowerCAmelCase__         =    True

												if changed:
																		continue

												lowerCAmelCase__    ,							lowerCAmelCase__         =    list_of_ints[j], list_of_ints[i]
												j -= 1
												if j != i:
																		i += 1

						_msd_radix_sort_inplace(UpperCamelCase_     ,							UpperCamelCase_     ,							UpperCamelCase_     ,							UpperCamelCase_		)
						_msd_radix_sort_inplace(UpperCamelCase_     ,							UpperCamelCase_     ,							UpperCamelCase_     ,							UpperCamelCase_		)


if __name__ == "__main__":
					import doctest

					doctest.testmod()





